Programs & Examples On #Publicdomain

Change the location of the ~ directory in a Windows install of Git Bash

So, $HOME is what I need to modify.

However I have been unable to find where this mythical $HOME variable is set so I assumed it was a Linux system version of PATH or something.

Git 2.23 (Q3 2019) is quite explicit on how HOME is set.

See commit e12a955 (04 Jul 2019) by Karsten Blees (kblees).
(Merged by Junio C Hamano -- gitster -- in commit fc613d2, 19 Jul 2019)

mingw: initialize HOME on startup

HOME initialization was historically duplicated in many different places, including /etc/profile, launch scripts such as git-bash.vbs and gitk.cmd, and (although slightly broken) in the git-wrapper.

Even unrelated projects such as GitExtensions and TortoiseGit need to implement the same logic to be able to call git directly.

Initialize HOME in Git's own startup code so that we can eventually retire all the duplicate initialization code.

Now, mingw.c includes the following code:

/* calculate HOME if not set */
if (!getenv("HOME")) {
    /*
     * try $HOMEDRIVE$HOMEPATH - the home share may be a network
     * location, thus also check if the path exists (i.e. is not
     * disconnected)
     */
    if ((tmp = getenv("HOMEDRIVE"))) {
        struct strbuf buf = STRBUF_INIT;
        strbuf_addstr(&buf, tmp);
        if ((tmp = getenv("HOMEPATH"))) {
            strbuf_addstr(&buf, tmp);
            if (is_directory(buf.buf))
                setenv("HOME", buf.buf, 1);
            else
                tmp = NULL; /* use $USERPROFILE */
        }
        strbuf_release(&buf);
    }
    /* use $USERPROFILE if the home share is not available */
    if (!tmp && (tmp = getenv("USERPROFILE")))
        setenv("HOME", tmp, 1);
}

DropDownList in MVC 4 with Razor

//ViewModel

public class RegisterViewModel
{

    public RegisterViewModel()
    {
        ActionsList = new List<SelectListItem>();
    }

    public IEnumerable<SelectListItem> ActionsList { get; set; }

    public string StudentGrade { get; set; }

  }

//Enum Class:

public enum GradeTypes
{
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H
}

//Controller Action

 public ActionResult Student()
    {
RegisterViewModel vm = new RegisterViewModel();
IEnumerable<GradeTypes> actionTypes = Enum.GetValues(typeof(GradeTypes))
                                             .Cast<GradeTypes>();
        vm.ActionsList = from action in actionTypes
                         select new SelectListItem
                         {
                             Text = action.ToString(),
                             Value = action.ToString()
                         };
        return View(vm);
    }

//view Action

 <div class="form-group">
                                <label class="col-lg-2 control-label" for="hobies">Student Grade:</label>
                                <div class="col-lg-10">
                                   @Html.DropDownListFor(model => model.StudentGrade, Model.ActionsList, new { @class = "form-control" })
                                </div>

React Native Border Radius with background color

You should add overflow: hidden to your styles:

Js:

<Button style={styles.submit}>Submit</Button>

Styles:

submit {
   backgroundColor: '#68a0cf';
   overflow: 'hidden';
}

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

In case MySQL Server is up but you are still getting the error:

For anyone who still have this issue, I followed awesome tutorial http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-9-mavericks/

However i still got #1045 error. What really did the trick was to change localhost to 127.0.0.1 at your config.inc.php. Why was it failing if locahost points to 127.0.0.1? I don't know. But it worked.

===== EDIT =====

Long story short, it is because of permissions in mysql. It may be set to accept connections from 127.0.0.1 but not from localhost.

The actual answer for why this isn't responding is here: https://serverfault.com/a/297310

How to make cross domain request

If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather). I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.

How to go back last page

To go back without refreshing the page, We can do in html like below javascript:history.back()

<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>

How to get id from URL in codeigniter?

A bit late but this worked for me

  $data_id = $this->input->get('name_of_field');

Add days to JavaScript Date

Try

var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));

Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.

SQL distinct for 2 fields in a database

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

No provider for HttpClient

Just import the HttpModule and the HttpClientModule only:

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

No need for the HttpClient.

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

No, but you can do this almost as easily.

Go here:

https://romannurik.github.io/AndroidAssetStudio/

Build your icons using that page, and then download the zip package. Unzip it into the right directory and it'll overwrite all the drawable-*/ic_launcher.png correctly.

How to get EditText value and display it on screen through TextView?

I'm just beginner to help you for getting edittext value to textview. Try out this code -

EditText edit = (EditText)findViewById(R.id.editext1);
TextView tview = (TextView)findViewById(R.id.textview1);
String result = edit.getText().toString();
tview.setText(result);

This will get the text which is in EditText Hope this helps you.

Escape single quote character for use in an SQLite query

In C# you can use the following to replace the single quote with a double quote:

 string sample = "St. Mary's";
 string escapedSample = sample.Replace("'", "''");

And the output will be:

"St. Mary''s"

And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:

private static string MySqlEscape(Object usString)
{
    if (usString is DBNull)
    {
        return "";
    }
    string sample = Convert.ToString(usString);
    return sample.Replace("'", "''");
}

if statement in ng-click

Don't put any Condition Expression in Template.

Do it at the Controller.

Template:

<input ng-click="check(profileForm.$valid)" name="submit" 
       id="submit" value="Save" class="submit" type="submit">

Controller:

$scope.check = function(value) {
    if (value) {
       updateMyProfile();
    }
}

How to determine total number of open/active connections in ms sql server 2005

see sp_who it gives you more details than just seeing the number of connections

in your case i would do something like this

 DECLARE @temp TABLE(spid int , ecid int, status varchar(50),
                     loginname varchar(50),   
                     hostname varchar(50),
blk varchar(50), dbname varchar(50), cmd varchar(50), request_id int) 
INSERT INTO @temp  

EXEC sp_who

SELECT COUNT(*) FROM @temp WHERE dbname = 'DB NAME'

Get index of current item in a PowerShell loop

I am not sure it's possible with an "automatic" variable. You can always declare one for yourself and increment it:

$letters = { 'A', 'B', 'C' }
$letters | % {$counter = 0}{...;$counter++}

Or use a for loop instead...

for ($counter=0; $counter -lt $letters.Length; $counter++){...}

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in ApacheĀ 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

How to position a div scrollbar on the left hand side?

I have the same problem. but when i add direction: rtl; in tabs and accordion combo but it crashes my structure.

The way to do it is add div with direction: rtl; as parent element, and for child div set direction: ltr;.

I use this first https://api.jquery.com/wrap/

$( ".your selector of child element" ).wrap( "<div class='scroll'></div>" );

then just simply work with css :)

In children div add to css

 .your_class {
            direction: ltr;    
        }

And to parent div added by jQuery with class .scroll

.scroll {
            unicode-bidi:bidi-override;
            direction: rtl;
            overflow: scroll;
            overflow-x: hidden!important;
        }

Works prefect for me

http://jsfiddle.net/jw3jsz08/1/

How can I make the Android emulator show the soft keyboard?

There is a bug in the new version of NOX app. Software keyboard doesn't work after switching to it in settings. To fix this, I installed Gboard using the Play Market.

Decrementing for loops

for i in range(10,0,-1):
    print i,

The range() function will include the first value and exclude the second.

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

I know Hebrew pretty well, so to clarify the name "Paamayim Nekudotayim" for you, the paraphrased meaning is "double colon", but translated literally:

  • "Paamayim" means "two" or "twice"
  • "Nekudotayim" means "dots" (lit. "holes")
    • In the Hebrew language, a nekuda means a dot.
    • The plural is nekudot, i.e, dots that act like vowels do in english.
    • The reason it why it's called Nekudo-tayim is because the suffix "-ayim" also means "two" or "twice", thus :: denotes "two times, two dots", or more commonly known as the Scope Resolution Operator.

How to change option menu icon in the action bar?

1) Declare menu in your class.

private Menu menu;

2) In onCreateOptionsMenu do the following :

public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    getMenuInflater().inflate(R.menu.menu_orders_screen, menu);
    return true;
}   

3) In onOptionsItemSelected, get the item and do the changes as required(icon, text, colour, background)

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_search) {
        return true;
    }
    if (id == R.id.ventor_status) {
        return true;
    }
    if (id == R.id.action_settings_online) {
        menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.history_converted));
        menu.getItem(1).setTitle("Online");
        return true;
    }
    if (id == R.id.action_settings_offline) {
        menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.cross));
        menu.getItem(1).setTitle("Offline");
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Note:
If you have 3 menu items :
menu.getItem(0) = 1 item,
menu.getItem(1) = 2 iteam,
menu.getItem(2) = 3 item

Based on this make the changes accordingly as per your requirement.

How to declare a constant in Java

final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.

So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

You are mixing code that was compiled with /MD (use DLL version of CRT) with code that was compiled with /MT (use static CRT library). That cannot work, all source code files must be compiled with the same setting. Given that you use libraries that were pre-compiled with /MD, almost always the correct setting, you must compile your own code with this setting as well.

Project + Properties, C/C++, Code Generation, Runtime Library.

Beware that these libraries were probably compiled with an earlier version of the CRT, msvcr100.dll is quite new. Not sure if that will cause trouble, you may have to prevent the linker from generating a manifest. You must also make sure to deploy the DLLs you need to the target machine, including msvcr100.dll

Get Request and Session Parameters and Attributes from JSF pages

You can also use a bean (request scoped is suggested) and directly access the context by way of the FacesContext.

You can get the HttpServletRequest and HttpServletResposne objects by using the following code:

HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();

After this, you can access individual parameters via getParameter(paramName) or access the full map via getParameterMap() req object

The reason I suggest a request scoped bean is that you can use these during initialization (worst case scenario being the constructor. Most frameworks give you some place to do code at bean initialization time) and they will be done as your request comes in.

It is, however, a bit of a hack. ;) You may want to look into seeing if there is a JSF Acegi module that will allow you to get access to the variables you need.

Remove or uninstall library previously added : cocoapods

  1. Remove the library from your Podfile

  2. Run pod install on the terminal

sql server Get the FULL month name from a date

select datename(DAY,GETDATE()) +'-'+ datename(MONTH,GETDATE()) +'- '+ 
       datename(YEAR,GETDATE()) as 'yourcolumnname'

Oracle SELECT TOP 10 records

You'll need to put your current query in subquery as below :

SELECT * FROM (
  SELECT DISTINCT 
  APP_ID, 
  NAME, 
  STORAGE_GB, 
  HISTORY_CREATED, 
  TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE  
  FROM HISTORY WHERE 
    STORAGE_GB IS NOT NULL AND 
      APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
  ORDER BY STORAGE_GB DESC )
WHERE ROWNUM <= 10

Oracle applies rownum to the result after it has been returned.
You need to filter the result after it has been returned, so a subquery is required. You can also use RANK() function to get Top-N results.

For performance try using NOT EXISTS in place of NOT IN. See this for more.

Eclipse jump to closing brace

With Ctrl + Shift + L you can open the "key assist", where you can find all the shortcuts.

The Use of Multiple JFrames: Good or Bad Practice?

If the frames are going to be the same size, why not create the frame and pass the frame then as a reference to it instead.

When you have passed the frame you can then decide how to populate it. It would be like having a method for calculating the average of a set of figures. Would you create the method over and over again?

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

SQL time difference between two dates result in hh:mm:ss

declare @StartDate datetime, @EndDate datetime

select @StartDate = '10/01/2012 08:40:18.000',@EndDate='10/04/2012 09:52:48.000'

select convert(varchar(5),DateDiff(s, @startDate, @EndDate)/3600)+':'+convert(varchar(5),DateDiff(s, @startDate, @EndDate)%3600/60)+':'+convert(varchar(5),(DateDiff(s, @startDate, @EndDate)%60)) as [hh:mm:ss]

This query will helpful to you.

Android ImageView Animation

imgDics = (ImageView) v.findViewById(R.id.img_player_tab2_dics);
    imgDics.setOnClickListener(onPlayer2Click);
    anim = new RotateAnimation(0f, 360f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);
    anim.setInterpolator(new LinearInterpolator());
    anim.setRepeatCount(Animation.INFINITE);
    anim.setDuration(4000);

    // Start animating the image
    imgDics.startAnimation(anim);

POST request with a simple string in body with Alamofire

Based on Illya Krit's answer

Details

  • Xcode Version 10.2.1 (10E1001)
  • Swift 5
  • Alamofire 4.8.2

Solution

import Alamofire

struct BodyStringEncoding: ParameterEncoding {

    private let body: String

    init(body: String) { self.body = body }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
        guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }
        urlRequest.httpBody = data
        return urlRequest
    }
}

extension BodyStringEncoding {
    enum Errors: Error {
        case emptyURLRequest
        case encodingProblem
    }
}

extension BodyStringEncoding.Errors: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .emptyURLRequest: return "Empty url request"
            case .encodingProblem: return "Encoding problem"
        }
    }
}

Usage

Alamofire.request(url, method: .post, parameters: nil, encoding: BodyStringEncoding(body: text), headers: headers).responseJSON { response in
     print(response)
}

How to check if Receiver is registered in Android?

If you put this on onDestroy or onStop method. I think that when the activity has been created again the MessageReciver wasn't being created.

@Override 
public void onDestroy (){
    super.onDestroy();
LocalBroadcastManager.getInstance(context).unregisterReceiver(mMessageReceiver);

}

how to select first N rows from a table in T-SQL?

select top(@count) * from users

If @count is a constant, you can drop the parentheses:

select top 42 * from users

(the latter works on SQL Server 2000 too, while the former requires at least 2005)

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

This is due a conflict of versions, to solve it, just force an update of your support-annotations version, adding this line on your module: app gradle

implementation ('com.android.support:support-annotations:27.1.1')

Hope this solves your issue ;)

Edit

Almost forgot, you can declare a single extra property (https://docs.gradle.org/current/userguide/writing_build_scripts.html#sec:extra_properties) for the version, go to your project (or your top) gradle file, and declare your support, or just for this example, annotation version var

ext.annotation_version = "27.1.1"

Then in your module gradle replace it with:

implementation ("com.android.support:support-annotations:$annotation_version")

This is very similar to the @emadabel solution, which is a good alternative for doing it, but without the block, or the rootproject prefix.

Sending JSON to PHP using ajax

just remove:

...
//dataType: "json",
url: "index.php",
data: {myData:postData},
//contentType: "application/json; charset=utf-8",
...

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Appending the same string to a list of strings in Python

Extending a bit to "Appending a list of strings to a list of strings":

    import numpy as np
    lst1 = ['a','b','c','d','e']
    lst2 = ['1','2','3','4','5']

    at = np.full(fill_value='@',shape=len(lst1),dtype=object) #optional third list
    result = np.array(lst1,dtype=object)+at+np.array(lst2,dtype=object)

Result:

array(['a@1', 'b@2', 'c@3', 'd@4', 'e@5'], dtype=object)

dtype odject may be further converted str

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

This is the minimal stuff I keep for day to day Android development (including production code). Latest versions from API 25 to API 27 (Nougat to Android P) included only, and you can work great with it.

  • To minimize even more, just keep any one of the below versions as same and keep a lower versions i.e. API 16 with same files downloaded as below.

NotificationCompat.Builder deprecated in Android O

Instead of checking for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O as many answers suggest, there is a slightly simpler way -

Add the following line to the application section of AndroidManifest.xml file as explained in the Set Up a Firebase Cloud Messaging Client App on Android doc:

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id" 
        android:value="@string/default_notification_channel_id" />

Then add a line with a channel name to the values/strings.xml file:

<string name="default_notification_channel_id">default</string>

After that you will be able to use the new version of NotificationCompat.Builder constructor with 2 parameters (since the old constructor with 1 parameter has been deprecated in Android Oreo):

private void sendNotification(String title, String body) {
    Intent i = new Intent(this, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pi = PendingIntent.getActivity(this,
            0 /* Request code */,
            i,
            PendingIntent.FLAG_ONE_SHOT);

    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, 
        getString(R.string.default_notification_channel_id))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pi);

    NotificationManager manager = 
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    manager.notify(0, builder.build());
}

Artificially create a connection timeout error

For me easiest way was adding static route on office router based on destination network. Just route traffic to some unresponsive host (e.g. your computer) and you will get request timeout.

Best thing for me was that static route can be managed over web interface and enabled/disabled easily.

How can a LEFT OUTER JOIN return more records than exist in the left table?

Pay attention if you have a where clause on the "right side' table of a query containing a left outer join... In case you have no record on the right side satisfying the where clause, then the corresponding record of the 'left side' table will not appear in the result of your query....

jQuery Date Picker - disable past dates

I have created function to disable previous date, disable flexible weekend days (Like Saturday, Sunday)

We are using beforeShowDay method of jQuery UI datepicker plugin.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
var NotBeforeToday = function(date) {_x000D_
  var now = new Date(); //this gets the current date and time_x000D_
  if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6) )_x000D_
   return [true,""];_x000D_
  if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
   return [true,""];_x000D_
  if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
   return [true,""];_x000D_
  return [false,""];_x000D_
 }_x000D_
_x000D_
_x000D_
jQuery("#datepicker").datepicker({_x000D_
  beforeShowDay: NotBeforeToday_x000D_
    });
_x000D_
_x000D_
_x000D_

enter image description here

Here today's date is 15th Sept. I have disabled Saturday and Sunday.

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.


1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

How to upgrade all Python packages with pip

This seemed to work for me...

pip install -U $(pip list --outdated | awk '{printf $1" "}')

I used printf with a space afterwards to properly separate the package names.

Import error: No module name urllib2

As stated in the urllib2 documentation:

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

So you should instead be saying

from urllib.request import urlopen
html = urlopen("http://www.google.com/").read()
print(html)

Your current, now-edited code sample is incorrect because you are saying urllib.urlopen("http://www.google.com/") instead of just urlopen("http://www.google.com/").

How can I detect the touch event of an UIImageView?

In practical terms, don't do that.

Instead add a button with Custom style (no button graphics unless you specify images) over the UIImageView. Then attach whatever methods you want called to that.

You can use that technique for many cases where you really want some area of the screen to act as a button instead of messing with the Touch stuff.

Python Selenium accessing HTML source

driver.page_source will help you get the page source code. You can check if the text is present in the page source or not.

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("some url")
if "your text here" in driver.page_source:
    print('Found it!')
else:
    print('Did not find it.')

If you want to store the page source in a variable, add below line after driver.get:

var_pgsource=driver.page_source

and change the if condition to:

if "your text here" in var_pgsource:

Examples of GoF Design Patterns in Java's core libraries

Even though I'm sort of a broken clock with this one, Java XML API uses Factory a lot. I mean just look at this:

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
String title = XPathFactory.newInstance().newXPath().evaluate("//title", doc);

...and so on and so forth.

Additionally various Buffers (StringBuffer, ByteBuffer, StringBuilder) use Builder.

Why is NULL undeclared?

Do use NULL. It is just #defined as 0 anyway and it is very useful to semantically distinguish it from the integer 0.

There are problems with using 0 (and hence NULL). For example:

void f(int);
void f(void*);

f(0); // Ambiguous. Calls f(int).

The next version of C++ (C++0x) includes nullptr to fix this.

f(nullptr); // Calls f(void*).

Largest and smallest number in an array

   static void PrintSmallestLargest(int[] arr)
    {
        if (arr.Length > 0)
        {
            int small = arr[0];
            int large = arr[0];
            for (int i = 0; i < arr.Length; i++)
            {
                if (large < arr[i])
                {
                    int tmp = large;
                    large = arr[i];
                    arr[i] = large;
                }
                if (small > arr[i])
                {
                    int tmp = small;
                    small = arr[i];
                    arr[i] = small;
                }
            }
            Console.WriteLine("Smallest is {0}", small);
            Console.WriteLine("Largest is {0}", large);
        }
    }

This way you can have smallest and largest number in a single loop.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

Old question, but here's another explanation of the problem. You'll get this error even if you have strongly typed views and aren't using ViewData to create your dropdown list. The reason for the error can becomes clear when you look at the MVC source:

// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
    selectList = htmlHelper.GetSelectData(name);
    usedViewData = true;
}

So if you have something like:

@Html.DropDownList("MyList", Model.DropDownData, "")

And Model.DropDownData is null, MVC looks through your ViewData for something named MyList and throws an error if there's no object in ViewData with that name.

Should I use JSLint or JSHint JavaScript validation?

Well, Instead of doing manual lint settings we can include all the lint settings at the top of our JS file itself e.g.

Declare all the global var in that file like:

/*global require,dojo,dojoConfig,alert */

Declare all the lint settings like:

/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */

Hope this will help you :)

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

@EH_warch You need to use the Complete callback to generate your base64:

onAnimationComplete: function(){
    console.log(this.toBase64Image())
}

If you see a white image, it means you called the toBase64Image before it finished rendering.

How to find duplicate records in PostgreSQL

In order to make it easier I assume that you wish to apply a unique constraint only for column year and the primary key is a column named id.

In order to find duplicate values you should run,

SELECT year, COUNT(id)
FROM YOUR_TABLE
GROUP BY year
HAVING COUNT(id) > 1
ORDER BY COUNT(id);

Using the sql statement above you get a table which contains all the duplicate years in your table. In order to delete all the duplicates except of the the latest duplicate entry you should use the above sql statement.

DELETE
FROM YOUR_TABLE A USING YOUR_TABLE_AGAIN B
WHERE A.year=B.year AND A.id<B.id;

Check if any type of files exist in a directory using BATCH script

To check if a folder contains at least one file

>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)

To check if a folder or any of its descendents contain at least one file

>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)

To check if a folder contains at least one file or folder.
Note addition of /a option to enable finding of hidden and system files/folders.

dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)

To check if a folder contains at least one folder

dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

just put #login-box before <h2>Welcome</h2> will be ok.

<div class='container'>
    <div class='hero-unit'>
        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>
        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

here is jsfiddle http://jsfiddle.net/SyjjW/4/

Sending HTTP Post request with SOAP action using org.apache.http

The soapAction must passed as a http-header parameter - when used, it's not part of the http-body/payload.

Look here for an example with apache httpclient: http://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/examples/PostSOAP.java

Java, How to add values to Array List used as value in HashMap

First, you have to lookup the correct ArrayList in the HashMap:

ArrayList<String> myAList = theHashMap.get(courseID)

Then, add the new grade to the ArrayList:

myAList.add(newGrade)

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

Increment a database field by 1

You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column

create table logins (userid int auto_increment primary key, 
  username varchar(30), password varchar(30));

then no special code is needed on insert. Just

insert into logins (username, password) values ('user','pass');

The MySQL API has functions to tell you what userid was created when you execute this statement in client code.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

Using BigDecimal to work with currencies

Primitive numeric types are useful for storing single values in memory. But when dealing with calculation using double and float types, there is a problems with the rounding.It happens because memory representation doesn't map exactly to the value. For example, a double value is supposed to take 64 bits but Java doesn't use all 64 bits.It only stores what it thinks the important parts of the number. So you can arrive to the wrong values when you adding values together of the float or double type.

Please see a short clip https://youtu.be/EXxUSz9x7BM

Static Final Variable in Java

Just having final will have the intended effect.

final int x = 5;

...
x = 10; // this will cause a compilation error because x is final

Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x

Loading context in Spring using web.xml

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

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

You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info

How to resolve javax.mail.AuthenticationFailedException issue?

The problem is, you are creating a transport object and using it's connect method to authenticate yourself. But then you use a static method to send the message which ignores authentication done by the object.

So, you should either use the sendMessage(message, message.getAllRecipients()) method on the object or use an authenticator as suggested by others to get authorize through the session.

Here's the Java Mail FAQ, you need to read.

Convert a bitmap into a byte array

Save the Image to a MemoryStream and then grab the byte array.

http://msdn.microsoft.com/en-us/library/ms142148.aspx

  Byte[] data;

  using (var memoryStream = new MemoryStream())
  {
    image.Save(memoryStream, ImageFormat.Bmp);

    data = memoryStream.ToArray();
  }

Android Studio - Device is connected but 'offline'

If your app doesn't manipulate WiFi connections - another slightly different solution, which bypasses USB issues entirely - enabling a wireless debugging connection - ADB over WiFi/TCP/IP.

How do I convert NSMutableArray to NSArray?

If you're constructing an array via mutability and then want to return an immutable version, you can simply return the mutable array as an "NSArray" via inheritance.

- (NSArray *)arrayOfStrings {
    NSMutableArray *mutableArray = [NSMutableArray array];
    mutableArray[0] = @"foo";
    mutableArray[1] = @"bar";

    return mutableArray;
}

If you "trust" the caller to treat the (technically still mutable) return object as an immutable NSArray, this is a cheaper option than [mutableArray copy].

Apple concurs:

To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.

The above practice is discussed in more detail here:

Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray

How do I POST an array of objects with $.ajax (jQuery or Zepto)

edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).

As simple as:

JSON.stringify(yourData)

You should encode you data in JSON before sending it, you can't just send an object like this as POST data.

I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:

$.post(_saveDeviceUrl, {
    data : $.toJSON(postData)
}, function(response){
    //Process your response here
}
);

How can I know if a branch has been already merged into master?

In order to verify which branches are merged into master you should use these commands:

  • git branch <flag[-r/-a/none]> --merged master list of all branches merged into master.
  • git branch <flag[-r/-a/none]> --merged master | wc -l count number of all branches merged into master.

Flags Are:

  • -a flag - (all) showing remote and local branches
  • -r flag - (remote) showing remote branches only
  • <emptyFlag> - showing local branches only

for example: git branch -r --merged master will show you all remote repositories merged into master.

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

How to remove all white spaces in java

java.lang.String class has method substring not substr , thats the error in your program.

Moreover you can do this in one single line if you are ok in using regular expression.

a.replaceAll("\\s+","");

How to filter JSON Data in JavaScript or jQuery?

The following code works for me:

_x000D_
_x000D_
var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]_x000D_
_x000D_
var data_filter = data.filter( element => element.website =="yahoo")_x000D_
console.log(data_filter)
_x000D_
_x000D_
_x000D_

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I have found the problem.

The problem was that the HTML I was trying to validate was not contained within a <form>...</form> tag.

As soon as I did that, I had a context that was not null.

How to get records randomly from the oracle database?

Here's how to pick a random sample out of each group:

SELECT GROUPING_COLUMN, 
       MIN (COLUMN_NAME) KEEP (DENSE_RANK FIRST ORDER BY DBMS_RANDOM.VALUE) 
         AS RANDOM_SAMPLE
FROM TABLE_NAME
GROUP BY GROUPING_COLUMN
ORDER BY GROUPING_COLUMN;

I'm not sure how efficient it is, but if you have a lot of categories and sub-categories, this seems to do the job nicely.

How to create a numeric vector of zero length in R

This isn't a very beautiful answer, but it's what I use to create zero-length vectors:

0[-1]     # numeric
""[-1]    # character
TRUE[-1]  # logical
0L[-1]    # integer

A literal is a vector of length 1, and [-1] removes the first element (the only element in this case) from the vector, leaving a vector with zero elements.

As a bonus, if you want a single NA of the respective type:

0[NA]     # numeric
""[NA]    # character
TRUE[NA]  # logical
0L[NA]    # integer

Passing a 2D array to a C++ function

A modification to shengy's first suggestion, you can use templates to make the function accept a multi-dimensional array variable (instead of storing an array of pointers that have to be managed and deleted):

template <size_t size_x, size_t size_y>
void func(double (&arr)[size_x][size_y])
{
    printf("%p\n", &arr);
}

int main()
{
    double a1[10][10];
    double a2[5][5];

    printf("%p\n%p\n\n", &a1, &a2);
    func(a1);
    func(a2);

    return 0;
}

The print statements are there to show that the arrays are getting passed by reference (by displaying the variables' addresses)

mvn command is not recognized as an internal or external command

For Windows you need to do the following:

  1. Windows and type env

  2. Open the edit environment panel

  3. Click Environment Variables

  4. In the system variables section, double click Path

  5. In the dialog, create a System Variable under Path like below ->

    MVN_HOME: C:\Users<username>\Documents\Project\Software\apache-maven-3.6.3\bin

  6. Open a new command prompt and hit mvn, you should be able to now.

Should C# or C++ be chosen for learning Games Programming (consoles)?

To tell the truth...you have to make the decision as to which is the better language. I know what I can do with C#. I know what can be done in C++. C# isn't made to do what C++ was made to do...write code at the most basic level and still be somewhat meaningful when read by human eyes.

We are developing a game engine with C#, DirectX...is it a challenge? hell yeah...but it's something we chose to do. We are looking at some performance levels that are very close to what C++ can give. So, I see no problems with this effort.

To cross-platform development, if it weren't for .Net, we might not have the Mono platform. The Mono platform has broadened our platform base.

Here is some support to my arguments...

How to check if that data already exist in the database during update (Mongoose And Express)

For anybody falling on this old solution. There is a better way from the mongoose docs.

var s = new Schema({ name: { type: String, unique: true }});
s.path('name').index({ unique: true });

Get user's non-truncated Active Directory groups from command line

GPRESULT is the right command, but it cannot be run without parameters. /v or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using

gpresult /user myAccount /v > C:\dev\me.txt--Ensure C:\Dev\me.txt exists

Another option is to display summary information only which may be entirely visible in the command window:

gpresult /user myAccount /r

The accounts are listed under the heading:

The user is a part of the following security groups
---------------------------------------------------

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).

Also, make sure your user is allowed to connect to whatever database you're trying to select.

error: expected unqualified-id before ā€˜.ā€™ token //(struct)

ReducedForm is a type, so you cannot say

ReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;

You can only use the . operator on an instance:

ReducedForm rf;
rf.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;

How to get file path from OpenFileDialog and FolderBrowserDialog?

For OpenFileDialog:

OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;

if (choofdlog.ShowDialog() == DialogResult.OK)    
{     
    string sFileName = choofdlog.FileName; 
    string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true           
}

For FolderBrowserDialog:

FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description"; 

if (fbd.ShowDialog() == DialogResult.OK)
{
    string sSelectedPath = fbd.SelectedPath;
}

To access selected folder and selected file name you can declare both string at class level.

namespace filereplacer
{
   public partial class Form1 : Form
   {
      string sSelectedFile;
      string sSelectedFolder;

      public Form1()
      {
         InitializeComponent();
      }

      private void direc_Click(object sender, EventArgs e)
      {
         FolderBrowserDialog fbd = new FolderBrowserDialog();
         //fbd.Description = "Custom Description"; //not mandatory

         if (fbd.ShowDialog() == DialogResult.OK)      
               sSelectedFolder = fbd.SelectedPath;
         else
               sSelectedFolder = string.Empty;    
      }

      private void choof_Click(object sender, EventArgs e)
      {
         OpenFileDialog choofdlog = new OpenFileDialog();
         choofdlog.Filter = "All Files (*.*)|*.*";
         choofdlog.FilterIndex = 1;
         choofdlog.Multiselect = true;

         if (choofdlog.ShowDialog() == DialogResult.OK)                 
             sSelectedFile = choofdlog.FileName;            
         else
             sSelectedFile = string.Empty;       
      }

      private void replacebtn_Click(object sender, EventArgs e)
      {
          if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
          {
               //use selected folder path and file path
          }
      }
      ....
}

NOTE:

As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).

In that case you could get all selected files in string[]:

At Class Level:

string[] arrAllFiles;

Locate this line (when Multiselect=true this line gives first file only):

sSelectedFile = choofdlog.FileName; 

To get all files use this:

arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files

How can I use pointers in Java?

Java does not have pointers like C has, but it does allow you to create new objects on the heap which are "referenced" by variables. The lack of pointers is to stop Java programs from referencing memory locations illegally, and also enables Garbage Collection to be automatically carried out by the Java Virtual Machine.

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

Android Studio: Add jar as library?

'compile files...' used to work for me, but not any more. after much pain, I found that using this instead works:

compile fileTree(dir: 'libs', include: '*.jar')

I have no idea why that made a difference, but, at least the damn thing is working now.

How to check if internet connection is present in Java?

URL url=new URL("http://[any domain]");
URLConnection con=url.openConnection();

/*now errors WILL arise here, i hav tried myself and it always shows "connected" so we'll open an InputStream on the connection, this way we know for sure that we're connected to d internet */

/* Get input stream */
con.getInputStream();

Put the above statements in try catch blocks and if an exception in caught means that there's no internet connection established. :-)

How do I check two or more conditions in one <c:if>?

If you are using JSP 2.0 and above It will come with the EL support: so that you can write in plain english and use and with empty operators to write your test:

<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">

java.io.IOException: Invalid Keystore format

Maybe maven encoding you KeyStore, you can set filtering=false to fix this problem.

<build>
    ...
    <resources>
        <resource>
            ...
            <!-- set filtering=false to fix -->
            <filtering>false</filtering>
            ...
        </resource>
    </resources>
</build>

Push origin master error on new repository

make sure you are on a branch, at least in master branch

type:

git branch

you should see:

ubuntu-user:~/git/turmeric-releng$ git branch

* (no branch)
master

then type:

git checkout master

then all your changes will fit in master branch (or the branch u choose)

What is the easiest way to encrypt a password when I save it to the registry?

If you need more than this, for example securing a connection string (for connection to a database), check this article, as it provides the best "option" for this.

Oli's answer is also good, as it shows how you can create a hash for a string.

Running a command in a new Mac OS X Terminal window

I call this script trun. I suggest putting it in a directory in your executable path. Make sure it is executable like this:

chmod +x ~/bin/trun

Then you can run commands in a new window by just adding trun before them, like this:

trun tail -f /var/log/system.log

Here's the script. It does some fancy things like pass your arguments, change the title bar, clear the screen to remove shell startup clutter, remove its file when its done. By using a unique file for each new window it can be used to create many windows at the same time.

#!/bin/bash
# make this file executable with chmod +x trun
# create a unique file in /tmp
trun_cmd=`mktemp`
# make it cd back to where we are now
echo "cd `pwd`" >$trun_cmd
# make the title bar contain the command being run
echo 'echo -n -e "\033]0;'$*'\007"' >>$trun_cmd
# clear window
echo clear >>$trun_cmd
# the shell command to execute
echo $* >>$trun_cmd
# make the command remove itself
echo rm $trun_cmd >>$trun_cmd
# make the file executable
chmod +x $trun_cmd

# open it in Terminal to run it in a new Terminal window
open -b com.apple.terminal $trun_cmd

Capturing a form submit with jquery and .submit

Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.

What does numpy.random.seed(0) do?

np.random.seed(0) makes the random numbers predictable

>>> numpy.random.seed(0) ; numpy.random.rand(4)
array([ 0.55,  0.72,  0.6 ,  0.54])
>>> numpy.random.seed(0) ; numpy.random.rand(4)
array([ 0.55,  0.72,  0.6 ,  0.54])

With the seed reset (every time), the same set of numbers will appear every time.

If the random seed is not reset, different numbers appear with every invocation:

>>> numpy.random.rand(4)
array([ 0.42,  0.65,  0.44,  0.89])
>>> numpy.random.rand(4)
array([ 0.96,  0.38,  0.79,  0.53])

(pseudo-)random numbers work by starting with a number (the seed), multiplying it by a large number, adding an offset, then taking modulo of that sum. The resulting number is then used as the seed to generate the next "random" number. When you set the seed (every time), it does the same thing every time, giving you the same numbers.

If you want seemingly random numbers, do not set the seed. If you have code that uses random numbers that you want to debug, however, it can be very helpful to set the seed before each run so that the code does the same thing every time you run it.

To get the most random numbers for each run, call numpy.random.seed(). This will cause numpy to set the seed to a random number obtained from /dev/urandom or its Windows analog or, if neither of those is available, it will use the clock.

For more information on using seeds to generate pseudo-random numbers, see wikipedia.

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

How to merge rows in a column into one cell in excel?

I know this is really a really old question, but I was trying to do the same thing and I stumbled upon a new formula in excel called "TEXTJOIN".

For the question, the following formula solves the problem

=TEXTJOIN("",TRUE,(a1:a4))

The signature of "TEXTJOIN" is explained as TEXTJOIN(delimiter,ignore_empty,text1,[text2],[text3],...)

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is the predefined environmental variable in Linux/Unix which sets the path which the linker should look in to while linking dynamic libraries/shared libraries.

LD_LIBRARY_PATH contains a colon separated list of paths and the linker gives priority to these paths over the standard library paths /lib and /usr/lib. The standard paths will still be searched, but only after the list of paths in LD_LIBRARY_PATH has been exhausted.

The best way to use LD_LIBRARY_PATH is to set it on the command line or script immediately before executing the program. This way the new LD_LIBRARY_PATH isolated from the rest of your system.

Example Usage:

$ export LD_LIBRARY_PATH="/list/of/library/paths:/another/path"
$ ./program

Since you talk about .dll you are on a windows system and a .dll must be placed at a path which the linker searches at link time, in windows this path is set by the environmental variable PATH, So add that .dll to PATH and it should work fine.

What's the best way to store a group of constants that my program uses?

What I like to do is the following (but make sure to read to the end to use the proper type of constants):

internal static class ColumnKeys
{
    internal const string Date = "Date";
    internal const string Value = "Value";
    ...
}

Read this to know why const might not be what you want. Possible type of constants are:

  • const fields. Do not use across assemblies (public or protected) if value might change in future because the value will be hardcoded at compile-time in those other assemblies. If you change the value, the old value will be used by the other assemblies until they are re-compiled.
  • static readonly fields
  • static property without set

Change the mouse pointer using JavaScript

Javascript is pretty good at manipulating css.

 document.body.style.cursor = *cursor-url*;
 //OR
 var elementToChange = document.getElementsByTagName("body")[0];
 elementToChange.style.cursor = "url('cursor url with protocol'), auto";

or with jquery:

$("html").css("cursor: url('cursor url with protocol'), auto");

Firefox will not work unless you specify a default cursor after the imaged one!

other cursor keywords

Also remember that IE6 only supports .cur and .ani cursors.

If cursor doesn't change: In case you are moving the element under the cursor relative to the cursor position (e.g. element dragging) you have to force a redraw on the element:

// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);

working sample:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First jQuery-Enabled Page</title>
<style type="text/css">

div {
    height: 100px;
    width: 1000px;
    background-color: red;
}

</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script></head>
<body>
<div>
hello with a fancy cursor!
</div>
</body>
<script type="text/javascript">
document.getElementsByTagName("body")[0].style.cursor = "url('http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur'), auto";


</script>
</html>

How do you scroll up/down on the console of a Linux VM

In some VPS hostings (like linode) you have to click Ctrl+A and then ESC. Exit with double ESC too.

How to make an input type=button act like a hyperlink and redirect using a get request?

For those who stumble upon this from a search (Google) and are trying to translate to .NET and MVC code. (as in my case)

@using (Html.BeginForm("RemoveLostRolls", "Process", FormMethod.Get)) {
     <input type="submit" value="Process" />
}

This will show a button labeled "Process" and take you to "/Process/RemoveLostRolls". Without "FormMethod.Get" it worked, but was seen as a "post".

Chaining multiple filter() in Django, is this a bug?

From Django docs :

To handle both of these situations, Django has a consistent way of processing filter() calls. Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects, but for multi-valued relations, they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

  • It is clearly said that multiple conditions in a single filter() are applied simultaneously. That means that doing :
objs = Mymodel.objects.filter(a=True, b=False)

will return a queryset with raws from model Mymodel where a=True AND b=False.

  • Successive filter(), in some case, will provide the same result. Doing :
objs = Mymodel.objects.filter(a=True).filter(b=False)

will return a queryset with raws from model Mymodel where a=True AND b=False too. Since you obtain "first" a queryset with records which have a=True and then it's restricted to those who have b=False at the same time.

  • The difference in chaining filter() comes when there are multi-valued relations, which means you are going through other models (such as the example given in the docs, between Blog and Entry models). It is said that in that case (...) they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

Which means that it applies the successives filter() on the target model directly, not on previous filter()

If I take the example from the docs :

Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)

remember that it's the model Blog that is filtered, not the Entry. So it will treat the 2 filter() independently.

It will, for instance, return a queryset with Blogs, that have entries that contain 'Lennon' (even if they are not from 2008) and entries that are from 2008 (even if their headline does not contain 'Lennon')

THIS ANSWER goes even further in the explanation. And the original question is similar.

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Similar to a few posts prior - I went to SDK Manager and uninstalled v20 and version L. Then I installed version 19 and this problem was resolved and I could debug using my android device, no errors.

beyond top level package error in relative import

As the most popular answer suggests, basically its because your PYTHONPATH or sys.path includes . but not your path to your package. And the relative import is relative to your current working directory, not the file where the import happens; oddly.

You could fix this by first changing your relative import to absolute and then either starting it with:

PYTHONPATH=/path/to/package python -m test_A.test

OR forcing the python path when called this way, because:

With python -m test_A.test you're executing test_A/test.py with __name__ == '__main__' and __file__ == '/absolute/path/to/test_A/test.py'

That means that in test.py you could use your absolute import semi-protected in the main case condition and also do some one-time Python path manipulation:

from os import path
ā€¦
def main():
ā€¦
if __name__ == '__main__':
    import sys
    sys.path.append(path.join(path.dirname(__file__), '..'))
    from A import foo

    exit(main())

Java program to find the largest & smallest number in n numbers without using arrays

@user3168844: try the below code:

import java.util.Scanner;

public class LargestSmallestNum {

    public void findLargestSmallestNo() {

        int smallest = Integer.MAX_VALUE;
        int large = 0;
        int num;

        System.out.println("enter the number");

        Scanner input = new Scanner(System.in);

        int n = input.nextInt();

        for (int i = 0; i < n; i++) {

            num = input.nextInt();

            if (num > large)
                large = num;

            if (num < smallest)
                smallest = num;

            System.out.println("the largest is:" + large);
            System.out.println("Smallest no is : "  + smallest);
        }
    }

    public static void main(String...strings){
        LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
        largestSmallestNum.findLargestSmalestNo();
    }
}

dlib installation on Windows 10

Choose dlib .whl file according to your installed python version. For example if installed python version is 3.6.7 , 64bit system or if python is 3.5.0 32 bit then choose dlib-19.5.1-cp36-cp36m-win_amd64.whl and dlib-18.17.100-cp35-none-win32.whl respectively.

Bolded text says the python supporting version.

Download wheel file from here or copy the link address

pip install dlib-19.5.1-cp36-cp36m-win_amd64.whl

for above method .whl file shoud be in the working directory

or

Below link for python3.6 supporting dlib link, for python 3.5 u can replace with dlib 35.whl link

pip install https://files.pythonhosted.org/packages/24/ea/81e4fc5b978277899b1c1a63ff358f1f645f9369e59d9b5d9cc1d57c007c/dlib-19.5.1-cp36-cp36m-win_amd64.whl#sha256=7739535b76eb40cbcf49ba98d894894d06ee0b6e8f18a25fef2ab302fd5401c7

How to use the switch statement in R functions?

This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

while (TRUE) {
  if (is.na(val)) {
    val <- "NULL"
    break
  }
  if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
    val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
    break
  }
  if (inherits(val, "Date")) {
    val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
    break
  }
  if (is.numeric(val)) break
  val <- paste0("'", gsub("'", "''", val), "'")
  break
}

How can I change the default Mysql connection timeout when connecting through python?

I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect call. For example,

con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
          connect_timeout=1000)

Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.

For detail about different arguments that you can pass to _mysql.connect, see MySQLdb API documentation

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

How to inspect FormData?

Here's a function to log entries of a FormData object to the console as an object.

export const logFormData = (formData) => {
    const entries = formData.entries();
    const result = {};
    let next;
    let pair;
    while ((next = entries.next()) && next.done === false) {
        pair = next.value;
        result[pair[0]] = pair[1];
    }
    console.log(result);
};

MDN doc on .entries()

MDN doc on .next() and .done

Conda activate not working?

Functions are not exported by default to be made available in subshells. I'd recommend you do:

source ~/anaconda3/etc/profile.d/conda.sh
conda activate my_env

In the commands above, replace ~/anaconda3/ with the path to your miniconda / anaconda installation.

Update value of a nested dictionary of varying depth

Another way of using recursion:

def updateDict(dict1,dict2):
    keys1 = list(dict1.keys())
    keys2= list(dict2.keys())
    keys2 = [x for x in keys2 if x in keys1]
    for x in keys2:
        if (x in keys1) & (type(dict1[x]) is dict) & (type(dict2[x]) is dict):
            updateDict(dict1[x],dict2[x])
        else:
            dict1.update({x:dict2[x]})
    return(dict1)

How to hide form code from view code/inspect element browser?

There is a smart way to disable inspect element in your website. Just add the following snippet inside script tag :

$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});

Please check out this blog

The function key F12 which directly take inspect element from browser, we can also disable it, by using the following code:

$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});

Get value of div content using jquery

Try this to get value of div content using jquery.

_x000D_
_x000D_
    $(".showplaintext").click(function(){_x000D_
        alert($(".plain").text());_x000D_
    });_x000D_
    _x000D_
    // Show text content of formatted paragraph_x000D_
    $(".showformattedtext").click(function(){_x000D_
        alert($(".formatted").text());_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p class="plain">Exploring the zoo, we saw every kangaroo jump and quite a few carried babies. </p>_x000D_
    <p class="formatted">Exploring the zoo<strong>, we saw every kangaroo</strong> jump <em><sup> and quite a </sup></em>few carried <a href="#"> babies</a>.</p>_x000D_
    <button type="button" class="showplaintext">Get Plain Text</button>_x000D_
    <button type="button" class="showformattedtext">Get Formatted Text</button>
_x000D_
_x000D_
_x000D_

Taken from @ Get the text inside an element using jQuery

Calculate cosine similarity given 2 sentence strings

Well, if you are aware of word embeddings like Glove/Word2Vec/Numberbatch, your job is half done. If not let me explain how this can be tackled. Convert each sentence into word tokens, and represent each of these tokens as vectors of high dimension (using the pre-trained word embeddings, or you could train them yourself even!). So, now you just don't capture their surface similarity but rather extract the meaning of each word which comprise the sentence as a whole. After this calculate their cosine similarity and you are set.

Open Facebook page from Android app?

this is the simplest code for doing this

public final void launchFacebook() {
        final String urlFb = "fb://page/"+yourpageid;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(urlFb));

        // If a Facebook app is installed, use it. Otherwise, launch
        // a browser
        final PackageManager packageManager = getPackageManager();
        List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() == 0) {
            final String urlBrowser = "https://www.facebook.com/"+pageid;
            intent.setData(Uri.parse(urlBrowser));
        }

        startActivity(intent);
    }

Which to use <div class="name"> or <div id="name">?

The object itself will not change. The main difference between these 2 keyword is the use:

  • The ID is usually single in the page
  • The class can have one or many occurences

In the CSS or Javascript files:

  • The ID will be accessed by the character #
  • The class will be accessed by the character .

list.clear() vs list = new ArrayList<Integer>();

It's hard to know without a benchmark, but if you have lots of items in your ArrayList and the average size is lower, it might be faster to make a new ArrayList.

http://www.docjar.com/html/api/java/util/ArrayList.java.html

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

Split a python list into other "sublists" i.e smaller lists

I'd say

chunks = [data[x:x+100] for x in range(0, len(data), 100)]

If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange(), changing the above code to:

chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

Android Studio Emulator and "Process finished with exit code 0"

I had this issue in Android Studio 3.1 :

I only have on board graphics. Went to Tools -> AVD Manager -> (Edit this AVD) under Actions -> Emulated Performance (Graphics): select "Software GLES 2.0".

Proper use of const for defining functions in JavaScript

It has been three years since this question was asked, but I am just now coming across it. Since this answer is so far down the stack, please allow me to repeat it:

Q: I am interested if there are any limits to what types of values can be set using const in JavaScriptā€”in particular functions. Is this valid? Granted it does work, but is it considered bad practice for any reason?

I was motivated to do some research after observing one prolific JavaScript coder who always uses const statement for functions, even when there is no apparent reason/benefit.

In answer to "is it considered bad practice for any reason?" let me say, IMO, yes it is, or at least, there are advantages to using function statement.

It seems to me that this is largely a matter of preference and style. There are some good arguments presented above, but none so clear as is done in this article:

Constant confusion: why I still use JavaScript function statements by medium.freecodecamp.org/Bill Sourour, JavaScript guru, consultant, and teacher.

I urge everyone to read that article, even if you have already made a decision.

Here's are the main points:

Function statements have two clear advantages over [const] function expressions:

Advantage #1: Clarity of intent

When scanning through thousands of lines of code a day, itā€™s useful to be able to figure out the programmerā€™s intent as quickly and easily as possible.

Advantage #2: Order of declaration == order of execution

Ideally, I want to declare my code more or less in the order that I expect it will get executed.

This is the showstopper for me: any value declared using the const keyword is inaccessible until execution reaches it.

What Iā€™ve just described above forces us to write code that looks upside down. We have to start with the lowest level function and work our way up.

My brain doesnā€™t work that way. I want the context before the details.

Most code is written by humans. So it makes sense that most peopleā€™s order of understanding roughly follows most codeā€™s order of execution.

JavaScript - onClick to get the ID of the clicked button

USING PURE JAVASCRIPT: I know it's late but may be for the future people it can help:

In the HTML part:

<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>

In the Javascipt Controller:

function reply_click()
{
    alert(event.srcElement.id);
}

This way we don't have to bind the 'id' of the Element at the time of calling the javascript function.

How to implement the Softmax function in Python

sklearn also offers implementation of softmax

from sklearn.utils.extmath import softmax
import numpy as np

x = np.array([[ 0.50839931,  0.49767588,  0.51260159]])
softmax(x)

# output
array([[ 0.3340521 ,  0.33048906,  0.33545884]]) 

Generating (pseudo)random alpha-numeric strings

I like this function for the job

function randomKey($length) {
    $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));

    for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
    }
    return $key;
}

echo randomKey(20);

check if "it's a number" function in Oracle

I'm against using when others so I would use (returning an "boolean integer" due to SQL not suppporting booleans)

create or replace function is_number(param in varchar2) return integer
 is
   ret number;
 begin
    ret := to_number(param);
    return 1; --true
 exception
    when invalid_number then return 0;
 end;

In the SQL call you would use something like

select case when ( is_number(myTable.id)=1 and (myTable.id >'0') ) 
            then 'Is a number greater than 0' 
            else 'it is not a number or is not greater than 0' 
       end as valuetype  
  from table myTable

How to make a <div> always full screen?

This is my solution to create a fullscreen div, using pure css. It displays a full screen div that is persistent on scrolling. And if the page content fits on the screen, the page won't show a scroll-bar.

Tested in IE9+, Firefox 13+, Chrome 21+

_x000D_
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title> Fullscreen Div </title>_x000D_
  <style>_x000D_
  .overlay {_x000D_
    position: fixed;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    background: rgba(51,51,51,0.7);_x000D_
    z-index: 10;_x000D_
  }_x000D_
  </style>_x000D_
</head>_x000D_
<body>_x000D_
  <div class='overlay'>Selectable text</div>_x000D_
  <p> This paragraph is located below the overlay, and cannot be selected because of that :)</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Thread pooling in C++11

A pool of threads means that all your threads are running, all the time – in other words, the thread function never returns. To give the threads something meaningful to do, you have to design a system of inter-thread communication, both for the purpose of telling the thread that there's something to do, as well as for communicating the actual work data.

Typically this will involve some kind of concurrent data structure, and each thread would presumably sleep on some kind of condition variable, which would be notified when there's work to do. Upon receiving the notification, one or several of the threads wake up, recover a task from the concurrent data structure, process it, and store the result in an analogous fashion.

The thread would then go on to check whether there's even more work to do, and if not go back to sleep.

The upshot is that you have to design all this yourself, since there isn't a natural notion of "work" that's universally applicable. It's quite a bit of work, and there are some subtle issues you have to get right. (You can program in Go if you like a system which takes care of thread management for you behind the scenes.)

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

What is an index in SQL?

A clustered index is like the contents of a phone book. You can open the book at 'Hilditch, David' and find all the information for all of the 'Hilditch's right next to each other. Here the keys for the clustered index are (lastname, firstname).

This makes clustered indexes great for retrieving lots of data based on range based queries since all the data is located next to each other.

Since the clustered index is actually related to how the data is stored, there is only one of them possible per table (although you can cheat to simulate multiple clustered indexes).

A non-clustered index is different in that you can have many of them and they then point at the data in the clustered index. You could have e.g. a non-clustered index at the back of a phone book which is keyed on (town, address)

Imagine if you had to search through the phone book for all the people who live in 'London' - with only the clustered index you would have to search every single item in the phone book since the key on the clustered index is on (lastname, firstname) and as a result the people living in London are scattered randomly throughout the index.

If you have a non-clustered index on (town) then these queries can be performed much more quickly.

Hope that helps!

How to check command line parameter in ".bat" file?

I've been struggling recently with the implementation of complex parameter switches in a batch file so here is the result of my research. None of the provided answers are fully safe, examples:

"%1"=="-?" will not match if the parameter is enclosed in quotes (needed for file names etc.) or will crash if the parameter is in quotes and has spaces (again often seen in file names)

@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
rem echo First parameter is %1
if "%1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -?

starting parameter test...

Condition is true, param=-?

C:\>test.bat "-?"

starting parameter test...

Condition is false, param="-?"

Any combination with square brackets [%1]==[-?] or [%~1]==[-?] will fail in case the parameter has spaces within quotes:

@ECHO OFF
SETLOCAL 
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if [%~1]==[-?] (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat "long file name"

starting parameter test...

First parameter is "long file name"
file was unexpected at this time.

The proposed safest solution "%~1"=="-?" will crash with a complex parameter that includes text outside the quotes and text with spaces within the quotes:

@ECHO OFF
SETLOCAL 
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if "%~1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat -source:"long file name"

starting parameter test...

First parameter is -source:"long file name"
file was unexpected at this time.

The only way to ensure all above scenarios are covered is to use EnableDelayedExpansion and to pass the parameters by reference (not by value) using variables. Then even the most complex scenario will work fine:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
echo.
echo starting parameter test...
echo.
echo First parameter is %1
:: we assign the parameter to a variable to pass by reference with delayed expansion
set "var1=%~1"
echo var1 is !var1!
:: we assign the value to compare with to a second variable to pass by reference with delayed expansion
set "var2=-source:"c:\app images"\image.png"
echo var2 is !var2!
if "!var1!"=="!var2!" (echo Condition is true, param=!var1!) else (echo Condition is false, param=!var1!)
C:\>test.bat -source:"c:\app images"\image.png

starting parameter test...

First parameter is -source:"c:\app images"\image.png
var1 is -source:"c:\app images"\image.png
var2 is -source:"c:\app images"\image.png
Condition is true, param=-source:"c:\app images"\image.png

C:\>test.bat -source:"c:\app images"\image1.png

starting parameter test...

First parameter is -source:"c:\app images"\image1.png
var1 is -source:"c:\app images"\image1.png
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images"\image1.png

C:\>test.bat -source:"c:\app images\image.png"

starting parameter test...

First parameter is -source:"c:\app images\image.png"
var1 is -source:"c:\app images\image.png"
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images\image.png"

Maximum value for long integer

You can use: max value of float is

float('inf')

for negative

float('-inf')

Return row of Data Frame based on value in a column - R

Based on the syntax provided

 Select * Where Amount = min(Amount)

You could do using:

 library(sqldf)

Using @Kara Woo's example df

  sqldf("select * from df where Amount in (select min(Amount) from df)")
  #Name Amount
 #1    B    120
 #2    E    120

Filtering array of objects with lodash based on property value

lodash also has a remove method

var myArr = [
    { name: "john", age: 23 },
    { name: "john", age: 43 },
    { name: "jim", age: 101 },
    { name: "bob", age: 67 }
];

var onlyJohn = myArr.remove( person => { return person.name == "john" })

Smooth scrolling with just pure css

You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.

You're likely best placed to use e.g. jQuery, specifically:

$('html, body').stop().animate({
   scrollTop: element.offset().top
}, 1000);

A complete implementation may be:

$('#up, #down').on('click', function(e){
    e.preventDefault();
    var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
    $('html, body').stop().animate({
       scrollTop: target.offset().top
    }, 1000);
});

Where element is the target element to scroll to and 1000 is the delay in ms before completion.

Demo Fiddle

The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.

How do I clone a generic List in Java?

I find using addAll works fine.

ArrayList<String> copy = new ArrayList<String>();
copy.addAll(original);

parentheses are used rather than the generics syntax

How to update and delete a cookie?

check this out A little framework: a complete cookies reader/writer with full Unicode support

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

How to Calculate Execution Time of a Code Snippet in C++

It is better to run the inner loop several times with the performance timing only once and average by dividing inner loop repetitions than to run the whole thing (loop + performance timing) several times and average. This will reduce the overhead of the performance timing code vs your actual profiled section.

Wrap your timer calls for the appropriate system. For Windows, QueryPerformanceCounter is pretty fast and "safe" to use.

You can use "rdtsc" on any modern X86 PC as well but there may be issues on some multicore machines (core hopping may change timer) or if you have speed-step of some sort turned on.

C# declare empty string array

Try this

string[] arr = new string[] {};

What's the difference between an element and a node in XML?

A Node is a part of the DOM tree, an Element is a particular type of Node

e.g. <foo> This is Text </foo>

You have a foo Element, (which is also a Node, as Element inherits from Node) and a Text Node 'This is Text', that is a child of the foo Element/Node

Force Java timezone as GMT/UTC

Also if you can set JVM timezone this way

System.setProperty("user.timezone", "EST");

or -Duser.timezone=GMT in the JVM args.

How to check if an array element exists?

You can also use array_keys for number of occurrences

<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
 echo "Element exists in Array";
?>

How to flush output of print function?

Here is my version, which provides writelines() and fileno(), too:

class FlushFile(object):
    def __init__(self, fd):
        self.fd = fd

    def write(self, x):
        ret = self.fd.write(x)
        self.fd.flush()
        return ret

    def writelines(self, lines):
        ret = self.writelines(lines)
        self.fd.flush()
        return ret

    def flush(self):
        return self.fd.flush

    def close(self):
        return self.fd.close()

    def fileno(self):
        return self.fd.fileno()

Visualizing branch topology in Git

For Mac users, checkout (no pun intended) the free, open source tool GitUp: http://gitup.co/

I like the way the graphs are displayed, it's clearer than some of the other tools I've seen.

The project is here: https://github.com/git-up/GitUp

GitUp screenshot

How to change a package name in Eclipse?

enter image description hereYou can open the class file in eclipse and at the top add "package XYZ(package_name), then while it shows error click to it and select ' move ABC.java(class_file) to package XYZ(package_name)

How to reference Microsoft.Office.Interop.Excel dll?

You have to check which version of Excel you are targeting?

If you are targeting Excel 2010 use version 14 (as per Grant's screenshot answer), Excel 2007 use version 12 . You can not support Excel 2003 using vS2012 as they do not have the correct Interop dll installed.

Adding elements to a C# array

You should take a look at the List object. Lists tend to be better at changing dynamically like you want. Arrays not so much...

How to clear react-native cache?

For React Native Init approach (without expo) use:

npm start -- --reset-cache

How to Check if value exists in a MySQL database

For Matching the ID:

Select * from table_name where 1=1

For Matching the Pattern:

Select * from table_name column_name Like '%string%'

TypeError: got multiple values for argument

I was brought here for a reason not explicitly mentioned in the answers so far, so to save others the trouble:

The error also occurs if the function arguments have changed order - for the same reason as in the accepted answer: the positional arguments clash with the keyword arguments.

In my case it was because the argument order of the Pandas set_axis function changed between 0.20 and 0.22:

0.20: DataFrame.set_axis(axis, labels)
0.22: DataFrame.set_axis(labels, axis=0, inplace=None)

Using the commonly found examples for set_axis results in this confusing error, since when you call:

df.set_axis(['a', 'b', 'c'], axis=1)

prior to 0.22, ['a', 'b', 'c'] is assigned to axis because it's the first argument, and then the positional argument provides "multiple values".

Error in strings.xml file in Android

You may be able to use unicode equivalent both apostrophe and other characters which are not supported in xml string. Apostrophe's equivalent is "\u0027" .

Declare multiple module.exports in Node.js

You can write a function that manually delegates between the other functions:

module.exports = function(arg) {
    if(arg instanceof String) {
         return doStringThing.apply(this, arguments);
    }else{
         return doObjectThing.apply(this, arguments);
    }
};

How can I merge the columns from two tables into one output?

SELECT col1,
  col2
FROM
  (SELECT rownum X,col_table1 FROM table1) T1
INNER JOIN
  (SELECT rownum Y, col_table2 FROM table2) T2
ON T1.X=T2.Y;

JavaScript equivalent to printf/String.Format

For use with jQuery.ajax() success functions. Pass only a single argument and string replace with the properties of that object as {propertyName}:

String.prototype.format = function () {
    var formatted = this;
    for (var prop in arguments[0]) {
        var regexp = new RegExp('\\{' + prop + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[0][prop]);
    }
    return formatted;
};

Example:

var userInfo = ("Email: {Email} - Phone: {Phone}").format({ Email: "[email protected]", Phone: "123-123-1234" });

Run R script from command line

Just for documentation, sometimes you need to run the script as sudo:

sudo Rscript path/to/your/file.R

Is Constructor Overriding Possible?

I found this as a good example for this question:

    class Publication {

    private String title;

    public Publication(String title) {
        this.title = title;
    }

    public String getDetails() {
        return "title=\"" + title + "\"";
    }

}

class Newspaper extends Publication {

    private String source;

    public Newspaper(String title, String source) {
        super(title);
        this.source = source;
    }

    @Override
    public String getDetails() {
        return super.getDetails() + ", source=\"" + source + "\"";
    }
}

class Article extends Publication {

    private String author;

    public Article(String title, String author) {
        super(title);
        this.author = author;
    }

    @Override
    public String getDetails() {
        return super.getDetails() + ", author=\"" + author + "\"";
    }

}

class Announcement extends Publication {

    private int daysToExpire;

    public Announcement(String title, int daysToExpire) {
        super(title);
        this.daysToExpire = daysToExpire;
    }

    @Override
    public String getDetails() {
        return super.getDetails() + ", daysToExpire=" + daysToExpire;
    }

}

How to enable Google Play App Signing

While Migrating Android application package file (APK) to Android App Bundle (AAB), publishing app into Play Store i faced this issue and got resolved like this below...

When building .aab file you get prompted for the location to store key export path as below:

enter image description here
enter image description here In second image you find Encrypted key export path Location where our .pepk will store in the specific folder while generating .aab file.

Once you log in to the Google Play Console with play store credential: select your project from left side choose App Signing option Release Management>>App Signing enter image description here

you will find the Google App Signing Certification window ACCEPT it.

After that you will find three radio button select **

Upload a key exported from Android Studio radio button

**, it will expand you APP SIGNING PRIVATE KEY button as below

enter image description here

click on the button and choose the .pepk file (We Stored while generating .aab file as above)

Read the all other option and submit.

Once Successfully you can go back to app release and browse the .aab file and complete RollOut...

@Ambilpura

How to pass a PHP variable using the URL

In your link.php your echo statement must be like this:

echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';

Then in your pass.php you cannot use $a because it was not initialized with your intended string value.

You can directly compare it to a string like this:

if($_GET['link'] == 'Link1')

Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a and $b variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.

Java ArrayList of Arrays?

This works very well.

ArrayList<String[]> a = new ArrayList<String[]>();
    a.add(new String[3]);
    a.get(0)[0] = "Zubair";
    a.get(0)[1] = "Borkala";
    a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);

Result will be

Borkala

Check folder size in Bash

To check the size of all of the directories within a directory, you can use:

du -h --max-depth=1

How do I escape reserved words used as column names? MySQL/Create Table

You should use back tick character (`) eg:

create table if not exists misc_info (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL)ENGINE=INNODB;

How to check if a service is running via batch file and start it, if it is not running?

To check a service's state, use sc query <SERVICE_NAME>. For if blocks in batch files, check the documentation.

The following code will check the status of the service MyServiceName and start it if it is not running (the if block will be executed if the service is not running):

for /F "tokens=3 delims=: " %%H in ('sc query "MyServiceName" ^| findstr "        STATE"') do (
  if /I "%%H" NEQ "RUNNING" (
   REM Put your code you want to execute here
   REM For example, the following line
   net start "MyServiceName"
  )
)

Explanation of what it does:

  1. Queries the properties of the service.
  2. Looks for the line containing the text "STATE"
  3. Tokenizes that line, and pulls out the 3rd token, which is the one containing the state of the service.
  4. Tests the resulting state against the string "RUNNING"

As for your second question, the argument you will want to pass to net start is the service name, not the display name.

Clicking the back button twice to exit an activity

This also helps when you have previous stack activity stored in stack.

I have modified Sudheesh's answer

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        //super.onBackPressed();

  Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//***Change Here***
                    startActivity(intent);
                    finish();
                    System.exit(0);
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;                       
        }
    }, 2000);
} 

Multiple axis line chart in excel

There is a way of displaying 3 Y axis see here.

Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Set port for php artisan.php serve

as this example you can change ip and port this works with me

php artisan serve --host=0.0.0.0 --port=8000

Flex-box: Align last row to grid

This is pretty hacky, but it works for me. I was trying to achieve consistent spacing/margins.

.grid {
  width: 1024px;
  display: flex;
  flex-flow: row wrap;
  padding: 32px;
  background-color: #ddd;  

  &:after {
    content: "";
    flex: auto;
    margin-left:-1%;
  }

  .item {
    flex: 1 0 24.25%;
    max-width: 24.25%;
    margin-bottom: 10px;
    text-align: center;
    background-color: #bbb;

    &:nth-child(4n+2),
    &:nth-child(4n+3),
    &:nth-child(4n+4) {
      margin-left: 1%;
    }

    &:nth-child(4n+1):nth-last-child(-n+4),
      &:nth-child(4n+1):nth-last-child(-n+4) ~ .item {
        margin-bottom: 0;
    }    

  }
}

http://codepen.io/rustydev/pen/f7c8920e0beb0ba9a904da7ebd9970ae/

Setting initial values on load with Select2 with Ajax

A very weird way for passing data. I prefer to get a JSON string/object from server and then assign values and stuff.

Anyway, when you do this var elementText = $(element).attr('data-initvalue'); you're getting this [{"id":"IN","name":"India"}]. That result you must PARSE it as suggested above so you can get the real vales for id ("IN") and name("India"). Now there are two scenarios, multi-select & single-value Select2.

Single Values:

$(element).select2({
    initSelection : function (element, callback) {
        var data = {id: "IN", text: "INDIA"};
        callback(data);
    }//Then the rest of your configurations (e.g.: ajax, allowClear, etc.)
});

Multi-Select

$("#tags").select2({
    initSelection : function (element, callback) {
        var countryId = "IN"; //Your values that somehow you parsed them
        var countryText = "INDIA";

        var data = [];//Array

        data.push({id: countryId, text: countryText});//Push values to data array


        callback(data); //Fill'em
    }
});

NOW HERE'S THE TRICK! Like belov91 suggested, you MUST put this...

$(element).select2("val", []);

Even if it's a single or multi-valued Select2. On the other hand remember that you can't assign the Select2 ajax function to a <select> tag, it must be an <input>.

Hope that helped you (or someone).

Bye.

Is bool a native C type?

_Bool is a keyword in C99: it specifies a type, just like int or double.

6.5.2

2 An object declared as type _Bool is large enough to store the values 0 and 1.

len() of a numpy array in python

You can transpose the array if you want to get the length of the other dimension.

len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)

Best Practices for securing a REST API / web service

There is a great checklist found on Github:

Authentication

  • Don't reinvent the wheel in Authentication, token generation, password storage. Use the standards.

  • Use Max Retry and jail features in Login.

  • Use encryption on all sensitive data.

JWT (JSON Web Token)

  • Use a random complicated key (JWT Secret) to make brute forcing the token very hard.

  • Don't extract the algorithm from the payload. Force the algorithm in the backend (HS256 or RS256).

  • Make token expiration (TTL, RTTL) as short as possible.

  • Don't store sensitive data in the JWT payload, it can be decoded easily.

OAuth

  • Always validate redirect_uri server-side to allow only whitelisted URLs.

  • Always try to exchange for code and not tokens (don't allow response_type=token).

  • Use state parameter with a random hash to prevent CSRF on the OAuth authentication process.

  • Define the default scope, and validate scope parameters for each application.

Access

  • Limit requests (Throttling) to avoid DDoS / brute-force attacks.

  • Use HTTPS on server side to avoid MITM (Man In The Middle Attack)

  • Use HSTS header with SSL to avoid SSL Strip attack.

Input

  • Use the proper HTTP method according to the operation: GET (read), POST (create), PUT/PATCH (replace/update), and DELETE (to delete a record), and respond with 405 Method Not Allowed if the requested method isn't appropriate for the requested resource.

  • Validate content-type on request Accept header (Content Negotiation) to allow only your supported format (e.g. application/xml, application/json, etc) and respond with 406 Not Acceptable response if not matched.

  • Validate content-type of posted data as you accept (e.g. application/x-www-form-urlencoded, multipart/form-data, application/json, etc).

  • Validate User input to avoid common vulnerabilities (e.g. XSS, SQL-Injection, Remote Code Execution, etc).

  • Don't use any sensitive data (credentials, Passwords, security tokens, or API keys) in the URL, but use standard Authorization header.

  • Use an API Gateway service to enable caching, Rate Limit policies (e.g. Quota, Spike Arrest, Concurrent Rate Limit) and deploy APIs resources dynamically.

Processing

  • Check if all the endpoints are protected behind authentication to avoid broken authentication process.

  • User own resource ID should be avoided. Use /me/orders instead of /user/654321/orders.

  • Don't auto-increment IDs. Use UUID instead.

  • If you are parsing XML files, make sure entity parsing is not enabled to avoid XXE (XML external entity attack).

  • If you are parsing XML files, make sure entity expansion is not enabled to avoid Billion Laughs/XML bomb via exponential entity expansion attack.

  • Use a CDN for file uploads.

  • If you are dealing with huge amount of data, use Workers and Queues to process as much as possible in background and return response fast to avoid HTTP Blocking.

  • Do not forget to turn the DEBUG mode OFF.

Output

  • Send X-Content-Type-Options: nosniff header.

  • Send X-Frame-Options: deny header.

  • Send Content-Security-Policy: default-src 'none' header.

  • Remove fingerprinting headers - X-Powered-By, Server, X-AspNet-Version etc.

  • Force content-type for your response, if you return application/json then your response content-type is application/json.

  • Don't return sensitive data like credentials, Passwords, security tokens.

  • Return the proper status code according to the operation completed. (e.g. 200 OK, 400 Bad Request, 401 Unauthorized, 405 Method Not Allowed, etc).

How do I discard unstaged changes in Git?

For all unstaged files in current working directory use:

git checkout -- .

For a specific file use:

git checkout -- path/to/file/to/revert

-- here to remove argument disambiguation.

For Git 2.23 onwards, one may want to use the more specific

git restore .

resp.

git restore path/to/file/to/revert

that together with git switch replaces the overloaded git checkout (see here), and thus removes the argument disambiguation.

how to hide the content of the div in css

Without changing the markup or using JavaScript, you'd pretty much have to alter the text color as knut mentions, or set text-indent: -1000em;

IE6 will not read the :hover selector on anything other than an anchor element, so you will have to use something like Dean Edwards' IE7.

Really though, you're better off putting the text in some kind of element (like p or span or a) and setting that to display: none; on hover.

Is there a way to add a gif to a Markdown file?

Upload from local:

  1. Add your .gif file to the root of Github repository and push the change.
  2. Go to README.md
  3. Add this ![Alt text](name-of-gif-file.gif) / ![](name-of-gif-file.gif)
  4. Commit and gif should be seen.

Show the gif using url:

  1. Go to README.md
  2. Add in this format ![Alt text](https://sample/url/name-of-gif-file.gif)
  3. Commit and gif should be seen.

Hope this helps.

Importing a function from a class in another file?

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

FILENAME is w/o the suffix

concat yesterdays date with a specific time

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

should work.

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
_x000D_
_x000D_
_x000D_

Android video streaming example

I had the same problem but finally I found the way.

Here is the walk through:

1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)

2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.

3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:

:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}

NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...

NOTE: You can see, the video codec is MP4V which is supported by android.

4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:

mVideoView = (VideoView) findViewById(R.id.surface_view);

mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));

5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...

Question: Anybody know how to reduce buffering time and play video almost live ?

PHP case-insensitive in_array function

I wrote a simple function to check for a insensitive value in an array the code is below.

function:

function in_array_insensitive($needle, $haystack) {
   $needle = strtolower($needle);
   foreach($haystack as $k => $v) {
      $haystack[$k] = strtolower($v);
   }
   return in_array($needle, $haystack);
}

how to use:

$array = array('one', 'two', 'three', 'four');
var_dump(in_array_insensitive('fOUr', $array));

How to turn on/off MySQL strict mode in localhost (xampp)?

For ubuntu :

  • Once you are connected to your VPS via SSH, please try connecting to your mysql with "root"

user: mysql -u root -p

  • Enter "root" user password and you will be in the mysql environment (mysql>), then simply check what is sql_mode, with the following command:

    SHOW VARIABLES LIKE 'sql_mode';

Basically, you will see the table as your result, if the table has a value of STRICT_TRANS_TABLES, it means that this option is enabled, so you need to remove the value from this table with the following command:

set global sql_mode='';

This will set your table's value to empty and disable this setting. Like this:

 +---------------+-------+
 | Variable_name | Value |
 +---------------+-------+
 | sql_mode      |       |
 +---------------+-------+

Please make sure to perform these commands within the MySQL environment and not simply via SSH. I think this moment was missed in the article provided below and the author assumes that the reader understands it intuitively.

Git Bash doesn't see my PATH

Create a User variable named Path and add as value %Path%, from what I noticed Git Bash only sees User Variables and not System Variables. By doing the mentioned procedure you'll expose your System Variable in the User Variables.

How to disable SSL certificate checking with Spring RestTemplate?

In my case, with letsencrypt https, this was caused by using cert.pem instead of fullchain.pem as the certificate file on the requested server. See this thread for details.

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

Java unsupported major minor version 52.0

Your code was compiled with Java Version 1.8 while it is being executed with Java Version 1.7 or below.

In your case it seems that two different Java installations are used, the newer to compile and the older to execute your code.

Try recompiling your code with Java 1.7 or upgrade your Java Plugin.

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

Sort array by firstname (alphabetically) in Javascript

also for both asec and desc sort, u can use this : suppose we have a variable SortType that specify ascending sort or descending sort you want:

 users.sort(function(a,b){
            return   sortType==="asc"? a.firstName.localeCompare( b.firstName): -( a.firstName.localeCompare(  b.firstName));
        })

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Your problem is that class B is not declared as a "new-style" class. Change it like so:

class B(object):

and it will work.

super() and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that (object) on any class definition to make sure it is a new-style class.

Old-style classes (also known as "classic" classes) are always of type classobj; new-style classes are of type type. This is why you got the error message you saw:

TypeError: super() argument 1 must be type, not classobj

Try this to see for yourself:

class OldStyle:
    pass

class NewStyle(object):
    pass

print type(OldStyle)  # prints: <type 'classobj'>

print type(NewStyle) # prints <type 'type'>

Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem.

php implode (101) with quotes

you can do it this way also

<?php
$csv= '\'' . join(array('lastname', 'email', 'phone'),'\',').'\'';
echo $csv;
?>

How to get UTF-8 working in Java webapps?

In case you have specified in connection pool (mysql-ds.xml), in your Java code you can open the connection as follows:

DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection conn = DriverManager.getConnection(
    "jdbc:mysql://192.168.1.12:3308/mydb?characterEncoding=greek",
    "Myuser", "mypass");

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

Plotting dates on the x-axis with Python's matplotlib

As @KyssTao has been saying, help(dates.num2date) says that the x has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102 is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).

Use datestr2num instead (see help(dates.datestr2num)):

new_x = dates.datestr2num(date) # where date is '01/02/1991'

jQuery - Illegal invocation

In my case, I just changed

Note: This is in case of Django, so I added csrftoken. In your case, you may not need it.

Added contentType: false, processData: false

Commented out "Content-Type": "application/json"

$.ajax({
    url: location.pathname, 
    type: "POST",
    crossDomain: true,
    dataType: "json",
    headers: {
        "X-CSRFToken": csrftoken,
        "Content-Type": "application/json"
    },
    data:formData,
    success: (response, textStatus, jQxhr) => {

    },
    error: (jQxhr, textStatus, errorThrown) => {

    }
})

to

$.ajax({
    url: location.pathname, 
    type: "POST",
    crossDomain: true,
    dataType: "json",
    contentType: false,
    processData: false,
    headers: {
        "X-CSRFToken": csrftoken
        // "Content-Type": "application/json",
    },
    data:formData,
    success: (response, textStatus, jQxhr) => {

    },
    error: (jQxhr, textStatus, errorThrown) => {

    }
})

and it worked.

Erase the current printed console line

there is a simple trick you can work here but it need preparation before you print, you have to put what ever you wants to print in a variable and then print so you will know the length to remove the string.here is an example.

#include <iostream>
#include <string> //actually this thing is not nessasory in tdm-gcc

using namespace  std;

int main(){

//create string variable

string str="Starting count";

//loop for printing numbers

    for(int i =0;i<=50000;i++){

        //get previous string length and clear it from screen with backspace charactor

        cout << string(str.length(),'\b');

        //create string line

        str="Starting count " +to_string(i);

        //print the new line in same spot

        cout <<str ;
    }

}

Invoke a second script with arguments from a script

Aha. This turned out to be a simple problem of there being spaces in the path to the script.

Changing the Invoke-Expression line to:

Invoke-Expression "& `"$scriptPath`" $argumentList"

...was enough to get it to kick off. Thanks to Neolisk for your help and feedback!

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.