Programs & Examples On #Jdbc odbc

The JDBC-ODBC Bridge enables Java applications to access ODBC data sources through the JDBC interface.

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Java program to connect to Sql Server and running the sample query From Eclipse

Just Change the query like this:

SELECT TOP 1 * FROM [HumanResources].[Employee]

where Employee is your table name and HumanResources is your Schema name if I am not wrong.

Hope your problem will be resolved. :)

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

add these dependecies to your .pom file:

<dependency>
  <groupId>org.hsqldb</groupId>
  <artifactId>hsqldb</artifactId>
  <version>2.5.0</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>com.healthmarketscience.jackcess</groupId>
  <artifactId>jackcess-encrypt</artifactId>
  <version>3.0.0</version>
</dependency>

<dependency>
  <groupId>net.sf.ucanaccess</groupId>
  <artifactId>ucanaccess</artifactId>
  <version>5.0.0</version>
</dependency>

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>

<dependency>
  <groupId>commons-logging</groupId>
  <artifactId>commons-logging</artifactId>
  <version>1.2</version>
</dependency>

and add to your code to call a driver:

Connection conn = DriverManager.getConnection("jdbc:ucanaccess://{file_location}/{accessdb_file_name.mdb};memory=false");

Regex date format validation on Java

This will do it regex: "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$" This will take care of valid formats and valid dates. It will not validate the correct days of the month i.e. leap year.

String regex = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$";

Assert.assertTrue("Date: matched.", Pattern.matches(regex, "2011-1-1"));
Assert.assertFalse("Date (month): not matched.", Pattern.matches(regex, "2011-13-1"));

Good luck!

MySQL Fire Trigger for both Insert and Update

unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle

How do I display Ruby on Rails form validation error messages one at a time?

ActiveRecord stores validation errors in an array called errors. If you have a User model then you would access the validation errors in a given instance like so:

@user = User.create[params[:user]] # create will automatically call validators

if @user.errors.any? # If there are errors, do something

  # You can iterate through all messages by attribute type and validation message
  # This will be something like:
  # attribute = 'name'
  # message = 'cannot be left blank'
  @user.errors.each do |attribute, message|
    # do stuff for each error
  end

  # Or if you prefer, you can get the full message in single string, like so:
  # message = 'Name cannot be left blank'
  @users.errors.full_messages.each do |message|
    # do stuff for each error
  end

  # To get all errors associated with a single attribute, do the following:
  if @user.errors.include?(:name)
    name_errors = @user.errors[:name]

    if name_errors.kind_of?(Array)
      name_errors.each do |error|
        # do stuff for each error on the name attribute
      end
    else
      error = name_errors
      # do stuff for the one error on the name attribute.
    end
  end
end

Of course you can also do any of this in the views instead of the controller, should you want to just display the first error to the user or something.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

I faced the same problem, I added android support design dependencies to the app level build.gradle

Add following:

implementation 'com.android.support:design:27.1.0'

in build.gradle. Now its working for me.

How do you post to the wall on a facebook page (not profile)

You can make api calls by choosing the HTTP method and setting optional parameters:

$facebook->api('/me/feed/', 'post', array(
    'message' => 'I want to display this message on my wall'
));

Submit Post to Facebook Wall :

Include the fbConfig.php file to connect Facebook API and get the access token.

Post message, name, link, description, and the picture will be submitted to Facebook wall. Post submission status will be shown.

If FB access token ($accessToken) is not available, the Facebook Login URL will be generated and the user would be redirected to the FB login page.

Post to facebook wall php sdk

<?php
//Include FB config file
require_once 'fbConfig.php';

if(isset($accessToken)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }else{
        // Put short-lived access token in session
        $_SESSION['facebook_access_token'] = (string) $accessToken;

        // OAuth 2.0 client handler helps to manage access tokens
        $oAuth2Client = $fb->getOAuth2Client();

        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

        // Set default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }

    //FB post content
    $message = 'Test message from CodexWorld.com website';
    $title = 'Post From Website';
    $link = 'http://www.codexworld.com/';
    $description = 'CodexWorld is a programming blog.';
    $picture = 'http://www.codexworld.com/wp-content/uploads/2015/12/www-codexworld-com-programming-blog.png';

    $attachment = array(
        'message' => $message,
        'name' => $title,
        'link' => $link,
        'description' => $description,
        'picture'=>$picture,
    );

    try{
        //Post to Facebook
        $fb->post('/me/feed', $attachment, $accessToken);

        //Display post submission status
        echo 'The post was submitted successfully to Facebook timeline.';
    }catch(FacebookResponseException $e){
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    }catch(FacebookSDKException $e){
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }
}else{
    //Get FB login URL
    $fbLoginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);

    //Redirect to FB login
    header("Location:".$fbLoginURL);
}

Refrences:

https://github.com/facebookarchive/facebook-php-sdk

https://developers.facebook.com/docs/pages/publishing/

https://developers.facebook.com/docs/php/gettingstarted

http://www.pontikis.net/blog/auto_post_on_facebook_with_php

https://www.codexworld.com/post-to-facebook-wall-from-website-php-sdk/

Private vs Protected - Visibility Good-Practice Concern

No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.

If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.

A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Have you looked under Advanced Security Settings?

something like below image change permissions of folder to IIS_IUSRS

enter image description here

Posting array from form

What you are doing is not necessarily bad practice but it does however require an extraordinary amount of typing. I would accomplish what you are trying to do like this.

foreach($_POST as $var => $val){
    $$var = $val;
}

This will take all the POST variables and put them in their own individual variables. So if you have a input field named email and the luser puts in [email protected] you will have a var named $email with a value of "[email protected]".

vertical divider between two columns in bootstrap

Well what I did was remove the gutter between the respective spans then drawing a left border for the left span and a right border for the right span in such a way that their borders overlapped just to give a single line. This way the visible line will just be one of borders.

CSS

.leftspan
{
padding-right:20px;
border-right: 1px solid #ccc;
}

.row-fluid .rightspan {
margin-left: -0.138297872340425%;
*margin-left: -0.13191489361702%;
padding-left:20px;
border-left: 1px solid #ccc;
}

.row-fluid .rightspan:first-child {
margin-left: -0.11063829787234%;
*margin-left: -0.104255319148938%;
}

HTML

  <div class="row-fluid" >
      <div class="span8 leftspan" >
      </div>

      <div class="span4 rightspan"  >
      </div>
 </div>

Try this it works for me

The system cannot find the file specified. in Visual Studio

The code should be :

#include <iostream>
using namespace std;

int main() {
    cout << "Hello World";
    return 0;
}

Or maybe :

#include <iostream>

int main() {
    std::cout << "Hello World";
    return 0;
}

Just a quick note: I have deleted the system command, because I heard it's not a good practice to use it. (but of course, you can add it for this kind of program)

RabbitMQ / AMQP: single queue, multiple consumers for same message?

The send pattern is a one-to-one relationship. If you want to "send" to more than one receiver you should be using the pub/sub pattern. See http://www.rabbitmq.com/tutorials/tutorial-three-python.html for more details.

filtering NSArray into a new NSArray in Objective-C

The Best and easy Way is to create this method And Pass Array And Value:

- (NSArray *) filter:(NSArray *)array where:(NSString *)key is:(id)value{
    NSMutableArray *temArr=[[NSMutableArray alloc] init];
    for(NSDictionary *dic in self)
        if([dic[key] isEqual:value])
            [temArr addObject:dic];
    return temArr;
}

What's the best way to limit text length of EditText in Android

For anyone else wondering how to achieve this, here is my extended EditText class EditTextNumeric.

.setMaxLength(int) - sets maximum number of digits

.setMaxValue(int) - limit maximum integer value

.setMin(int) - limit minimum integer value

.getValue() - get integer value

import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;

public class EditTextNumeric extends EditText {
    protected int max_value = Integer.MAX_VALUE;
    protected int min_value = Integer.MIN_VALUE;

    // constructor
    public EditTextNumeric(Context context) {
        super(context);
        this.setInputType(InputType.TYPE_CLASS_NUMBER);
    }

    // checks whether the limits are set and corrects them if not within limits
    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        if (max_value != Integer.MAX_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) > max_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(max_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        if (min_value != Integer.MIN_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) < min_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(min_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        super.onTextChanged(text, start, before, after);
    }

    // set the max number of digits the user can enter
    public void setMaxLength(int length) {
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(length);
        this.setFilters(FilterArray);
    }

    // set the maximum integer value the user can enter.
    // if exeeded, input value will become equal to the set limit
    public void setMaxValue(int value) {
        max_value = value;
    }
    // set the minimum integer value the user can enter.
    // if entered value is inferior, input value will become equal to the set limit
    public void setMinValue(int value) {
        min_value = value;
    }

    // returns integer value or 0 if errorous value
    public int getValue() {
        try {
            return Integer.parseInt(this.getText().toString());
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}

Example usage:

final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);

All other methods and attributes that apply to EditText, of course work too.

Xcode project not showing list of simulators

Deployment Target version change to a lower one helped for me:

Window -> Devices and Simulators -> Simulators. Check what are the latest versions of existing simulators.

simulators

Then go to your project's Target. Under Deployment Info, change Target to the version you saw the latest within your simulators. Mine was set to iOS 13.6 when the simulator was iOS 13.5 only.

deployment-target

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

What is meant by Ems? (Android TextView)

em is basically CSS property for font sizes.

The em and ex units depend on the font and may be different for each element in the document. The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as text-indent: 1.5em and margin: 1em are extremely common in CSS.

Source:https://www.w3.org/Style/Examples/007/units

Insert, on duplicate update in PostgreSQL?

I custom "upsert" function above, if you want to INSERT AND REPLACE :

`

 CREATE OR REPLACE FUNCTION upsert(sql_insert text, sql_update text)

 RETURNS void AS
 $BODY$
 BEGIN
    -- first try to insert and after to update. Note : insert has pk and update not...

    EXECUTE sql_insert;
    RETURN;
    EXCEPTION WHEN unique_violation THEN
    EXECUTE sql_update; 
    IF FOUND THEN 
        RETURN; 
    END IF;
 END;
 $BODY$
 LANGUAGE plpgsql VOLATILE
 COST 100;
 ALTER FUNCTION upsert(text, text)
 OWNER TO postgres;`

And after to execute, do something like this :

SELECT upsert($$INSERT INTO ...$$,$$UPDATE... $$)

Is important to put double dollar-comma to avoid compiler errors

  • check the speed...

Async always WaitingForActivation

I overcome this issue with if anybody interested. In myMain method i called my readasync method like

Dispatcher.BeginInvoke(new ThreadStart(() => ReadData()));

Everything is fine for me now.

How to make g++ search for header files in a specific directory?

it's simple, use the "-B" option to add .h files' dir to search path.

E.g. g++ -B /header_file.h your.cpp -o bin/your_command

Freeing up a TCP/IP port?

In terminal type :

netstat -anp|grep "port_number"

It will show the port details. Go to last column. It will be in this format . For example :- PID/java

then execute :

kill -9 PID. Worked on Centos5

For MAC:

lsof -n -i :'port-number' | grep LISTEN

Sample Response :

java   4744 (PID)  test  364u  IP0 asdasdasda   0t0  TCP *:port-number (LISTEN)

and then execute :

kill -9 PID 

Worked on Macbook

Checking to see if one array's elements are in another array in PHP

You could also use in_array as follows:

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
foreach($people as $num) {
    if (in_array($num,$criminals)) {
        $found[$num] = true;
    } 
}
var_dump($found);
// array(2) { [20]=> bool(true)   [2]=> bool(true) }

While array_intersect is certainly more convenient to use, it turns out that its not really superior in terms of performance. I created this script too:

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
$fastfind = array_intersect($people,$criminals);
var_dump($fastfind);
// array(2) { [1]=> int(20)   [2]=> int(2) }

Then, I ran both snippets respectively at: http://3v4l.org/WGhO7/perf#tabs and http://3v4l.org/g1Hnu/perf#tabs and checked the performance of each. The interesting thing is that the total CPU time, i.e. user time + system time is the same for PHP5.6 and the memory also is the same. The total CPU time under PHP5.4 is less for in_array than array_intersect, albeit marginally so.

How to get the selected date value while using Bootstrap Datepicker?

I tried with the above answers, but they didn't worked out for me; So as user3475960 referred, I used $('#startdate').html() which gave me the html text so i used it as necessary... May be some one will make use of it..

How to strip HTML tags from string in JavaScript?

I know this question has an accepted answer, but I feel that it doesn't work in all cases.

For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):

http://phpjs.org/functions/strip_tags:535

It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script /> tag above.

Android Canvas: drawing too large bitmap

Move your image in the (hi-res) drawable to drawable-xxhdpi. But in app development, you do not need to use large image. It will increase your APK file size.

How to send email in ASP.NET C#

Just pass parameter like body - The content(query) from the customer
subject - subject that defined in mail subject
username - nothing name anything
mail - mail (required)

   public static bool SendMail(String body, String subject, string username, String mail)
    {
        bool isSendSuccess = false;
        try
        {
            var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
            var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
            var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
            var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();


            MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName),
                new MailAddress(mail, username));
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = body;

            var client = new SmtpClient();
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
            client.Host = smtpHost;
            client.EnableSsl = false;
            client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
            client.Send(message);
            isSendSuccess = true;
        }
        catch (Exception ex)
        {
            throw (new Exception("Mail send failed to loginId " + mail + ", though registration done."+ex.ToString()+"\n"+ex.StackTrace));
        }

        return isSendSuccess;
    }

if your using go daddy server this work . add this in web.config

  <appSettings>
    ---other ---setting

    <add key="FromEmailAddress" value="[email protected]" />
    <add key="FromEmailDisplayName" value="anyname" />
    <add key="FromEmailPassword" value="mypassword@" />
    <add key="SMTPHost" value="relay-hosting.secureserver.net" />
    <add key="SMTPPort" value="25" />

</appSettings>

if you are using localhost or vps server change this configuration to this

 <appSettings>
    ---other ---setting

    <add key="FromEmailAddress" value="[email protected]" />
    <add key="FromEmailDisplayName" value="anyname" />
    <add key="FromEmailPassword" value="mypassword@" />
    <add key="SMTPHost" value="smtp.gmail.com" /> 
    <add key="SMTPPort" value="587" />
</appSettings>

change the code

          client.EnableSsl = true;

if your are using gmail please enable secure app. using this link https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4Pd6h3XxE663Flvd-FfeRXxW_eNrIsGTBlZklgkAHZEeuHvheCQuZ1-djB9uIWaB-2EV7hyLCU0dWKA7D0JzYKe4ZRkuA

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

You have set your %JAVA_HOME to jdk 1.7, but you are trying to compile using 1.8. Install jdk 1.8 and make sure your %JAVA_HOME points to that or drop the target release to 1.7.

invalid target release: 1.8

The target release refers to the jdk version.

Override devise registrations controller

A better and more organized way of overriding Devise controllers and views using namespaces:

Create the following folders:

app/controllers/my_devise
app/views/my_devise

Put all controllers that you want to override into app/controllers/my_devise and add MyDevise namespace to controller class names. Registrations example:

# app/controllers/my_devise/registrations_controller.rb
class MyDevise::RegistrationsController < Devise::RegistrationsController

  ...

  def create
    # add custom create logic here
  end

  ...    

end 

Change your routes accordingly:

devise_for :users,
           :controllers  => {
             :registrations => 'my_devise/registrations',
             # ...
           }

Copy all required views into app/views/my_devise from Devise gem folder or use rails generate devise:views, delete the views you are not overriding and rename devise folder to my_devise.

This way you will have everything neatly organized in two folders.

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

How can I store HashMap<String, ArrayList<String>> inside a list?

First you need to define the List as :

List<Map<String, ArrayList<String>>> list = new ArrayList<>();

To add the Map to the List , use add(E e) method :

list.add(map);

img onclick call to JavaScript function

Well your onclick function works absolutely fine its your this line
window.external.values(a.value, b.value, c.value, d.value, e.value);

window.external is object and has no method name values

<html>
    <head>
     <script type="text/javascript">
          function exportToForm(a,b,c,d,e) {
             // window.external.values(a.value, b.value, c.value, d.value, e.value);
          //use alert to check its working 
         alert("HELLO");
}
      </script>
    </head>
    <body>
      <img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
      <button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
    </body>

    </html>

SQL Server FOR EACH Loop

Off course an old question. But I have a simple solution where no need of Looping, CTE, Table variables etc.

DECLARE @MyVar datetime = '1/1/2010'    
SELECT @MyVar

SELECT DATEADD (DD,NUMBER,@MyVar) 
FROM master.dbo.spt_values 
WHERE TYPE='P' AND NUMBER BETWEEN 0 AND 4 
ORDER BY NUMBER

Note : spt_values is a Mircrosoft's undocumented table. It has numbers for every type. Its not suggestible to use as it can be removed in any new versions of sql server without prior information, since it is undocumented. But we can use it as quick workaround in some scenario's like above.

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

In HTML5, should the main navigation be inside or outside the <header> element?

It's completely up to you. You can either put them in the header or not, as long as the elements within them are internal navigation elements only (i.e. don't link to external sites such as a twitter or facebook account) then it's fine.

They tend to get placed in a header simply because that's where navigation often goes, but it's not set in stone.

You can read more about it at HTML5 Doctor.

Float a DIV on top of another DIV

Use this css

.close-image {
    cursor: pointer;
    z-index: 3;
    right: 5px;
    top: 5px;
    position: absolute;
}

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I tried the steps mentioned by @bcmoney but for me the current version was already set to the latest version. In my it was Java8.

I had various versions of java installed (java6, java7 and java8). I got the same error but instead of 1.5 and 1.7 i got 1.7 and 1.8. I uninstalled java6 on my windows 8.1 machine. After which i tried java -version in command prompt and the error did not appear.

I am not sure whether this is the right answer but it worked for me so i thought it would help the community too.

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

How to clear the text of all textBoxes in the form?

And this for clearing all controls in form like textbox, checkbox, radioButton

you can add different types you want..

private void ClearTextBoxes(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Clear();
            }

            if (c.HasChildren)
            {
                ClearTextBoxes(c);
            }


            if (c is CheckBox)
            {

                ((CheckBox)c).Checked = false;
            }

            if (c is RadioButton)
            {
                ((RadioButton)c).Checked = false;
            }
        }
    }

DateTime.TryParseExact() rejecting valid formats

Here you can check for couple of things.

  1. Date formats you are using correctly. You can provide more than one format for DateTime.TryParseExact. Check the complete list of formats, available here.
  2. CultureInfo.InvariantCulture which is more likely add problem. So instead of passing a NULL value or setting it to CultureInfo provider = new CultureInfo("en-US"), you may write it like. .

    if (!DateTime.TryParseExact(txtStartDate.Text, formats, 
                    System.Globalization.CultureInfo.InvariantCulture,
                    System.Globalization.DateTimeStyles.None, out startDate))
    {
        //your condition fail code goes here
        return false;
    }
    else
    {
        //success code
    }
    

Simple Android RecyclerView example

Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.

val items = mutableListOf<String>()

inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
    var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    rvitems.layoutManager = LinearLayoutManager(context)
    rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
            return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
        }

        override fun getItemCount(): Int {
            return items.size
        }

        override fun onBindViewHolder(holder: ItemHolder, position: Int) {
            holder.textField.text = items[position]
            holder.textField.setOnClickListener {
                Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.

Why are my CSS3 media queries not working on mobile devices?

Throwing another answer into the ring. If you're trying to use CSS variables, then it will quietly fail.

@media screen and (max-device-width: var(--breakpoint-small)) {}

CSS variables don't work in media queries (by design).

FPDF utf-8 encoding (HOW-TO)

Don't use UTF-8 encoding. Standard FPDF fonts use ISO-8859-1 or Windows-1252. It is possible to perform a conversion to ISO-8859-1 with utf8_decode(): $str = utf8_decode($str); But some characters such as Euro won't be translated correctly. If the iconv extension is available, the right way to do it is the following: $str = iconv('UTF-8', 'windows-1252', $str);

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

It means you don't have privileges to create the trigger with root@localhost user..

try removing definer from the trigger command:

CREATE DEFINER = root@localhost FUNCTION fnc_calcWalkedDistance

how to set active class to nav menu from twitter bootstrap

For single-page sites where the menu items simply jump down to other sections of the page, this simple solution works for me:

$('.nav li').on('click', function(){
    $('.nav li').removeClass('active');
    $(this).addClass('active');
  });

How can I remove the search bar and footer added by the jQuery DataTables plugin?

var table = $("#datatable").DataTable({
   "paging": false,
   "ordering": false,
   "searching": false
});

How do I reset a jquery-chosen select option with jQuery?

If you are using chosen, a jquery plugin, then to refresh or clear the content of the dropdown use:

$('#dropdown_id').empty().append($('< option>'))

dropdown_id.chosen().trigger("chosen:updated")

chosen:updated event will re-build itself based on the updated content.

PHP isset() with multiple parameters

Use the php's OR (||) logical operator for php isset() with multiple operator e.g

if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {

}

@angular/material/index.d.ts' is not a module

And also ng update @angular/material will update your code and fix all imports

Twitter bootstrap scrollable modal

Your modal is being hidden in firefox, and that is because of the negative margin declaration you have inside your general stylesheet:

.modal {
    margin-top: -45%; /* remove this */
    max-height: 90%;
    overflow-y: auto;
}

Remove the negative margin and everything works just fine.

mysql command for showing current configuration variables

As an alternative you can also query the information_schema database and retrieve the data from the global_variables (and global_status of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.

For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size in bytes and megabytes:

SELECT
  variable_name,
  variable_value AS innodb_log_buffer_size_bytes,
  ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE  'innodb_log_buffer_size';

As a result you get:

+------------------------+------------------------------+---------------------------+
| variable_name          | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456                    |                       256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)

Wait for a void async method

If you can change the signature of your function to async Task then you can use the code presented here

Making an API call in Python with an API that requires a bearer token

If you are using requests module, an alternative option is to write an auth class, as discussed in "New Forms of Authentication":

import requests

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

and then can you send requests like this

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))

which allows you to use the same auth argument just like basic auth, and may help you in certain situations.

How to add a single item to a Pandas Series

How to add single item. This is not very effective but follows what you are asking for:

x = p.Series()
N = 4
for i in xrange(N):
   x = x.set_value(i, i**2)

produces x:

0    0
1    1
2    4
3    9

Obviously there are better ways to generate this series in only one shot.

For your second question check answer and references of SO question add one row in a pandas.DataFrame.

How can I get the current screen orientation?

I just want to propose another alternative that will concern some of you :

android:configChanges="orientation|keyboardHidden" 

implies that we explicitly declare the layout to be injected.

In case we want to keep the automatic injection thanks to the layout-land and layout folders. All you have to do is add it to the onCreate:

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        getSupportActionBar().hide();

    } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        getSupportActionBar().show();
    }

Here, we display or not the actionbar depending on the orientation of the phone

isPrime Function for Python Language

Finding the square root of the number is for efficiency. eg. if I am trying to find the factors of 36, the highest number that can be multiplied by itself to form 36 is 6. 7*7 = 49.

therefore every factor of 36 has to be multiplied by 6 or a lesser number.

Angular ng-if not true

use this

ng-if="area == false"

OR

ng-if="area == true"

this may help someone

Handling NULL values in Hive

What is the datatype for column1 in your Hive table? Please note that if your column is STRING it won't be having a NULL value even though your external file does not have any data for that column.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Load HTML page dynamically into div with jQuery

Try with this one:

$(document).ready(function(){
  $('a').click(function(e){
     e.preventDefault();
     $("#content").load($(this).attr('href'));
  });
});

and make sure to call this library first:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>

Change the mouse cursor on mouse over to anchor-like style

I think :hover was missing in above answers. So following would do the needful.(if css was required)

#myDiv:hover
{
    cursor: pointer;
}

Copy Image from Remote Server Over HTTP

use

$imageString = file_get_contents("http://example.com/image.jpg");
$save = file_put_contents('Image/saveto/image.jpg',$imageString);

How to extract year and month from date in PostgreSQL without using to_char() function?

It is working for "greater than" functions not for less than.

For example:

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) > '2000' limit 10;

is working fine.

but for

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) < '2000' limit 10;

I am getting error.

In Typescript, How to check if a string is Numeric

Simple answer: (watch for blank & null)

isNaN(+'111') = false;
isNaN(+'111r') = true;
isNaN(+'r') = true;
isNaN(+'') = false;   
isNaN(null) = false;   

https://codepen.io/CQCoder/pen/zYGEjxd?editors=1111

Create hyperlink to another sheet

In my implementation, the cell I was referencing could have been several options. I used the following format where 'ws' is the current worksheet being edited

For each ws in Activeworkbook.Worksheets
    For i…
       For j...
...
ws.Cells(i, j).Value = "=HYPERLINK(""#'" & SHEET-REF-VAR & "'!" & CELL-REF-VAR & """,""" & SHEET-REF-VAR & """)"

Why use a READ UNCOMMITTED isolation level?

The advantage is that it can be faster in some situations. The disadvantage is the result can be wrong (data which hasn't been committed yet could be returned) and there is no guarantee that the result is repeatable.

If you care about accuracy, don't use this.

More information is on MSDN:

Implements dirty read, or isolation level 0 locking, which means that no shared locks are issued and no exclusive locks are honored. When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. This option has the same effect as setting NOLOCK on all tables in all SELECT statements in a transaction. This is the least restrictive of the four isolation levels.

How do I get started with Node.js

First, learn the core concepts of Node.js:

Then, you're going to want to see what the community has to offer:

The gold standard for Node.js package management is NPM.

Finally, you're going to want to know what some of the more popular packages are for various tasks:

Useful Tools for Every Project:

  • Underscore contains just about every core utility method you want.
  • Lo-Dash is a clone of Underscore that aims to be faster, more customizable, and has quite a few functions that underscore doesn't have. Certain versions of it can be used as drop-in replacements of underscore.
  • TypeScript makes JavaScript considerably more bearable, while also keeping you out of trouble!
  • JSHint is a code-checking tool that'll save you loads of time finding stupid errors. Find a plugin for your text editor that will automatically run it on your code.

Unit Testing:

  • Mocha is a popular test framework.
  • Vows is a fantastic take on asynchronous testing, albeit somewhat stale.
  • Expresso is a more traditional unit testing framework.
  • node-unit is another relatively traditional unit testing framework.
  • AVA is a new test runner with Babel built-in and runs tests concurrently.

Web Frameworks:

  • Express.js is by far the most popular framework.
  • Koa is a new web framework designed by the team behind Express.js, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
  • sails.js the most popular MVC framework for Node.js, and is based on express. It is designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture.
  • Meteor bundles together jQuery, Handlebars, Node.js, WebSocket, MongoDB, and DDP and promotes convention over configuration without being a Ruby on Rails clone.
  • Tower (deprecated) is an abstraction of a top of Express.js that aims to be a Ruby on Rails clone.
  • Geddy is another take on web frameworks.
  • RailwayJS is a Ruby on Rails inspired MVC web framework.
  • Sleek.js is a simple web framework, built upon Express.js.
  • Hapi is a configuration-centric framework with built-in support for input validation, caching, authentication, etc.
  • Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.

  • Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.

  • Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.

  • Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.

Web Framework Tools:

Networking:

  • Connect is the Rack or WSGI of the Node.js world.
  • Request is a very popular HTTP request library.
  • socket.io is handy for building WebSocket servers.

Command Line Interaction:

  • minimist just command line argument parsing.
  • Yargs is a powerful library for parsing command-line arguments.
  • Commander.js is a complete solution for building single-use command-line applications.
  • Vorpal.js is a framework for building mature, immersive command-line applications.
  • Chalk makes your CLI output pretty.

Code Generators:

  • Yeoman Scaffolding tool from the command-line.
  • Skaffolder Code generator with visual and command-line interface. It generates a customizable CRUD application starting from the database schema or an OpenAPI 3.0 YAML file.

Work with streams:

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

Find and replace Android studio

ctrl + H ..... its give option to replace word from class.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

How to sort a list of strings?

The proper way to sort strings is:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

The previous example of mylist.sort(key=lambda x: x.lower()) will work fine for ASCII-only contexts.

Difference between WebStorm and PHPStorm

Essentially, PHPStorm = WebStorm + PHP, SQL and more.

BUT (and this is a very important "but") because it is capable of parsing so much more, it quite often fails to parse Node.js dependencies, as they (probably) conflict with some other syntax it is capable of parsing.

The most notable example of that would be Mongoose model definition, where WebStorm easily recognizes mongoose.model method, whereas PHPStorm marks it as unresolved as soon as you connect Node.js plugin.

Surprisingly, it manages to resolve the method if you turn the plugin off, but leave the core modules connected, but then it cannot be used for debugging. And this happens to quite a few methods out there.

All this goes for PHPStorm 8.0.1, maybe in later releases this annoying bug would be fixed.

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

Converting Secret Key into a String and Vice Versa

You don't want to use .toString().

Notice that SecretKey inherits from java.security.Key, which itself inherits from Serializable. So the key here (no pun intended) is to serialize the key into a ByteArrayOutputStream, get the byte[] array and store it into the db. The reverse process would be to get the byte[] array off the db, create a ByteArrayInputStream offf the byte[] array, and deserialize the SecretKey off it...

... or even simpler, just use the .getEncoded() method inherited from java.security.Key (which is a parent interface of SecretKey). This method returns the encoded byte[] array off Key/SecretKey, which you can store or retrieve from the database.

This is all assuming your SecretKey implementation supports encoding. Otherwise, getEncoded() will return null.

edit:

You should look at the Key/SecretKey javadocs (available right at the start of a google page):

http://download.oracle.com/javase/6/docs/api/java/security/Key.html

Or this from CodeRanch (also found with the same google search):

http://www.coderanch.com/t/429127/java/java/Convertion-between-SecretKey-String-or

Make a dictionary with duplicate keys in Python

If you want to have lists only when they are necessary, and values in any other cases, then you can do this:

class DictList(dict):
    def __setitem__(self, key, value):
        try:
            # Assumes there is a list on the key
            self[key].append(value)
        except KeyError: # If it fails, because there is no key
            super(DictList, self).__setitem__(key, value)
        except AttributeError: # If it fails because it is not a list
            super(DictList, self).__setitem__(key, [self[key], value])

You can then do the following:

dl = DictList()
dl['a']  = 1
dl['b']  = 2
dl['b'] = 3

Which will store the following {'a': 1, 'b': [2, 3]}.


I tend to use this implementation when I want to have reverse/inverse dictionaries, in which case I simply do:

my_dict = {1: 'a', 2: 'b', 3: 'b'}
rev = DictList()
for k, v in my_dict.items():
    rev_med[v] = k

Which will generate the same output as above: {'a': 1, 'b': [2, 3]}.


CAVEAT: This implementation relies on the non-existence of the append method (in the values you are storing). This might produce unexpected results if the values you are storing are lists. For example,

dl = DictList()
dl['a']  = 1
dl['b']  = [2]
dl['b'] = 3

would produce the same result as before {'a': 1, 'b': [2, 3]}, but one might expected the following: {'a': 1, 'b': [[2], 3]}.

Pretty printing XML with javascript

var formatXml = this.formatXml = function (xml) {
        var reg = /(>)(<)(\/*)/g;
        var wsexp = / *(.*) +\n/g;
        var contexp = /(<.+>)(.+\n)/g;
        xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
        var pad = 0;
        var formatted = '';
        var lines = xml.split('\n');
        var indent = 0;
        var lastType = 'other';

ASP.Net MVC How to pass data from view to controller

In case you don't want/need to post:

@Html.ActionLink("link caption", "actionName", new { Model.Page })  // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);

[HttpGet]
public ActionResult actionName(int reportID)
{

Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)

Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.

element not interactable exception in selenium web automation

In my case the element that generated the Exception was a button belonging to a form. I replaced

WebElement btnLogin = driver.findElement(By.cssSelector("button"));
btnLogin.click();

with

btnLogin.submit();

My environment was chromedriver windows 10

Android Studio and Gradle build error

I used a local distribution of gradle downloaded from gradle website and used it in android studio.

It fixed the gradle build error.

.datepicker('setdate') issues, in jQuery

Try changing it to:

queryDate = '2009-11-01';
$('#datePicker').datepicker({defaultDate: new Date (queryDate)});

Edit Crystal report file without Crystal Report software

I wouldn't have thought so.

If you have Visual Studio you could edit them through that. Some versions of Visual Studio has Crystal Reports shipped with them.

If not, you will have to find someone who has Crystal Reports and ask then nicely to amend them for you. Or buy Crystal Reports!

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

tooltips for Button

You should use both title and alt attributes to make it work in all browsers.

<button title="Hello World!" alt="Hello World!">Sample Button</button>

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

After changing the main port 80 to 8080 you have to update the port in the control panel: enter image description here Then click here: enter image description here And here: enter image description here Then save and restart.

Explaining Python's '__enter__' and '__exit__'

I found it strangely difficult to locate the python docs for __enter__ and __exit__ methods by Googling, so to help others here is the link:

https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers
https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers
(detail is the same for both versions)

object.__enter__(self)
Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

object.__exit__(self, exc_type, exc_value, traceback)
Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.

Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.

I was hoping for a clear description of the __exit__ method arguments. This is lacking but we can deduce them...

Presumably exc_type is the class of the exception.

It says you should not re-raise the passed-in exception. This suggests to us that one of the arguments might be an actual Exception instance ...or maybe you're supposed to instantiate it yourself from the type and value?

We can answer by looking at this article:
http://effbot.org/zone/python-with-statement.htm

For example, the following __exit__ method swallows any TypeError, but lets all other exceptions through:

def __exit__(self, type, value, traceback):
    return isinstance(value, TypeError)

...so clearly value is an Exception instance.

And presumably traceback is a Python traceback object.

Most efficient way to remove special characters from string

public string RemoveSpecial(string evalstr)
{
StringBuilder finalstr = new StringBuilder();
            foreach(char c in evalstr){
            int charassci = Convert.ToInt16(c);
            if (!(charassci >= 33 && charassci <= 47))// special char ???
             finalstr.append(c);
            }
return finalstr.ToString();
}

TypeScript getting error TS2304: cannot find name ' require'

Electron + Angular 2/4 addition:

On top of adding the 'node' type to ts.config various files, what eventually worked for me was adding the next to the typings.d.ts file:

declare var window: Window;
interface Window {
  process: any;
  require: any;
}

Note that my case is developing with Electron + Angular 2/4. I needed the require on the window global.

Remove char at specific index - python

Try this code:

s = input() 
a = int(input()) 
b = s.replace(s[a],'')
print(b)

Creating a JSON array in C#

You're close. This should do the trick:

new {items = new [] {
    new {name = "command" , index = "X", optional = "0"}, 
    new {name = "command" , index = "X", optional = "0"}
}}

If your source was an enumerable of some sort, you might want to do this:

new {items = source.Select(item => new 
{
    name = item.Name, index = item.Index, options = item.Optional
})};

C: socket connection timeout

The two socket options SO_RCVTIMEO and SO_SNDTIMEO have no effect on connect. Below is a link to the screenshot which includes this explanation, here I am just briefing it. The apt way of implementing timeouts with connect are using signal or select or poll.

Signals

connect can be interrupted by a self generated signal SIGALRM by using syscall (wrapper) alarm. But, a signal disposition should be installed for the same signal otherwise the program would be terminated. The code goes like this...

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<signal.h>
#include<errno.h>

static void signal_handler(int signo)
{
    return; // Do nothing just interrupt.
}

int main()
{
    /* Register signal handler */

    struct sigaction act, oact;

    act.sa_handler = signal_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;

#ifdef SA_INTERRUPT
    act.sa_flags |= SA_INTERRUPT;
#endif

    if(sigaction(SIGALRM, &act, &oact) < 0)  // Error registering signal handler.
    {
        fprintf(stderr, "Error registering signal disposition\n");
        exit(1);
    }

    /* Prepare your socket and sockaddr structures */

    int sockfd;
    struct sockaddr* servaddr;

    /* Implementing timeout connect */

    int sec = 30;

    if(alarm(sec) != 0)
        fprintf(stderr, "Already timer was set\n");

    if(connect(sockfd, servaddr, sizeof(struct sockaddr)) < 0)
    {
        if(errno == EINTR)
            fprintf(stderr, "Connect timeout\n");
        else
            fprintf(stderr, "Connect failed\n");

        close(sockfd);

        exit(1);
    }

    alarm(0);  /* turn off the alarm */

    sigaction(SIGALRM, &oact, NULL);  /* Restore the default actions of SIGALRM */

    /* Use socket */


    /* End program */

    close(sockfd);
    return 0;
}

Select or Poll

As already some users provided nice explanation on how to use select to achieve connect timeout, it would not be necessary for me to reiterate the same. poll can be used in the same way. However, there are few mistakes that are common in all of the answers, which I would like to address.

  • Even though socket is non-blocking, if the server to which we are connecting is on the same local machine, connect may return with success. So it is advised to check the return value of connect before calling select.

  • Berkeley-derived implementations (and POSIX) have the following rules for non-blocking sockets and connect.

    1) When the connection completes successfully, the descriptor becomes writable (p. 531 of TCPv2).

    2) When the connection establishment encounters an error, the descriptor becomes both readable and writable (p. 530 of TCPv2).

So the code should handle these cases, here I just code the necessary modifications.

/* All the code stays */

/* Modifications at connect */

int conn_ret = connect(sockfd, servaddr, sizeof(struct sockdaddr));

if(conn_ret == 0)
    goto done;

/* Modifications at select */

int sec = 30;
for( ; ; )
{
    struct timeval timeo;
    timeo.tv_sec = sec;
    timeo.tv_usec = 0;

    fd_set wr_set, rd_set;
    FDZERO(&wr_set);
    FD_SET(sockfd, &wr_set);
    rd_set = wr_set;
    int sl_ret = select(sockfd + 1, &rd_set, &wr_set, NULL, &timeo);

    /* All the code stays */
}


done:

    /* Use your socket */

Text from Unix Network Programming Volume 1

How to detect a mobile device with JavaScript?

Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:

var result = window.matchMedia("(any-pointer:coarse)").matches;

That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.

The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.

https://patrickhlauke.github.io/touch/touchscreen-detection/

Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia

In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.

UPDATE:

Using jqXHR.done(), jqXHR.fail() and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//exapmple.com//ajax.php",
        data: settings,
        cache : false
    });
}

/* .... Somewhere in your code ..... */

call_ajax({
    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    }
    /* ... */
}).done(function(data){

    /* DO SOMETHING AWESOME */

});

Most concise way to convert a Set<T> to a List<T>

List<String> list = new ArrayList<String>(listOfTopicAuthors);

When to use Spring Security`s antMatcher()?

I'm updating my answer...

antMatcher() is a method of HttpSecurity, it doesn't have anything to do with authorizeRequests(). Basically, http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

The authorizeRequests().antMatchers() is then used to apply authorization to one or more paths you specify in antMatchers(). Such as permitAll() or hasRole('USER3'). These only get applied if the first http.antMatcher() is matched.

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

foreach (var data in dynObj.quizlist)
{
    foreach (var data1 in data.QUIZ.QPROP)
    {
        Response.Write("Name" + ":" + data1.name + "<br>");
        Response.Write("Intro" + ":" + data1.intro + "<br>");
        Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");
        Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");
        Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");
        Response.Write("Noofques" + ":" + data1.noofques + "<br>");

        foreach (var queprop in data1.QUESTION.QUEPROP)
        {
            Response.Write("Questiontext" + ":" + queprop.questiontext  + "<br>");
            Response.Write("Mark" + ":" + queprop.mark  + "<br>");
        }
    }
}

req.query and req.param in ExpressJS

Passing params

GET request to "/cars/honda" 

returns a list of Honda car models

Passing query

GET request to "/car/honda?color=blue"

returns a list of Honda car models, but filtered so only models with an stock color of blue are returned.

It doesn't make sense to add those filters into the URL parameters (/car/honda/color/blue) because according to REST, that would imply that we want to get a bunch of information about the color "blue". Since what we really want is a filtered list of Honda models, we use query strings to filter down the results that get returned.

Notice that the query strings are really just { key: value } pairs in a slightly different format: ?key1=value1&key2=value2&key3=value3.

PHPDoc type hinting for array of objects?

The problem is that @var can just denote a single type - Not contain a complex formula. If you had a syntax for "array of Foo", why stop there and not add a syntax for "array of array, that contains 2 Foo's and three Bar's"? I understand that a list of elements is perhaps more generic than that, but it's a slippery slope.

Personally, I have some times used @var Foo[] to signify "an array of Foo's", but it's not supported by IDE's.

Could not extract response: no suitable HttpMessageConverter found for response type

public class Application {

    private static List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        return converters;
    }   

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        restTemplate.setMessageConverters(getMessageConverters());
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        //Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);

        ResponseEntity<Page> response = 
                  restTemplate.exchange("http://graph.facebook.com/skbh86", HttpMethod.GET, entity, Page.class, "1");
        Page page = response.getBody();
        System.out.println("Name:    " + page.getId());
        System.out.println("About:   " + page.getFirst_name());
        System.out.println("Phone:   " + page.getLast_name());
        System.out.println("Website: " + page.getMiddle_name());
        System.out.println("Website: " + page.getName());
    }
}

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

fastest MD5 Implementation in JavaScript

You could also check my md5 implementation. It should be approx. the same as the other posted above. Unfortunately, the performance is limited by the inner loop which is impossible to optimize more.

Browser detection in JavaScript?

This little library may help you. But be aware that browser detection is not always the solution.

How can I import a database with MySQL from terminal?

mysql -u <USERNAME> -p <DB NAME> < <dump file path>

-u - for Username

-p - to prompt the Password

Eg. mysql -u root -p mydb < /home/db_backup.sql

You can also provide password preceded by -p but for the security reasons it is not suggestible. The password will appear on the command itself rather masked.

How to return a PNG image from Jersey REST service method to the browser

I built a general method for that with following features:

  • returning "not modified" if the file hasn't been modified locally, a Status.NOT_MODIFIED is sent to the caller. Uses Apache Commons Lang
  • using a file stream object instead of reading the file itself

Here the code:

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger logger = LoggerFactory.getLogger(Utils.class);

@GET
@Path("16x16")
@Produces("image/png")
public Response get16x16PNG(@HeaderParam("If-Modified-Since") String modified) {
    File repositoryFile = new File("c:/temp/myfile.png");
    return returnFile(repositoryFile, modified);
}

/**
 * 
 * Sends the file if modified and "not modified" if not modified
 * future work may put each file with a unique id in a separate folder in tomcat
 *   * use that static URL for each file
 *   * if file is modified, URL of file changes
 *   * -> client always fetches correct file 
 * 
 *     method header for calling method public Response getXY(@HeaderParam("If-Modified-Since") String modified) {
 * 
 * @param file to send
 * @param modified - HeaderField "If-Modified-Since" - may be "null"
 * @return Response to be sent to the client
 */
public static Response returnFile(File file, String modified) {
    if (!file.exists()) {
        return Response.status(Status.NOT_FOUND).build();
    }

    // do we really need to send the file or can send "not modified"?
    if (modified != null) {
        Date modifiedDate = null;

        // we have to switch the locale to ENGLISH as parseDate parses in the default locale
        Locale old = Locale.getDefault();
        Locale.setDefault(Locale.ENGLISH);
        try {
            modifiedDate = DateUtils.parseDate(modified, org.apache.http.impl.cookie.DateUtils.DEFAULT_PATTERNS);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        Locale.setDefault(old);

        if (modifiedDate != null) {
            // modifiedDate does not carry milliseconds, but fileDate does
            // therefore we have to do a range-based comparison
            // 1000 milliseconds = 1 second
            if (file.lastModified()-modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
                return Response.status(Status.NOT_MODIFIED).build();
            }
        }
    }        
    // we really need to send the file

    try {
        Date fileDate = new Date(file.lastModified());
        return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
    } catch (FileNotFoundException e) {
        return Response.status(Status.NOT_FOUND).build();
    }
}

/*** copied from org.apache.http.impl.cookie.DateUtils, Apache 2.0 License ***/

/**
 * Date format pattern used to parse HTTP date headers in RFC 1123 format.
 */
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";

/**
 * Date format pattern used to parse HTTP date headers in RFC 1036 format.
 */
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";

/**
 * Date format pattern used to parse HTTP date headers in ANSI C
 * <code>asctime()</code> format.
 */
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";

public static final String[] DEFAULT_PATTERNS = new String[] {
    PATTERN_RFC1036,
    PATTERN_RFC1123,
    PATTERN_ASCTIME
};

Note that the Locale switching does not seem to be thread-safe. I think, it's better to switch the locale globally. I am not sure about the side-effects though...

How to create a .gitignore file

You can directly create empty .gitignore file , open cmd in the location you need to add this file and type this command

copy con .gitignore

press ENTER you are now in edit mode of the newly created file, but we do not need to add anything now, just press F6 and then press ENTER Now you have an empty .gitignore file, edit your file in whatever editor you have

How do I convert strings between uppercase and lowercase in Java?

Yes. There are methods on the String itself for this.

Note that the result depends on the Locale the JVM is using. Beware, locales is an art in itself.

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

On the xkcd note, the Bobby Tables website has good advice for avoiding the improper interpretation of user data (in this case, the string "Null") in SQL queries in various languages, including ColdFusion.

It is not clear from the question that this is the source of the problem, and given the solution noted in a comment to the first answer (embedding the parameters in a structure) it seems likely that it was something else.

How to read the post request parameters using JavaScript

JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.

Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.

Creating email templates with Django

I have made django-templated-email in an effort to solve this problem, inspired by this solution (and the need to, at some point, switch from using django templates to using a mailchimp etc. set of templates for transactional, templated emails for my own project). It is still a work-in-progress though, but for the example above, you would do:

from templated_email import send_templated_mail
send_templated_mail(
        'email',
        '[email protected]',
        ['[email protected]'],
        { 'username':username }
    )

With the addition of the following to settings.py (to complete the example):

TEMPLATED_EMAIL_DJANGO_SUBJECTS = {'email':'hello',}

This will automatically look for templates named 'templated_email/email.txt' and 'templated_email/email.html' for the plain and html parts respectively, in the normal django template dirs/loaders (complaining if it cannot find at least one of those).

How do you convert CString and std::string std::wstring to each other?

Solve that by using std::basic_string<TCHAR> instead of std::string and it should work fine regardless of your character setting.

Update row with data from another row in the same table

If you just need to insert a new row with a data from another row,

    insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;

In vb.net, how to get the column names from a datatable

This is how to retrieve a Column Name from a DataColumn:

MyDataTable.Columns(1).ColumnName 

To get the name of all DataColumns within your DataTable:

Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
  name(i) = column.ColumnName
  i += 1
Next

References

What causes HttpHostConnectException?

You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document

Sleep/Wait command in Batch

timeout 5

to delay

timeout 5 >nul

to delay without asking you to press any key to cancel

Laravel Advanced Wheres how to pass variable into function?

If you are using Laravel eloquent you may try this as well.

$result = self::select('*')
                    ->with('user')
                    ->where('subscriptionPlan', function($query) use($activated){
                        $query->where('activated', '=', $roleId);
                    })
                    ->get();

Integration Testing POSTing an entire object to Spring MVC controller

I had the same question and it turned out the solution was fairly simple, by using JSON marshaller.
Having your controller just change the signature by changing @ModelAttribute("newObject") to @RequestBody. Like this:

@Controller
@RequestMapping(value = "/somewhere/new")
public class SomewhereController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@RequestBody NewObject newObject) {
        // ...
    }
}

Then in your tests you can simply say:

NewObject newObjectInstance = new NewObject();
// setting fields for the NewObject  

mockMvc.perform(MockMvcRequestBuilders.post(uri)
  .content(asJsonString(newObjectInstance))
  .contentType(MediaType.APPLICATION_JSON)
  .accept(MediaType.APPLICATION_JSON));

Where the asJsonString method is just:

public static String asJsonString(final Object obj) {
    try {
        final ObjectMapper mapper = new ObjectMapper();
        final String jsonContent = mapper.writeValueAsString(obj);
        return jsonContent;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}  

javac option to compile all java files under a given directory recursively

I would also suggest using some kind of build tool (Ant or Maven, Ant is already suggested and is easier to start with) or an IDE that handles the compilation (Eclipse uses incremental compilation with reconciling strategy, and you don't even have to care to press any "Compile" buttons).

Using Javac

If you need to try something out for a larger project and don't have any proper build tools nearby, you can always use a small trick that javac offers: the classnames to compile can be specified in a file. You simply have to pass the name of the file to javac with the @ prefix.

If you can create a list of all the *.java files in your project, it's easy:

# Linux / MacOS
$ find -name "*.java" > sources.txt
$ javac @sources.txt

:: Windows
> dir /s /B *.java > sources.txt
> javac @sources.txt
  • The advantage is that is is a quick and easy solution.
  • The drawback is that you have to regenerate the sources.txt file each time you create a new source or rename an existing one file which is an easy to forget (thus error-prone) and tiresome task.

Using a build tool

On the long run it is better to use a tool that was designed to build software.

Using Ant

If you create a simple build.xml file that describes how to build the software:

<project default="compile">
    <target name="compile">
        <mkdir dir="bin"/>
        <javac srcdir="src" destdir="bin"/>
    </target>
</project>

you can compile the whole software by running the following command:

$ ant
  • The advantage is that you are using a standard build tool that is easy to extend.
  • The drawback is that you have to download, set up and learn an additional tool. Note that most of the IDEs (like NetBeans and Eclipse) offer great support for writing build files so you don't have to download anything in this case.

Using Maven

Maven is not that trivial to set up and work with, but learning it pays well. Here's a great tutorial to start a project within 5 minutes.

  • It's main advantage (for me) is that it handles dependencies too, so you won't need to download any more Jar files and manage them by hand and I found it more useful for building, packaging and testing larger projects.
  • The drawback is that it has a steep learning curve, and if Maven plugins like to suppress errors :-) Another thing is that quite a lot of tools also operate with Maven repositories (like Sbt for Scala, Ivy for Ant, Graddle for Groovy).

Using an IDE

Now that what could boost your development productivity. There are a few open source alternatives (like Eclipse and NetBeans, I prefer the former) and even commercial ones (like IntelliJ) which are quite popular and powerful.

They can manage the project building in the background so you don't have to deal with all the command line stuff. However, it always comes handy if you know what actually happens in the background so you can hunt down occasional errors like a ClassNotFoundException.

One additional note

For larger projects, it is always advised to use an IDE and a build tool. The former boosts your productivity, while the latter makes it possible to use different IDEs with the project (e.g., Maven can generate Eclipse project descriptors with a simple mvn eclipse:eclipse command). Moreover, having a project that can be tested/built with a single line command is easy to introduce to new colleagues and into a continuous integration server for example. Piece of cake :-)

C# function to return array

Two changes are needed:

  1. Change the return type of the method from Array[] to ArtWorkData[]
  2. Change Labels[] in the return statement to Labels

How to get logged-in user's name in Access vba?

In a Form, Create a text box, with in text box properties select data tab

Default value =CurrentUser()

Current source "select table field name"

It will display current user log on name in text box / label as well as saves the user name in the table field

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

I prefer to just return a null, and rely on the caller to handle it appropriately. The (for lack of a better word) exception is if I am absolutely 'certain' this method will return an object. In that case a failure is an exceptional should and should throw.

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

Assign format of DateTime with data annotations?

Did you try this?

[DataType(DataType.Date)]

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

this works for me:

It can be used inside the dialog, but the dialog can´t be inside any componet such as panels, accordion, etc.

CGContextDrawImage draws image upside down when passed UIImage.CGImage

I use this Swift 5, pure Core Graphics extension that correctly handles non-zero origins in image rects:

extension CGContext {

    /// Draw `image` flipped vertically, positioned and scaled inside `rect`.
    public func drawFlipped(_ image: CGImage, in rect: CGRect) {
        self.saveGState()
        self.translateBy(x: 0, y: rect.origin.y + rect.height)
        self.scaleBy(x: 1.0, y: -1.0)
        self.draw(image, in: CGRect(origin: CGPoint(x: rect.origin.x, y: 0), size: rect.size))
        self.restoreGState()
    }
}

You can use it exactly like CGContext's regular draw(: in:) method:

ctx.drawFlipped(myImage, in: myRect)

Align text in a table header

HTML:

<tr>
    <th>Language</th>
    <th>Skill Level</th>
    <th>&nbsp;</th>
</tr>

CSS:

tr, th {
    padding: 10px;
    text-align: center;
}

fitting data with numpy

Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]: 
array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,
          0.65459882])

In [41]: np.polyfit(x, y, 4)
Out[41]: 
array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,
         84.29340846])

In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

ffit = np.polyval(coefs[::-1], x_new)

However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

You're safest to use only the polynomial package:

import numpy.polynomial.polynomial as poly

coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)

Or, to create the polynomial function:

ffit = poly.Polynomial(coefs)    # instead of np.poly1d
plt.plot(x_new, ffit(x_new))

fit and data plot

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Replace all whitespace with a line break/paragraph mark to make a word list

You can also do it with xargs:

cat old | xargs -n1 > new

or

xargs -n1 < old > new

String representation of an Enum

Try type-safe-enum pattern.

public sealed class AuthenticationMethod {

    private readonly String name;
    private readonly int value;

    public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");
    public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");
    public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");        

    private AuthenticationMethod(int value, String name){
        this.name = name;
        this.value = value;
    }

    public override String ToString(){
        return name;
    }

}

Update Explicit (or implicit) type conversion can be done by

  • adding static field with mapping

    private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
    
    • n.b. In order that the initialisation of the the "enum member" fields doesn't throw a NullReferenceException when calling the instance constructor, be sure to put the Dictionary field before the "enum member" fields in your class. This is because static field initialisers are called in declaration order, and before the static constructor, creating the weird and necessary but confusing situation that the instance constructor can be called before all static fields have been initialised, and before the static constructor is called.
  • filling this mapping in instance constructor

    instance[name] = this;
    
  • and adding user-defined type conversion operator

    public static explicit operator AuthenticationMethod(string str)
    {
        AuthenticationMethod result;
        if (instance.TryGetValue(str, out result))
            return result;
        else
            throw new InvalidCastException();
    }
    

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

In SQL Developer: Everything was working fine and I had all the permissions to login and there was no password change and I could click the table and see the data tab.

But when I run query (simple select statement) it was showing "ORA-01031: insufficient privileges" message.

The solution is simply disconnect the connection and reconnect. Note: only doing Reconnect did not work for me. SQL Developer Disconnect Snapshot

What is Common Gateway Interface (CGI)?

You maybe want to know what is not CGI, and the answer is a MODULE for your web server (if I suppose you are runnig Apache). AND THAT'S THE BIG DIFERENCE, because CGI needs and external program, thread, whatever to instantiate a PERL, PHP, C app server where when you run as a MODULE that program is the web server (apache) per-se.

Because of all this there is a lot of performance, security, portability issues that come into play. But it's good to know what is not CGI first, to understand what it is.

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

python inserting variable string as file name

Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance

f = open('{}.csv'.format(name), 'wb')

Another option - the f-string formatting (ref):

f = open(f"{name}.csv", 'wb') 

Replace console output in Python

In python 3 you can do this to print on the same line:

print('', end='\r')

Especially useful to keep track of the latest update and progress.

I would also recommend tqdm from here if one wants to see the progress of a loop. It prints the current iteration and total iterations as a progression bar with an expected time of finishing. Super useful and quick. Works for python2 and python3.

Java and HTTPS url connection without downloading certificate

But why don't I have to install a certificate locally for the site?

Well the code that you are using is explicitly designed to accept the certificate without doing any checks whatsoever. This is not good practice ... but if that is what you want to do, then (obviously) there is no need to install a certificate that your code is explicitly ignoring.

Shouldn't I have to install a certificate locally and load it for this program or is it downloaded behind the covers?

No, and no. See above.

Is the traffic between the client to the remote site still encrypted in transmission?

Yes it is. However, the problem is that since you have told it to trust the server's certificate without doing any checks, you don't know if you are talking to the real server, or to some other site that is pretending to be the real server. Whether this is a problem depends on the circumstances.


If we used the browser as an example, typically a browser doesn't ask the user to explicitly install a certificate for each ssl site visited.

The browser has a set of trusted root certificates pre-installed. Most times, when you visit an "https" site, the browser can verify that the site's certificate is (ultimately, via the certificate chain) secured by one of those trusted certs. If the browser doesn't recognize the cert at the start of the chain as being a trusted cert (or if the certificates are out of date or otherwise invalid / inappropriate), then it will display a warning.

Java works the same way. The JVM's keystore has a set of trusted certificates, and the same process is used to check the certificate is secured by a trusted certificate.

Does the java https client api support some type of mechanism to download certificate information automatically?

No. Allowing applications to download certificates from random places, and install them (as trusted) in the system keystore would be a security hole.

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

Not knowing the actual details, my guess is that it makes an attempt to join like you might join relative URIs. For example:

urljoin('/some/abs/path', '../other') = '/some/abs/other'

This means that when you join a path with a preceding slash, you are actually joining one base to another, in which case the second gets precedence.

What is considered a good response time for a dynamic, personalized web application?

I have been striving for < 3 seconds for my applications, but I'm a bit picky when it comes to performance.

If you ask around, they say that people start to loose interest in the >= 7 second range, by 10-15 seconds you have typically lost them, unless you REALLY have something they want or need.

Making macOS Installer Packages which are Developer ID ready

Here is a build script which creates a signed installer package out of a build root.

#!/bin/bash
# TRIMCheck build script
# Copyright Doug Richardson 2015
# Usage: build.sh
#
# The result is a disk image that contains the TRIMCheck installer.
#

DSTROOT=/tmp/trimcheck.dst
SRCROOT=/tmp/trimcheck.src

INSTALLER_PATH=/tmp/trimcheck
INSTALLER_PKG="TRIMCheck.pkg"
INSTALLER="$INSTALLER_PATH/$INSTALLER_PKG"

#
# Clean out anything that doesn't belong.
#
echo Going to clean out build directories
rm -rf build $DSTROOT $SRCROOT $INSTALLER_PATH
echo Build directories cleaned out


#
# Build
#
echo ------------------
echo Installing Sources
echo ------------------
xcodebuild -project TRIMCheck.xcodeproj installsrc SRCROOT=$SRCROOT || exit 1

echo ----------------
echo Building Project
echo ----------------
pushd $SRCROOT
xcodebuild -project TRIMCheck.xcodeproj -target trimcheck -configuration Release install || exit 1
popd

echo ------------------
echo Building Installer
echo ------------------
mkdir -p "$INSTALLER_PATH" || exit 1

echo "Runing pkgbuild. Note you must be connected to Internet for this to work as it"
echo "has to contact a time server in order to generate a trusted timestamp. See"
echo "man pkgbuild for more info under SIGNED PACKAGES."
pkgbuild --identifier "com.delicioussafari.TRIMCheck" \
    --sign "Developer ID Installer: Douglas Richardson (4L84QT8KA9)" \
    --root "$DSTROOT" \
    "$INSTALLER" || exit 1


echo Successfully built TRIMCheck
open "$INSTALLER_PATH"

exit 0

Fatal error: Call to undefined function mb_strlen()

PHP 7.2 Ubuntu 18.04

sudo apt install php-mbstring

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

Android: Tabs at the BOTTOM

I was having the same problem with android tabs when trying to place them on the bottom of the screen. My scenario was to not use a layout file and create the tabs in code, I was also looking to fire activities from each tab which seemed a bit too complex using other approaches so, here is the sample code to overcome the problem:

adding-tabs-in-android-and-placing-them

grep for special characters in Unix

grep -n "\*\^\%\Q\&\$\&\^\@\$\&\!\^\@\$\&\^\&\^\&\^\&" test.log
1:*^%Q&$&^@$&!^@$&^&^&^&
8:*^%Q&$&^@$&!^@$&^&^&^&
14:*^%Q&$&^@$&!^@$&^&^&^&

Java code To convert byte to Hexadecimal

If you use Tink, then there is:

package com.google.crypto.tink.subtle;

public final class Hex {
  public static String encode(final byte[] bytes) { ... }
  public static byte[] decode(String hex) { ... }
}

so something like this should work:

import com.google.crypto.tink.subtle.Hex;

byte[] bytes = {-1, 0, 1, 2, 3 };
String enc = Hex.encode(bytes);
byte[] dec = Hex.decode(enc)

in python how do I convert a single digit number into a double digits string?

In Python 3.6 you can use so called f-strings. In my opinion this method is much clearer to read.

>>> f'{a:02d}'
'05'

Pass multiple complex objects to a post/put Web API method

Create one complex object to combine Content and Config in it as others mentioned, use dynamic and just do a .ToObject(); as:

[HttpPost]
public void StartProcessiong([FromBody] dynamic obj)
{
   var complexObj= obj.ToObject<ComplexObj>();
   var content = complexObj.Content;
   var config = complexObj.Config;
}

What does the fpermissive flag do?

Right from the docs:

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Bottom line: don't use it unless you know what you are doing!

Git pull command from different user

Was looking for the solution of a similar problem. Thanks to the answer provided by Davlet and Cupcake I was able to solve my problem.

Posting this answer here since I think this is the intended question

So I guess generally the problem that people like me face is what to do when a repo is cloned by another user on a server and that user is no longer associated with the repo.

How to pull from the repo without using the credentials of the old user ?

You edit the .git/config file of your repo.

and change

url = https://<old-username>@github.com/abc/repo.git/

to

url = https://<new-username>@github.com/abc/repo.git/

After saving the changes, from now onwards git pull will pull data while using credentials of the new user.

I hope this helps anyone with a similar problem

PG COPY error: invalid input syntax for integer

I think it's better to change your csv file like:

"age","first_name","last_name"
23,Ivan,Poupkine
,Eugene,Pirogov

It's also possible to define your table like

CREATE TABLE people (
  age        varchar(20),
  first_name varchar(20),
  last_name  varchar(20)
);

and after copy, you can convert empty strings:

select nullif(age, '')::int as age, first_name, last_name
from people

No signing certificate "iOS Distribution" found

Goto Xcode -> Prefrences and import the profile enter image description here

Cannot use special principal dbo: Error 15405

This answer doesn't help for SQL databases where SharePoint is connected. db_securityadmin is required for the configuration databases. In order to add db_securityadmin, you will need to change the owner of the database to an administrative account. You can use that account just for dbo roles.

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

This code seems completely unnecessary:

String serverURLS = getRecipientURL(message);

serverURLS = "https:\\\\abc.my.domain.com:55555\\update";

if (serverURLS != null){
    serverURL = new URL(serverURLS);
}
  1. serverURLS is assigned the result of getRecipientURL(message)
  2. Then immediately you overwrite the value of serverURLS, making the previous statement a dead store
  3. Then, because if (serverURLS != null) evaluates to true, since you just assigned the variable a value in the preceding statement, you assign a value to serverURL. It is impossible for if (serverURLS != null) to evaluate to false!
  4. You never actually use the variable serverURLS beyond the previous line of code.

You could replace all of this with just:

serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");

S3 - Access-Control-Allow-Origin Header

Like others have stated, you first need to have the CORS configuration in your S3 bucket:

<CORSConfiguration>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod> <!-- Add this -->
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

But in my case after doing that, it was still not working. I was using Chrome (probably the same problem with other browsers).

The problem was that Chrome was caching the image with the headers (not containing the CORS data), so no matter what I tried to change in AWS, I would not see my CORS headers.

After clearing Chrome cache and reloading the page, the image had the expected CORS Headers

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Difference between EXISTS and IN in SQL?

I believe this has a straightforward answer. Why don't you check it from the people who developed that function in their systems?

If you are a MS SQL developer, here is the answer directly from Microsoft.

IN:

Determines whether a specified value matches any value in a subquery or a list.

EXISTS:

Specifies a subquery to test for the existence of rows.

Rails 4 - Strong Parameters - Nested Objects

Permitting a nested object :

params.permit( {:school => [:id , :name]}, 
               {:student => [:id, 
                            :name, 
                            :address, 
                            :city]},
                {:records => [:marks, :subject]})

Reverse Y-Axis in PyPlot

Another similar method to those described above is to use plt.ylim for example:

plt.ylim(max(y_array), min(y_array))

This method works for me when I'm attempting to compound multiple datasets on Y1 and/or Y2

Get current URL from IFRAME

For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:

document.getElementById("iframe_id").contentWindow.location.href

If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.

See also answers to a similar question.

Grep for beginning and end of line?

Many answers provided for this question. Just wanted to add one more which uses bashism-

#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"

@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).

CSV in Python adding an extra carriage return, on Windows

While @john-machin gives a good answer, it's not always the best approach. For example, it doesn't work on Python 3 unless you encode all of your inputs to the CSV writer. Also, it doesn't address the issue if the script wants to use sys.stdout as the stream.

I suggest instead setting the 'lineterminator' attribute when creating the writer:

import csv
import sys

doc = csv.writer(sys.stdout, lineterminator='\n')
doc.writerow('abc')
doc.writerow(range(3))

That example will work on Python 2 and Python 3 and won't produce the unwanted newline characters. Note, however, that it may produce undesirable newlines (omitting the LF character on Unix operating systems).

In most cases, however, I believe that behavior is preferable and more natural than treating all CSV as a binary format. I provide this answer as an alternative for your consideration.

How to do the Recursive SELECT query in MySQL?

Building off of Master DJon

Here is simplified function which provides the added utility of returning depth (in case you want to use logic to include the parent task or search at a specific depth)

DELIMITER $$
FUNCTION `childDepth`(pParentId INT, pId INT) RETURNS int(11)
    READS SQL DATA
    DETERMINISTIC
BEGIN
DECLARE depth,curId int;
SET depth = 0;
SET curId = pId;

WHILE curId IS not null AND curId <> pParentId DO
    SELECT ParentId from test where id=curId limit 1 into curId;
    SET depth = depth + 1;
END WHILE;

IF curId IS NULL THEN
    set depth = -1;
END IF;

RETURN depth;
END$$

Usage:

select * from test where childDepth(1, id) <> -1;

How do I convert an Array to a List<object> in C#?

Use the constructor: new List<object>(myArray)

How to resolve the "ADB server didn't ACK" error?

On my Mac, I wrote this code in my Terminal:

xxx-MacBook-Pro:~ xxx$ cd /Users/xxx/Documents/0_Software/adt20140702/sdk/platform-tools/

xxx-MacBook-Pro:platform-tools xxx$ ./adb kill-server

xxx-MacBook-Pro:platform-tools xxx$ ./adb start-server

  • daemon not running. starting it now on port 5037 *
  • daemon started successfully *

xxx-MacBook-Pro:platform-tools tuananh$

Hope this help.

POST request send json data java HttpUrlConnection

Your JSON is not correct. Instead of

JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString());              // <-- toString()

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

write

JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

So, the JSONObject.toString() should be called only once for the outer object.

Another thing (most probably not your problem, but I'd like to mention it):

To be sure not to run into encoding problems, you should specify the encoding, if it is not UTF-8:

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");

// ...

OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

How do you convert an entire directory with ffmpeg?

To convert with subdirectories use e.g.

find . -exec ffmpeg -i {} {}.mp3 \;

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

FirebaseInstanceIdService is deprecated

In KOTLIN:- If you want to save Token into DB or shared preferences then override onNewToken in FirebaseMessagingService

override fun onNewToken(token: String) {
        super.onNewToken(token)
    }

Get token at run-time,use

FirebaseInstanceId.getInstance().instanceId
                        .addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
                            val mToken = instanceIdResult.token
                            println("printing  fcm token: $mToken")
                        }

Accessing bash command line args $@ vs $*

$*

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

$@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Source: Bash man

How to copy data from one table to another new table in MySQL?

You should create table2 first.

insert into table2(field1,field2,...)
select field1,field2,....
from table1
where condition;

Spring MVC: how to create a default controller for index page?

Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml

<mvc:view-controller path="/" view-name="index"/>

After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml file.

change index with your jsp name.

How to get $(this) selected option in jQuery?

Best guess:

var cur_value = $('#select-id').children('option:selected').text();

I like children better in this case because you know you're only going one branch down the DOM tree...

How to install older version of node.js on Windows?

Just uninstall whatever node version you have in your system. Then go to this site https://nodejs.org/download/release/ and choose your desired version like for me its like v7.0.0/ and click on that go get .msi file of that. Finally you will get installer in your system, so install it. It will solve all your problems.

Multi-character constant warnings

If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:

-Wno-multichar

I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.

PowerShell: Create Local User Account

Try using Carbon's Install-User and Add-GroupMember functions:

Install-User -Username "User" -Description "LocalAdmin" -FullName "Local Admin by Powershell" -Password "Password01"
Add-GroupMember -Name 'Administrators' -Member 'User'

Disclaimer: I am the creator/maintainer of the Carbon project.

How to disable HTML links

you cannot disable a link, if you want that click event should not fire then simply Remove the action from that link.

$(td).find('a').attr('href', '');

For More Info :- Elements that can be Disabled

Execute a shell function with timeout

There's an inline alternative also launching a subprocess of bash shell:


timeout 10s bash <<EOT
function echoFooBar {
  echo foo
}

echoFooBar
sleep 20
EOT

Uploading a file in Rails

Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field to get the file,

In controller,

 @person = Person.new(person_params)

Here person_params return whitelisted params[:person] (define yourself)

Save file as,

dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")

Note, Add this path in .gitignore & if you want to use this file again add this path asset_pathan of application by application.rb

Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets

note: Storing files like this will increase the size of the application, better to store in the database using paperclip.

How to pass 2D array (matrix) in a function in C?

2D array:

int sum(int array[][COLS], int rows)
{

}

3D array:

int sum(int array[][B][C], int A)
{

}

4D array:

int sum(int array[][B][C][D], int A)
{

}

and nD array:

int sum(int ar[][B][C][D][E][F].....[N], int A)
{

}

How to start an application using android ADB tools?

Also, I want to mention one more thing.

When you start an application from adb shell am, it automatically adds FLAG_ACTIVITY_NEW_TASK flag which makes behavior change. See the code.

For example, if you launch Play Store activity from adb shell am, pressing 'Back' button(hardware back button) wouldn't take you your app, instead it would take you previous Play Store activity if there was some(If there was not Play store task, then it would take you your app). FLAG_ACTIVITY_NEW_TASK documentation says :

if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in

This caused me to spend a few hours to find out what went wrong.

So, keep in mind that adb shell am add FLAG_ACTIVITY_NEW_TASK flag.

Differences between hard real-time, soft real-time, and firm real-time?

real-time - Pertaining to a system or mode of operation in which computation is performed during the actual time that an external process occurs, in order that the computation results can be used to control, monitor, or respond to the external process in a timely manner. [IEEE Standard 610.12.1990]

I know this definition is old, very old. I can't, however, find a more recent definition by the IEEE (Institute of Electrical and Electronics Engineers).

How to call a MySQL stored procedure from within PHP code?

I now found solution by using mysqli instead of mysql.

<?php 

// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$connection = mysqli_connect("hostname", "user", "password", "db", "port");

//run the store proc
$result = mysqli_query($connection, "CALL StoreProcName");

//loop the result set
while ($row = mysqli_fetch_array($result)){     
  echo $row[0] . " - " . + $row[1]; 
}

I found that many people seem to have a problem with using mysql_connect, mysql_query and mysql_fetch_array.

Don't understand why UnboundLocalError occurs (closure)

To modify a global variable inside a function, you must use the global keyword.

When you try to do this without the line

global counter

inside of the definition of increment, a local variable named counter is created so as to keep you from mucking up the counter variable that the whole program may depend on.

Note that you only need to use global when you are modifying the variable; you could read counter from within increment without the need for the global statement.

Is there a timeout for idle PostgreSQL connections?

Another option is set this value "tcp_keepalives_idle". Check more in documentation https://www.postgresql.org/docs/10/runtime-config-connection.html.

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

How to fix C++ error: expected unqualified-id

For what it's worth, I had the same problem but it wasn't because of an extra semicolon, it was because I'd forgotten a semicolon on the previous statement.

My situation was something like

mynamespace::MyObject otherObject

for (const auto& element: otherObject.myVector) {
  // execute arbitrary code on element
  //...
  //...
} 

From this code, my compiler kept telling me:

error: expected unqualified-id before for (const auto& element: otherObject.myVector) { etc... which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ; after declaring otherObject.

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
   //define something for Windows (32-bit and 64-bit, this part is common)
   #ifdef _WIN64
      //define something for Windows (64-bit only)
   #else
      //define something for Windows (32-bit only)
   #endif
#elif __APPLE__
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR
         // iOS Simulator
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

The defined macros depend on the compiler that you are going to use.

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both (also WIN32 without underscore allows IDE to highlight the right partition of code).

How to put a horizontal divisor line between edit text's in a activity

Try this link.... horizontal rule

That should do the trick.

The code below is xml.

<View
    android:layout_width="fill_parent"
    android:layout_height="2dip"
    android:background="#FF00FF00" />

C++ JSON Serialization

Try json_dto. It is header-only and easy to use.

Simple example:

struct message_t
{
  std::string m_from;
  std::string m_text;

  // Entry point for json_dto.
  template < typename JSON_IO >
  void
  json_io( JSON_IO & io )
  {
    io
      & json_dto::mandatory( "from", m_from )
      & json_dto::mandatory( "text", m_text );
  }
};

This will be convertable to and from JSON:

{ "from" : "json_dto", "text" : "Hello world!" }

ListView inside ScrollView is not scrolling on Android

Add: android:nestedScrollingEnabled="true"

CSS opacity only to background color, not the text on it?

This will work with every browser

div {
    -khtml-opacity: .50;
    -moz-opacity: .50;
    -ms-filter: ”alpha(opacity=50)”;
    filter: alpha(opacity=50);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
    opacity: .50;
}

If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent to achieve this. CSS Opacity That Doesn’t Affect Child Elements

Check a working demo at CSS Opacity That Doesn't Affect "Children"

Insert new column into table in sqlite?

I was facing the same problem and the second method proposed in the accepted answer, as noted in the comments, can be problematic when dealing with foreign keys.

My workaround is to export the database to a sql file making sure that the INSERT statements include column names. I do it using DB Browser for SQLite which has an handy feature for that. After that you just have to edit the create table statement and insert the new column where you want it and recreate the db.

In *nix like systems is just something along the lines of

cat db.sql | sqlite3 database.db

I don't know how feasible this is with very big databases, but it worked in my case.

./xx.py: line 1: import: command not found

When you see "import: command not found" on the very first import, it is caused by the parser not using the character encoding matching your py file. Especially when you are not using ASCII encoding in your py file.

The way to get it right is to specify the correct encoding on top of your py file to match your file character encoding.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

How can I know which radio button is selected via jQuery?

Use this..

$("#myform input[type='radio']:checked").val();

Boto3 to download all files from a S3 Bucket

I'm currently achieving the task, by using the following

#!/usr/bin/python
import boto3
s3=boto3.client('s3')
list=s3.list_objects(Bucket='bucket')['Contents']
for s3_key in list:
    s3_object = s3_key['Key']
    if not s3_object.endswith("/"):
        s3.download_file('bucket', s3_object, s3_object)
    else:
        import os
        if not os.path.exists(s3_object):
            os.makedirs(s3_object)

Although, it does the job, I'm not sure its good to do this way. I'm leaving it here to help other users and further answers, with better manner of achieving this

How to iterate over a TreeMap?

Using Google Collections, assuming K is your key type:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

You can use filterEntries instead if you need the value as well.

Convert Long into Integer

In addition to @Thilo's accepted answer, Math.toIntExact works also great in Optional method chaining, despite it accepts only an int as an argument

Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0

error TS2339: Property 'x' does not exist on type 'Y'

If you want to be able to access images.main then you must define it explicitly:

interface Images {
    main: string;
    [key:string]: string;
}

function getMainImageUrl(images: Images): string {
    return images.main;
}

You can not access indexed properties using the dot notation because typescript has no way of knowing whether or not the object has that property.
However, when you specifically define a property then the compiler knows that it's there (or not), whether it's optional or not and what's the type.


Edit

You can have a helper class for map instances, something like:

class Map<T> {
    private items: { [key: string]: T };

    public constructor() {
        this.items = Object.create(null);
    }

    public set(key: string, value: T): void {
        this.items[key] = value;
    }

    public get(key: string): T {
        return this.items[key];
    }

    public remove(key: string): T {
        let value = this.get(key);
        delete this.items[key];
        return value;
    }
}

function getMainImageUrl(images: Map<string>): string {
    return images.get("main");
}

I have something like that implemented, and I find it very useful.

Read tab-separated file line into array

You're very close:

while IFS=$'\t' read -r -a myArray
do
 echo "${myArray[0]}"
 echo "${myArray[1]}"
 echo "${myArray[2]}"
done < myfile

(The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)