Programs & Examples On #Hidden files

A file that is normally not visible for the user, unless the user requires to show the hidden files. It is still accessible by name and path as any other file.

Handling back button in Android Navigation Component

you can provide your custom back navigation by using OnBackPressedDispatcher

class MyFragment : Fragment() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // This callback will only be called when MyFragment is at least Started.
    val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
        // Handle the back button event
// and if you want to need navigate up
//NavHostFragment.findNavController(this).navigateUp()
    }

    // The callback can be enabled or disabled here or in the lambda
}
}

More explanations in android official guide: https://developer.android.com/guide/navigation/navigation-custom-back

ImportError: No module named tensorflow

For Anaconda3, simply install in Anaconda Navigator: enter image description here

equivalent of rm and mv in windows .cmd

move and del ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move command. And the same thing applies with del.

The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.

mv and rm are in the CoreUtils package and they work wonderfully!

Collision resolution in Java HashMap

Your case is not talking about collision resolution, it is simply replacement of older value with a new value for the same key because Java's HashMap can't contain duplicates (i.e., multiple values) for the same key.

In your example, the value 17 will be simply replaced with 20 for the same key 10 inside the HashMap.

If you are trying to put a different/new value for the same key, it is not the concept of collision resolution, rather it is simply replacing the old value with a new value for the same key. It is how HashMap has been designed and you can have a look at the below API (emphasis is mine) taken from here.

public V put(K key, V value)

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.


On the other hand, collision resolution techniques comes into play only when multiple keys end up with the same hashcode (i.e., they fall in the same bucket location) where an entry is already stored. HashMap handles the collision resolution by using the concept of chaining i.e., it stores the values in a linked list (or a balanced tree since Java8, depends on the number of entries).

How to avoid Sql Query Timeout

This is happen because another instance of sql server is running. So you need to kill first then you can able to login to SQL Server.

For that go to Task Manager and Kill or End Task the SQL Server service then go to Services.msc and start the SQL Server service.

HTTP Error 404.3-Not Found in IIS 7.5

You should install IIS sub components from

Control Panel -> Programs and Features -> Turn Windows features on or off

Internet Information Services has subsection World Wide Web Services / Application Development Features

There you must check ASP.NET (.NET Extensibility, ISAPI Extensions, ISAPI Filters will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.

Run from cmd:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.

Also, look at this answer.

Mongoose limit/offset and count query

db.collection_name.aggregate([
    { '$match'    : { } },
    { '$sort'     : { '_id' : -1 } },
    { '$facet'    : {
        metadata: [ { $count: "total" } ],
        data: [ { $skip: 1 }, { $limit: 10 },{ '$project' : {"_id":0} } ] // add projection here wish you re-shape the docs
    } }
] )

Instead of using two queries to find the total count and skip the matched record.
$facet is the best and optimized way.

  1. Match the record
  2. Find total_count
  3. skip the record
  4. And also can reshape data according to our needs in the query.

Why does make think the target is up to date?

Maybe you have a file/directory named test in the directory. If this directory exists, and has no dependencies that are more recent, then this target is not rebuild.

To force rebuild on these kind of not-file-related targets, you should make them phony as follows:

.PHONY: all test clean

Note that you can declare all of your phony targets there.

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request.

How to verify Facebook access token?

The officially supported method for this is:

GET graph.facebook.com/debug_token?
     input_token={token-to-inspect}
     &access_token={app-token-or-admin-token}

See the check token docs for more information.

An example response is:

{
    "data": {
        "app_id": 138483919580948, 
        "application": "Social Cafe", 
        "expires_at": 1352419328, 
        "is_valid": true, 
        "issued_at": 1347235328, 
        "metadata": {
            "sso": "iphone-safari"
        }, 
        "scopes": [
            "email", 
            "publish_actions"
        ], 
        "user_id": 1207059
    }
}

SQL - How do I get only the numbers after the decimal?

The usual hack (which varies a bit in syntax) is

x - floor(x)

That's the fractional part. To make into an integer, scale it.

(x - floor(x)) * 1000

How to diff one file to an arbitrary version in Git?

If neither commit is your HEAD then bash's brace expansion proves really useful, especially if your filenames are long, the example above:

git diff master~20:pom.xml master:pom.xml

Would become

git diff {master~20,master}:pom.xml

More on Brace expansion with bash.

Variables within app.config/web.config

A slightly more complicated, but far more flexible, alternative is to create a class that represents a configuration section. In your app.config / web.config file, you can have this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <!-- This section must be the first section within the <configuration> node -->
    <configSections>
        <section name="DirectoryInfo" type="MyProjectNamespace.DirectoryInfoConfigSection, MyProjectAssemblyName" />
    </configSections>

    <DirectoryInfo>
        <Directory MyBaseDir="C:\MyBase" Dir1="Dir1" Dir2="Dir2" />
    </DirectoryInfo>
</configuration>

Then, in your .NET code (I'll use C# in my example), you can create two classes like this:

using System;
using System.Configuration;

namespace MyProjectNamespace {

    public class DirectoryInfoConfigSection : ConfigurationSection {

        [ConfigurationProperty("Directory")]
        public DirectoryConfigElement Directory {
            get {
                return (DirectoryConfigElement)base["Directory"];
            }
    }

    public class DirectoryConfigElement : ConfigurationElement {

        [ConfigurationProperty("MyBaseDir")]
        public String BaseDirectory {
            get {
                return (String)base["MyBaseDir"];
            }
        }

        [ConfigurationProperty("Dir1")]
        public String Directory1 {
            get {
                return (String)base["Dir1"];
            }
        }

        [ConfigurationProperty("Dir2")]
        public String Directory2 {
            get {
                return (String)base["Dir2"];
            }
        }
        // You can make custom properties to combine your directory names.
        public String Directory1Resolved {
            get {
                return System.IO.Path.Combine(BaseDirectory, Directory1);
            }
        }
    }
}

Finally, in your program code, you can access your app.config variables, using your new classes, in this manner:

DirectoryInfoConfigSection config =
  (DirectoryInfoConfigSection)ConfigurationManager.GetSection("DirectoryInfo");
String dir1Path = config.Directory.Directory1Resolved;  // This value will equal "C:\MyBase\Dir1"

Firefox 'Cross-Origin Request Blocked' despite headers

Just add

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

to the .htaccess file in the root of the website you are trying to connect with.

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">
</td>

Method to get all files within folder and subfolders that will return a list

You can use Directory.GetFiles to replace your method.

 Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories)

How do I set vertical space between list items?

Old question but I think it lacked an answer. I would use an adjacent siblings selector. This way we only write "one" line of CSS and take into consideration the space at the end or beginning, which most of the answers lacks.

li + li {
  margin-top: 10px;
}

How do I remove objects from a JavaScript associative array?

If, for whatever reason, the delete key is not working (like it wasn't working for me), you can splice it out and then filter the undefined values:

// To cut out one element via arr.splice(indexToRemove, numberToRemove);
array.splice(key, 1)
array.filter(function(n){return n});

Don’t try and chain them since splice returns removed elements;

What's the difference between abstraction and encapsulation?

Abstraction: In case of an hardware abstraction layer, you have simple interfaces to trigger the hardware (e.g. turn enginge left/right) without knowing the hardware details behind. So hiding the complexity of the system. It's a simplified view of the real world.

Encapsulation: Hiding of object internals. The object is an abstraction of the real world. But the details of this object (like data structures...) can be hidden via encapsulation.

Python: find position of element in array

Have you thought about using Python list's .index(value) method? It return the index in the list of where the first instance of the value passed in is found.

Git keeps asking me for my ssh key passphrase

Another possible solution that is not mentioned above is to check your remote with the following command:

git remote -v

If the remote does not start with git but starts with https you might want to change it to git by following the example below.

git remote -v // origin is https://github.com/user/myrepo.git
git remote set-url origin [email protected]:user/myrepo.git
git remote -v // check if remote is changed

How to load a model from an HDF5 file in Keras?

See the following sample code on how to Build a basic Keras Neural Net Model, save Model (JSON) & Weights (HDF5) and load them:

# create model
model = Sequential()
model.add(Dense(X.shape[1], input_dim=X.shape[1], activation='relu')) #Input Layer
model.add(Dense(X.shape[1], activation='relu')) #Hidden Layer
model.add(Dense(output_dim, activation='softmax')) #Output Layer

# Compile & Fit model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X,Y,nb_epoch=5,batch_size=100,verbose=1)    

# serialize model to JSON
model_json = model.to_json()
with open("Data/model.json", "w") as json_file:
    json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))

# serialize weights to HDF5
model.save_weights("Data/model.h5")
print("Saved model to disk")

# load json and create model
json_file = open('Data/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("Data/model.h5")
print("Loaded model from disk")

# evaluate loaded model on test data 
# Define X_test & Y_test data first
loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
score = loaded_model.evaluate(X_test, Y_test, verbose=0)
print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

Git merge error "commit is not possible because you have unmerged files"

You need to do two things. First add the changes with

git add .
git stash  

git checkout <some branch>

It should solve your issue as it solved to me.

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

I had a similar issue. the error comes up when the i switched the fb user from setting. Facebook authorization fails on iOS6 when switching FB account on device This solved my problem

How to start an Android application from the command line?

You can use:

adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1

This will start the LAUNCHER Activity of the application using monkeyrunner test tool.

OperationalError, no such column. Django

I had this problem recently, even though on a different tutorial. I had the django version 2.2.3 so I thought I should not have this kind of issue. In my case, once I add a new field to a model and try to access it in admin, it would say no such column. I learnt the 'right' way after three days of searching for solution with nothing working. First, if you are making a change to a model, you should make sure that the server is not running. This is what caused my own problem. And this is not easy to rectify. I had to rename the field (while server was not running) and re-apply migrations. Second, I found that python manage.py makemigrations <app_name> captured the change as opposed to just python manage.py makemigrations. I don't know why. You could also follow that up with python manage.py migrate <app_name>. I'm glad I found this out by myself.

remove inner shadow of text input

border-style:solid; will override the inset style. Which is what you asked.

border:none will remove the border all together.

border-width:1px will set it up to be kind of like before the background change.

border:1px solid #cccccc is more specific and applies all three, width, style and color.

Example: https://jsbin.com/quleh/2/edit?html,output

How to run bootRun with spring profile via gradle task

For anyone looking how to do this in Kotlin DSL, here's a working example for build.gradle.kts:

tasks.register("bootRunDev") {
    group = "application"
    description = "Runs this project as a Spring Boot application with the dev profile"
    doFirst {
        tasks.bootRun.configure {
            systemProperty("spring.profiles.active", "dev")
        }
    }
    finalizedBy("bootRun")
}

What is the maximum number of edges in a directed graph with n nodes?

If the graph is not a multi graph then it is clearly n * (n - 1), as each node can at most have edges to every other node. If this is a multigraph, then there is no max limit.

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

You could also use =COUNTA(A1:A200) which requires no conditions.

From Google Support:

COUNTA counts all values in a dataset, including those which appear more than once and text values (including zero-length strings and whitespace). To count unique values, use COUNTUNIQUE.

Import numpy on pycharm

In general, the cause of the problem could be the following:

You started a new project with the new virtual environment. So probably you install numpy from the terminal, but it is not in your venv. So

  • either install it from PyCahrm Interface: Settings -> Project Interpreter -> Add the package

  • or activate your venv and -> pip install numPy

How do write IF ELSE statement in a MySQL query

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

Python loop that also accesses previous and next values

I think this works and not complicated

array= [1,5,6,6,3,2]
for i in range(0,len(array)):
    Current = array[i]
    Next = array[i+1]
    Prev = array[i-1]

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

Android disable screen timeout while app is running

procedure SetSleep(aEnable:Boolean);
var
    vFlags: integer;
begin
    vFlags := TJWindowManager_LayoutParams.JavaClass.FLAG_TURN_SCREEN_ON or
        TJWindowManager_LayoutParams.JavaClass.FLAG_DISMISS_KEYGUARD or
        TJWindowManager_LayoutParams.JavaClass.FLAG_SHOW_WHEN_LOCKED or
        TJWindowManager_LayoutParams.JavaClass.FLAG_KEEP_SCREEN_ON;

    if aEnable then
    begin
      CallInUIThread (   // uses FMX.Helpers.Android
      procedure
      begin
        TAndroidHelper.Activity.getWindow.setFlags (vFlags, vFlags);
      end );
    end
    else
      CallInUIThread (
      procedure
      begin
        TAndroidHelper.Activity.getWindow.clearFlags (vFlags);
      end );
end;

How to export html table to excel or pdf in php

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel"> 

exporttable.php

<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

How to add 20 minutes to a current date?

Use .getMinutes() to get the current minutes, then add 20 and use .setMinutes() to update the date object.

var twentyMinutesLater = new Date();
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20);

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

How to remove duplicates from Python list and keep order?

If your input is already sorted, then there may be a simpler way to do it:

from operator import itemgetter
from itertools import groupby
unique_list = list(map(itemgetter(0), groupby(yourList)))

Detect changed input text box

In my case, I had a textbox that was attached to a datepicker. The only solution that worked for me was to handle it inside the onSelect event of the datepicker.

<input type="text"  id="bookdate">

$("#bookdate").datepicker({            
     onSelect: function (selected) {
         //handle change event here
     }
});

How to access site running apache server over lan without internet connection

  1. Open the "internet protocol properties" section on computer_2.
  2. Enter the ip address (192.168.1.2) of computer_1 in "Preferred DNS server" text box and click ok and close the dialog box.

Now try to open the website again on computer_2.

File Upload using AngularJS

Easy with a directive

Html:

<input type="file" file-upload multiple/>

JS:

app.directive('fileUpload', function () {
return {
    scope: true,        //create a new scope
    link: function (scope, el, attrs) {
        el.bind('change', function (event) {
            var files = event.target.files;
            //iterate files since 'multiple' may be specified on the element
            for (var i = 0;i<files.length;i++) {
                //emit event upward
                scope.$emit("fileSelected", { file: files[i] });
            }                                       
        });
    }
};

In the directive we ensure a new scope is created and then listen for changes made to the file input element. When changes are detected with emit an event to all ancestor scopes (upward) with the file object as a parameter.

In your controller:

$scope.files = [];

//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
    $scope.$apply(function () {            
        //add the file object to the scope's files collection
        $scope.files.push(args.file);
    });
});

Then in your ajax call:

data: { model: $scope.model, files: $scope.files }

http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/

Clear listview content?

You need to call both clear() from ArrayAdapter and notifyDataSetChanged() both.

Below is link click

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

Vertically center text in a 100% height div?

Try this one http://jsfiddle.net/Husamuddin/ByNa3/ it works fine with me,
css

.table {
    width:100%;
    height:100%;
    position:absolute;
    display:table;
}
.cell {
    display:table-cell;
    vertical-align:middle;
    width:100%;
    height:100%:
}

and the html

<div class="table">
    <div class="cell">Hello, I'm in the middle</div>
</div>

jQuery $("#radioButton").change(...) not firing during de-selection

Let's say those radio buttons are inside a div that has the id radioButtons and that the radio buttons have the same name (for example commonName) then:

$('#radioButtons').on('change', 'input[name=commonName]:radio', function (e) {
    console.log('You have changed the selected radio button!');
});

Convert negative data into positive data in SQL Server

UPDATE mytbl
SET a = ABS(a)
where a < 0

Get list from pandas dataframe column or row?

If your column will only have one value something like pd.series.tolist() will produce an error. To guarantee that it will work for all cases, use the code below:

(
    df
        .filter(['column_name'])
        .values
        .reshape(1, -1)
        .ravel()
        .tolist()
)

How do I install a pip package globally instead of locally?

Why don't you try sudo with the H flag? This should do the trick.

sudo -H pip install flake8

A regular sudo pip install flake8 will try to use your own home directory. The -H instructs it to use the system's home directory. More info at https://stackoverflow.com/a/43623102/

changing the language of error message in required field in html5 contact form

HTML:

<form id="myform">
    <input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);"  type="email" required="required" />
    <input type="submit" />
</form>

JAVASCRIPT :

function InvalidMsg(textbox) {
    if (textbox.value == '') {
        textbox.setCustomValidity('Lütfen isaretli yerleri doldurunuz');
    }
    else if (textbox.validity.typeMismatch){{
        textbox.setCustomValidity('please enter a valid email address');
    }
    else {
       textbox.setCustomValidity('');
    }
    return true;
}

Demo :

http://jsfiddle.net/patelriki13/Sqq8e/4

How to display hexadecimal numbers in C?

i use it like this:

printf("my number is 0x%02X\n",number);
// output: my number is 0x4A

Just change number "2" to any number of chars You want to print ;)

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

LINQ: Distinct values

Just use the Distinct() with your own comparer.

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

String representation of an Enum

Unfortunately reflection to get attributes on enums is quite slow:

See this question: Anyone know a quick way to get to custom attributes on an enum value?

The .ToString() is quite slow on enums too.

You can write extension methods for enums though:

public static string GetName( this MyEnum input ) {
    switch ( input ) {
        case MyEnum.WINDOWSAUTHENTICATION:
            return "Windows";
        //and so on
    }
}

This isn't great, but will be quick and not require the reflection for attributes or field name.


C#6 Update

If you can use C#6 then the new nameof operator works for enums, so nameof(MyEnum.WINDOWSAUTHENTICATION) will be converted to "WINDOWSAUTHENTICATION" at compile time, making it the quickest way to get enum names.

Note that this will convert the explicit enum to an inlined constant, so it doesn't work for enums that you have in a variable. So:

nameof(AuthenticationMethod.FORMS) == "FORMS"

But...

var myMethod = AuthenticationMethod.FORMS;
nameof(myMethod) == "myMethod"

Convert UTF-8 encoded NSData to NSString

You could call this method

+(id)stringWithUTF8String:(const char *)bytes.

How to check for a valid URL in Java?

My favorite approach, without external libraries:

try {
    URI uri = new URI(name);

    // perform checks for scheme, authority, host, etc., based on your requirements

    if ("mailto".equals(uri.getScheme()) {/*Code*/}
    if (uri.getHost() == null) {/*Code*/}

} catch (URISyntaxException e) {
}

Using Python's list index() method on a list of tuples or objects?

How about this?

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [x for x, y in enumerate(tuple_list) if y[1] == 7]
[1]
>>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']
[2]

As pointed out in the comments, this would get all matches. To just get the first one, you can do:

>>> [y[0] for y in tuple_list].index('kumquat')
2

There is a good discussion in the comments as to the speed difference between all the solutions posted. I may be a little biased but I would personally stick to a one-liner as the speed we're talking about is pretty insignificant versus creating functions and importing modules for this problem, but if you are planning on doing this to a very large amount of elements you might want to look at the other answers provided, as they are faster than what I provided.

Session state can only be used when enableSessionState is set to true either in a configuration

Did you enable the session state in the section as well?

 <system.web>
      <pages enableSessionState="true" /> 
 </system.web>

Or did you add this to the page?

 <%@Page enableSessionState="true"> 

And did you verify that the ASP.NET Session State Manager Service service is running? In your screenshot it isn't. It's set to start-up mode Manual which requires you to start it every time you want to make use of it. To start it, highlight the service and click the green play button on the toolbar. To start it automatically, edit the properties and adjust the Start-up type.

Or set the SessionState's mode property to InProc, so that the state service is not required.

 <system.web>
      <sessionState mode="InProc" />
 </system.web>

Check MSDN for all the options available to you with regards to storing data in the ASP.NET session state.


Note: It's better to have your Controller fetch the value from the session and have it add the value to the Model for your page/control (or to the ViewBag), that way the View doesn't depend on the HttpSession and you can choose a different source for this item later with minimal code changes. Or even better, not use the session state at all. It can kill you performance when you're using a lot of async javascript calls.

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys.

Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}

Example

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="angular.js"></script>

</head>
<body>
    <div ng-app="myApp" ng-controller="personController">
        <table>
            <tr> <th>First Name</th> <th>Last Name</th> </tr>
            <tr ng-repeat="person in people track by $index">
                <td>{{person.firstName}}</td>
                <td>{{person.lastName}}</td>
                <td><input type="button" value="Select" ng-click="showDetails($index)" /></td>
            </tr>

        </table> <hr />
        <table>
            <tr ng-repeat="person1 in items track by $index">
                <td>{{person1.firstName}}</td>
                <td>{{person1.lastName}}</td>
            </tr>
        </table>
        <span>   {{sayHello()}}</span>
    </div>
    <script> var myApp = angular.module("myApp", []);
        myApp.controller("personController", ['$scope', function ($scope)
        { 
            $scope.people = [{ firstName: "F1", lastName: "L1" },
                { firstName: "F2", lastName: "L2" }, 
                { firstName: "F3", lastName: "L3" }, 
                { firstName: "F4", lastName: "L4" }, 
                { firstName: "F5", lastName: "L5" }]
            $scope.items = [];
            $scope.selectedPerson = $scope.people[0];
            $scope.showDetails = function (ind) 
            { 
                $scope.selectedPerson = $scope.people[ind];
                $scope.items.push($scope.selectedPerson);
            }
            $scope.sayHello = function ()
            {
                return $scope.items.firstName;
            }
        }]) </script>
</body>
</html>

Copy files to network computers on windows command line

Below command will work in command prompt:

copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y

To Copy all files:

copy c:\folder\*.* \\dest-machine\destfolder /Z /Y

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

Create an S3 client object with your credentials

AWS_S3_CREDS = {
    "aws_access_key_id":"your access key", # os.getenv("AWS_ACCESS_KEY")
    "aws_secret_access_key":"your aws secret key" # os.getenv("AWS_SECRET_KEY")
}
s3_client = boto3.client('s3',**AWS_S3_CREDS)

It is always good to get credentials from os environment

To set Environment variables run the following commands in terminal

if linux or mac

$ export AWS_ACCESS_KEY="aws_access_key"
$ export AWS_SECRET_KEY="aws_secret_key"

if windows

c:System\> set AWS_ACCESS_KEY="aws_access_key"
c:System\> set AWS_SECRET_KEY="aws_secret_key"

How do I run a batch file from my Java Application?

The following is working fine:

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);

Getting key with maximum value in dictionary?

A heap queue is a generalised solution which allows you to extract the top n keys ordered by value:

from heapq import nlargest

stats = {'a':1000, 'b':3000, 'c': 100}

res1 = nlargest(1, stats, key=stats.__getitem__)  # ['b']
res2 = nlargest(2, stats, key=stats.__getitem__)  # ['b', 'a']

res1_val = next(iter(res1))                       # 'b'

Note dict.__getitem__ is the method called by the syntactic sugar dict[]. As opposed to dict.get, it will return KeyError if a key is not found, which here cannot occur.

The differences between initialize, define, declare a variable

Declaration

Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":

void xyz();

or declare an incomplete type:

class klass;
struct ztruct;

and last but not least, to declare an object:

int x;

It is described, in the C++ standard, at §3.1/1 as:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

Definition

A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

Specifically the C++ standard defines it, at §3.1/1, as:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

Initialization

Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T, it's often in the form:

T x = i;

but in C++ it can be:

T x(i);

or even:

T x {i};

with C++11.

Conclusion

So does it mean definition equals declaration plus initialization?

It depends. On what you are talking about. If you are talking about an object, for example:

int x;

This is a definition without initialization. The following, instead, is a definition with initialization:

int x = 0;

In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.

So, the answer is no: definition does not automatically mean declaration plus initialization.

Fitting polynomial model to data in R

Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:

x <- 1:10
y <- x + c(-0.5,0.5)

plot(x,y, xlim=c(0,11), ylim=c(-1,12))

fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )

fit7 <- lm( y ~ x + cos(x*pi) )

xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')

Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).

How do I get a file extension in PHP?

Although the "best way" is debatable, I believe this is the best way for a few reasons:

function getExt($path)
{
    $basename = basename($path);
    return substr($basename, strlen(explode('.', $basename)[0]) + 1);
}
  1. It works with multiple parts to an extension, eg tar.gz
  2. Short and efficient code
  3. It works with both a filename and a complete path

jquery to change style attribute of a div class

In order to change the attribute of the class conditionally,

var css_val = $(".handle").css('left');
if(css_val == '336px')
{
  $(".handle").css('left','300px');
}

If id is given as following,

<a id="handle" class="handle" href="#" style="left: 336px;"></a>

Here is an alternative solution:

var css_val = $("#handle").css('left');
if(css_val == '336px')
{
  $("#handle").css('left','300px');
}

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

symfony 2 twig limit the length of the text and put three dots

Use the truncate filter to cut off a string after limit is reached

{{ "Hello World!"|truncate(5) }} // default separator is ...

Hello...

You can also tell truncate to preserve whole words by setting the second parameter to true. If the last Word is on the the separator, truncate will print out the whole Word.

 {{ "Hello World!"|truncate(7, true) }} // preserve words

Here Hello World!

If you want to change the separator, just set the third parameter to your desired separator.

{{ "Hello World!"|truncate(7, false, "??") }} 

Hello W??

Reversing a string in C

Just a rearrangement, and safety check. I also removed your non-used return type. I think this is a safe and clean as it gets:

#include <stdio.h>
#include <string.h>

void reverse_string(char *str)
{
    /* skip null */
    if (str == 0)
    {
        return;
    }

    /* skip empty string */
    if (*str == 0)
    {
        return;
    }

    /* get range */
    char *start = str;
    char *end = start + strlen(str) - 1; /* -1 for \0 */
    char temp;

    /* reverse */
    while (end > start)
    {
        /* swap */
        temp = *start;
        *start = *end;
        *end = temp;

        /* move */
        ++start;
        --end;
    }
}


int main(void)
{
    char s1[] = "Reverse me!";
    char s2[] = "abc";
    char s3[] = "ab";
    char s4[] = "a";
    char s5[] = "";

    reverse_string(0);

    reverse_string(s1);
    reverse_string(s2);
    reverse_string(s3);
    reverse_string(s4);
    reverse_string(s5);

    printf("%s\n", s1);
    printf("%s\n", s2);
    printf("%s\n", s3);
    printf("%s\n", s4);
    printf("%s\n", s5);

    return 0;
}

Edited so that end will not point to a possibly bad memory location when strlen is 0.

Turning a Comma Separated string into individual rows

By creating this function ([DelimitedSplit]) which splits a string, you could do an OUTER APPLY to your SELECT.

CREATE FUNCTION [dbo].[DelimitedSplit]
--===== Define I/O parameters
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE!  IT WILL KILL PERFORMANCE!
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
     -- enough to cover VARCHAR(8000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a INNER JOIN E1 b ON b.N = a.N), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a INNER JOIN E2 b ON b.N = a.N), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;

TEST

CREATE TABLE #Testdata
(
    SomeID INT,
    OtherID INT,
    String VARCHAR(MAX)
)

INSERT #Testdata SELECT 1,  9, '18,20,22'
INSERT #Testdata SELECT 2,  8, '17,19'
INSERT #Testdata SELECT 3,  7, '13,19,20'
INSERT #Testdata SELECT 4,  6, ''
INSERT #Testdata SELECT 9, 11, '1,2,3,4'

SELECT
 *
FROM #Testdata
OUTER APPLY [dbo].[DelimitedSplit](String,',')

DROP TABLE #Testdata

RESULT

SomeID  OtherID String      ItemNumber  Item
1       9       18,20,22    1           18
1       9       18,20,22    2           20
1       9       18,20,22    3           22
2       8       17,19       1           17
2       8       17,19       2           19
3       7       13,19,20    1           13
3       7       13,19,20    2           19
3       7       13,19,20    3           20
4       6       1   
9       11      1,2,3,4     1           1
9       11      1,2,3,4     2           2
9       11      1,2,3,4     3           3
9       11      1,2,3,4     4           4

JQuery Ajax POST in Codeigniter

<script>
$("#editTest23").click(function () {

        var test_date = $(this).data('id');
        // alert(status_id);    

        $.ajax({
            type: "POST",
            url: base_url+"Doctor/getTestData",
            data: {
                test_data: test_date,
            },
            dataType: "text",
            success: function (data) {
                $('#prepend_here_test1').html(data);
            }
        });
        // you have missed this bracket
        return false;
    });
</script>

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

Prepend text to beginning of string

Since the question is about what is the fastest method, I thought I'd throw up add some perf metrics.

TL;DR The winner, by a wide margin, is the + operator, and please never use regex

https://jsperf.com/prepend-text-to-string/1

enter image description here

What is the difference between null and undefined in JavaScript?

I picked this from here

The undefined value is a primitive value used when a variable has not been assigned a value.

The null value is a primitive value that represents the null, empty, or non-existent reference.

When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:

var s;
WScript.Echo(s);
WScript.Echo("" + s);

You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.

You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

undefined == null
null == undefined

They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:

var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));

Running the above script will result in the following output:

undefined
object

Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).

You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.

Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.

var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);

The result of the above script is:

0.) a
1.) undefined
2.) c

You will also get undefined returned when reading a subscript or member that never existed.

The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.

How to initialize a vector with fixed length in R

The initialization method easiest to remember is

vec = vector(,10); #the same as "vec = vector(length = 10);"

The values of vec are: "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE" (logical mode) by default.

But after setting a character value, like

vec[2] = 'abc'

vec becomes: "FALSE" "abc" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"", which is of the character mode.

regex pattern to match the end of a string

Use following pattern:

/([^/]+)$

What are the date formats available in SimpleDateFormat class?

Date and time formats are well described below

SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns

There could be n Number of formats you can possibly make. ex - dd/MM/yyyy or YYYY-'W'ww-u or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.

  • G - Era designator (AD)
  • y - Year (1996; 96)
  • Y - Week Year (2009; 09)
  • M - Month in year (July; Jul; 07)
  • w - Week in year (27)
  • W - Week in month (2)
  • D - Day in year (189)
  • d - Day in month (10)
  • F - Day of week in month (2)
  • E - Day name in week (Tuesday; Tue)
  • u - Day number of week (1 = Monday, ..., 7 = Sunday)
  • a - AM/PM marker
  • H - Hour in day (0-23)
  • k - Hour in day (1-24)
  • K - Hour in am/pm (0-11)
  • h - Hour in am/pm (1-12)
  • m - Minute in hour (30)
  • s - Second in minute (55)
  • S - Millisecond (978)
  • z - General time zone (Pacific Standard Time; PST; GMT-08:00)
  • Z - RFC 822 time zone (-0800)
  • X - ISO 8601 time zone (-08; -0800; -08:00)

To parse:

2000-01-23T04:56:07.000+0000

Use: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

Business logic in MVC

Model = code for CRUD database operations.

Controller = responds to user actions, and passes the user requests for data retrieval or delete/update to the model, subject to the business rules specific to an organization. These business rules could be implemented in helper classes, or if they are not too complex, just directly in the controller actions. The controller finally asks the view to update itself so as to give feedback to the user in the form of a new display, or a message like 'updated, thanks', etc.,

View = UI that is generated based on a query on the model.

There are no hard and fast rules regarding where business rules should go. In some designs they go into model, whereas in others they are included with the controller. But I think it is better to keep them with the controller. Let the model worry only about database connectivity.

How to stop a vb script running in windows

I can think of at least 2 different ways:

  1. using Task Manager (Ctrl-Shift-Esc), select the process tab, look for a process name cscript.exe or wscript.exe and use End Process.

  2. From the command line you could use taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed)

Another way is using scripting and WMI. Here are some hints: look for the Win32_Process class and the Terminate method.

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

Trying to merge 2 dataframes but get ValueError

Additional: when you save df to .csv format, the datetime (year in this specific case) is saved as object, so you need to convert it into integer (year in this specific case) when you do the merge. That is why when you upload both df from csv files, you can do the merge easily, while above error will show up if one df is uploaded from csv files and the other is from an existing df. This is somewhat annoying, but have an easy solution if kept in mind.

Microsoft Azure: How to create sub directory in a blob container

In Azure Portal we have below option while uploading file :

enter image description here

Insert an item into sorted list in Python

This is a possible solution for you:

a = [15, 12, 10]
b = sorted(a)
print b # --> b = [10, 12, 15]
c = 13
for i in range(len(b)):
    if b[i] > c:
        break
d = b[:i] + [c] + b[i:]
print d # --> d = [10, 12, 13, 15]

Serializing a list to JSON

building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x

using Newtonsoft.Json;

static class JsonObj
{
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Poirier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
    {
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

        try
        {
            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
            {
                foreach (T data in Record)
                {
                    objectOut.Add(data);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            Console.Write(ex.Message);
        }

        return objectOut;
    }
}

call to process

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}

or this call to process

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();
        jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}

Java - Check if input is a positive integer, negative integer, natural number and so on.

You could use if(number >= 0). The fact that you use int number = input.nextInt(); makes sure that it has to be an Integer.

How do I convert a String to an InputStream in Java?

You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

What is the best way to test for an empty string with jquery-out-of-the-box?

To checks for all 'empties' like null, undefined, '', ' ', {}, [].

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

Use cases and results.

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

Tool to convert java to c# code

For your reference:

Note: I had no experience on them.

Convert list to tuple in Python

It should work fine. Don't use tuple, list or other special names as a variable name. It's probably what's causing your problem.

>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)

>>> tuple = 'whoops'   # Don't do this
>>> tuple(l)
TypeError: 'tuple' object is not callable

How to get name of calling function/method in PHP?

The simplest way is:

echo debug_backtrace()[1]['function'];

How can I convert an image into a Base64 string?

Here is code for image encoding and image decoding.

In an XML file

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="yyuyuyuuyuyuyu"
    android:id="@+id/tv5"
/>

In a Java file:

TextView textView5;
Bitmap bitmap;

textView5 = (TextView) findViewById(R.id.tv5);

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);

new AsyncTask<Void, Void, String>() {
    @Override
    protected String doInBackground(Void... voids) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] byteFormat = stream.toByteArray();

        // Get the Base64 string
        String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

        return imgString;
    }

    @Override
    protected void onPostExecute(String s) {
       textView5.setText(s);
    }
}.execute();

How to change sa password in SQL Server 2008 express?

This is what worked for me:

  • Close all Sql Server referencing apps.
  • Open Services in Control Panel.
  • Find the "SQL Server (SQLEXPRESS)" entry and select properties.
  • Stop the service (all Sql Server services).
  • Enter "-m" at the Start parameters" fields.
  • Start the service (click on Start button on General Tab).
  • Open a Command Prompt (right click, Run as administrator if needed).
  • Enter the command:

    osql -S localhost\SQLEXPRESS -E

    (or change localhost to whatever your PC is called).

  • At the prompt type the following commands:

    CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'

    go

    sp_addsrvrolemember 'my_Login_here', 'sysadmin'

    go

    quit

  • Stop the "SQL Server (SQLEXPRESS)" service.

  • Remove the "-m" from the Start parameters field (if still there).

  • Start the service.

  • In Management Studio, use the login and password you just created. This should give it admin permission.

Angular cli generate a service and include the provider in one step

Actually, it is possible to provide the service (or guard, since that also needs to be provided) when creating the service.

The command is the following...

ng g s services/backendApi --module=app.module

Edit

It is possible to provide to a feature module, as well, you must give it the path to the module you would like.

ng g s services/backendApi --module=services/services.module

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

In my case:

sudo -E add-apt-repository ppa:linuxuprising/java

sudo apt-get update

sudo apt install  oracle-java12-installer

that works fine

Xcode Project vs. Xcode Workspace - Differences

I think there are three key items you need to understand regarding project structure: Targets, projects, and workspaces. Targets specify in detail how a product/binary (i.e., an application or library) is built. They include build settings, such as compiler and linker flags, and they define which files (source code and resources) actually belong to a product. When you build/run, you always select one specific target.

It is likely that you have a few targets that share code and resources. These different targets can be slightly different versions of an app (iPad/iPhone, different brandings,…) or test cases that naturally need to access the same source files as the app. All these related targets can be grouped in a project. While the project contains the files from all its targets, each target picks its own subset of relevant files. The same goes for build settings: You can define default project-wide settings in the project, but if one of your targets needs different settings, you can always override them there:

Shared project settings that all targets inherit, unless they overwrite it

Shared project settings that all targets inherit, unless they override it

Concrete target settings: PSE iPhone overwrites the project’s Base SDK setting

Concrete target settings: PSE iPhone overrides the project’s Base SDK setting

In Xcode, you always open projects (or workspaces, but not targets), and all the targets it contains can be built/run, but there’s no way/definition of building a project, so every project needs at least one target in order to be more than just a collection of files and settings.

Select one of the project’s targets to run

Select one of the project’s targets to run

In a lot of cases, projects are all you need. If you have a dependency that you build from source, you can embed it as a subproject. Subprojects can be opened separately or within their super project.

demoLib is a subprojec

demoLib is a subproject

If you add one of the subproject’s targets to the super project’s dependencies, the subproject will be automatically built unless it has remained unchanged. The advantage here is that you can edit files from both your project and your dependencies in the same Xcode window, and when you build/run, you can select from the project’s and its subprojects’ targets:

Running targets from a subproject

If, however, your library (the subproject) is used by a variety of other projects (or their targets, to be precise), it makes sense to put it on the same hierarchy level – that’s what workspaces are for. Workspaces contain and manage projects, and all the projects it includes directly (i.e., not their subprojects) are on the same level and their targets can depend on each other (projects’ targets can depend on subprojects’ targets, but not vice versa).

Workspace structure

Workspace structure

In this example, both apps (AnotherApplication / ProjectStructureExample) can reference the demoLib project’s targets. This would also be possible by including the demoLib project in both other projects as a subproject (which is a reference only, so no duplication necessary), but if you have lots of cross-dependencies, workspaces make more sense. If you open a workspace, you can choose from all projects’ targets when building/running.

Running targets from a workspace

You can still open your project files separately, but it is likely their targets won’t build because Xcode cannot resolve the dependencies unless you open the workspace file. Workspaces give you the same benefit as subprojects: Once a dependency changes, Xcode will rebuild it to make sure it’s up-to-date (although I have had some issues with that, it doesn’t seem to work reliably).

Your questions in a nutshell:

1) Projects contain files (code/resouces), settings, and targets that build products from those files and settings. Workspaces contain projects which can reference each other.

2) Both are responsible for structuring your overall project, but on different levels.

3) I think projects are sufficient in most cases. Don’t use workspaces unless there’s a specific reason. Plus, you can always embed your project in a workspace later.

4) I think that’s what the above text is for…

There’s one remark for 3): CocoaPods, which automatically handles 3rd party libraries for you, uses workspaces. Therefore, you have to use them, too, when you use CocoaPods (which a lot of people do).

Calculate distance between 2 GPS coordinates

This is version from "Henry Vilinskiy" adapted for MySQL and Kilometers:

CREATE FUNCTION `CalculateDistanceInKm`(
  fromLatitude float,
  fromLongitude float,
  toLatitude float, 
  toLongitude float
) RETURNS float
BEGIN
  declare distance float;

  select 
    6367 * ACOS(
            round(
              COS(RADIANS(90-fromLatitude)) *
                COS(RADIANS(90-toLatitude)) +
                SIN(RADIANS(90-fromLatitude)) *
                SIN(RADIANS(90-toLatitude)) *
                COS(RADIANS(fromLongitude-toLongitude))
              ,15)
            )
    into distance;

  return  round(distance,3);
END;

How to add the JDBC mysql driver to an Eclipse project?

  1. copy mysql-connector-java-5.1.24-bin.jar

  2. Paste it into \Apache Software Foundation\Tomcat 6.0\lib\<--here-->

  3. Restart Your Server from Eclipes.

  4. Done

How to concatenate characters in java?

You need a String object of some description to hold your array of concatenated chars, since the char type will hold only a single character. e.g.,

StringBuilder sb = new StringBuilder('a').append('b').append('c');
System.out.println(sb.toString);

NumPy first and last element from array

This does it. Note that with an odd number of elements the one in the middle won't be included.

test = [1, 23, 4, 6, 7, 8, 5]    
for i in range(len(test)/2):
    print (test[i], test[-1-i])

Output:

(1, 5)
(23, 8)
(4, 7)

Resizing an Image without losing any quality

Are you resizing larger, or smaller? By a small % or by a larger factor like 2x, 3x? What do you mean by quality for your application? And what type of images - photographs, hard-edged line drawings, or what? Writing your own low-level pixel grinding code or trying to do it as much as possible with existing libraries (.net or whatever)?

There is a large body of knowledge on this topic. The key concept is interpolation.

Browsing recommendations:
* http://www.all-in-one.ee/~dersch/interpolator/interpolator.html
* http://www.cambridgeincolour.com/tutorials/image-interpolation.htm
* for C#: https://secure.codeproject.com/KB/GDI-plus/imageprocessing4.aspx?display=PrintAll&fid=3657&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26&select=629945 * this is java-specific but might be educational - http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

.NET - Get protocol, host, and port

Even shorter way, may require newer ASP.Net:

string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)

The UriComponents enum lets you specify which component(s) of the URI you want to include.

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

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

Exceptions are related to Design by Contract.

The interface of an objects is actually a contract between two objects, the caller must meet the contract or else the receiver may just fail with an exception. There are two possible contracts

1) all input the method is valid, in which case you must return null when the object is not found.

2) only some input is valid, ie that which results in a found object. In which case you MUST offer a second method that allows the caller to determine if its input will be correct. For example

is_present(key)
find(key) throws Exception

IF and ONLY IF you provide both methods of the 2nd contract, you are allowed to throw an exception is nothing is found!

How to fix java.net.SocketException: Broken pipe?

The issue could be that your deployed files are not updated with the correct RMI methods. Check to see that your RMI interface has updated parameters, or updated data structures that your client does not have. Or that your RMI client has no parameters that differ from what your server version has.

This is just an educated guess. After re-deploying my server application's class files and re-testing, the problem of "Broken pipe" went away.

How to zip a file using cmd line?

tar.exe -acf out.zip in.txt

out.zip is an output folder or filename and in.txt is an input folder or filename. To use this command you should be in the file existing folder.

'ssh-keygen' is not recognized as an internal or external command

If you have installed Git, and is installed at C:\Program Files, follow as below

  1. Go to "C:\Program Files\Git"
  2. Run git-bash.exe, this opens a new window
  3. In the new bash window, run "ssh-keygen -t rsa -C""
  4. It prompts for file in which to save key, dont input any value - just press enter
  5. Same for passphrase (twice), just press enter
  6. id_rsa and id_rsa.pub will be generated in your home folder under .ssh

How to print the value of a Tensor object in TensorFlow?

Enable the eager execution which is introduced in tensorflow after version 1.10. It's very easy to use.

# Initialize session
import tensorflow as tf
tf.enable_eager_execution()


# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

print(a)

Encrypt & Decrypt using PyCrypto AES 256

It's little late but i think this will be very helpful. No one mention about use scheme like PKCS#7 padding. You can use it instead the previous functions to pad(when do encryption) and unpad(when do decryption).i will provide the full Source Code below.

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
import pkcs7
class Encryption:

    def __init__(self):
        pass

    def Encrypt(self, PlainText, SecurePassword):
        pw_encode = SecurePassword.encode('utf-8')
        text_encode = PlainText.encode('utf-8')

        key = hashlib.sha256(pw_encode).digest()
        iv = Random.new().read(AES.block_size)

        cipher = AES.new(key, AES.MODE_CBC, iv)
        pad_text = pkcs7.encode(text_encode)
        msg = iv + cipher.encrypt(pad_text)

        EncodeMsg = base64.b64encode(msg)
        return EncodeMsg

    def Decrypt(self, Encrypted, SecurePassword):
        decodbase64 = base64.b64decode(Encrypted.decode("utf-8"))
        pw_encode = SecurePassword.decode('utf-8')

        iv = decodbase64[:AES.block_size]
        key = hashlib.sha256(pw_encode).digest()

        cipher = AES.new(key, AES.MODE_CBC, iv)
        msg = cipher.decrypt(decodbase64[AES.block_size:])
        pad_text = pkcs7.decode(msg)

        decryptedString = pad_text.decode('utf-8')
        return decryptedString

import StringIO
import binascii


def decode(text, k=16):
    nl = len(text)
    val = int(binascii.hexlify(text[-1]), 16)
    if val > k:
        raise ValueError('Input is not padded or padding is corrupt')

    l = nl - val
    return text[:l]


def encode(text, k=16):
    l = len(text)
    output = StringIO.StringIO()
    val = k - (l % k)
    for _ in xrange(val):
        output.write('%02x' % val)
    return text + binascii.unhexlify(output.getvalue())

Can I set background image and opacity in the same property?

Solution with 1 div and NO transparent image:

You can use the multibackground CSS3 feature and put two backgrounds: one with the image, another with a transparent panel over it (cause I think there's no way to set directly the opacity of the background image):

background: -moz-linear-gradient(top, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.7) 100%), url(bg.png) repeat 0 0, url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -moz-linear-gradient(top, rgba(255,255,255,0.7) 0%, rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0.7)), color-stop(100%,rgba(255,255,255,0.7))), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -webkit-linear-gradient(top, rgba(255,255,255,0.7) 0%,rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -o-linear-gradient(top, rgba(255,255,255,0.7) 0%,rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -ms-linear-gradient(top, rgba(255,255,255,0.7) 0%,rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: linear-gradient(to bottom, rgba(255,255,255,0.7) 0%,rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

You can't use rgba(255,255,255,0.5) because alone it is only accepted on the back, so you I've used generated gradients for each browser for this example (that's why it is so long). But the concept is the following:

background: tranparentColor, url("myImage"); 

http://jsfiddle.net/pBVsD/1/

Java 8, Streams to find the duplicate elements

You need a set (allItems below) to hold the entire array contents, but this is O(n):

Integer[] numbers = new Integer[] { 1, 2, 1, 3, 4, 4 };
Set<Integer> allItems = new HashSet<>();
Set<Integer> duplicates = Arrays.stream(numbers)
        .filter(n -> !allItems.add(n)) //Set.add() returns false if the item was already in the set.
        .collect(Collectors.toSet());
System.out.println(duplicates); // [1, 4]

PHP function ssh2_connect is not working

You need to install ssh2 lib

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart

that should be enough to get you on the road

Get the previous month's first and last day dates in c#

This is a take on Mike W's answer:

internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
    DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
    DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
    if (returnLastDayOfMonth) return lastDayOfLastMonth;
    return firstDayOfThisMonth.AddMonths(-1);
}

You can call it like so:

dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);

x86 Assembly on a Mac

After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with.

You'll also want to take a look at the Compiler & Debugging Guides, because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to.

Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next.

Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations.

Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days.

HTTP Content-Type Header and JSON

Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html' apparently extensions can and will use the response header to alter the content prior to further processing by the browser. Changing the content-type fixed the issue.

SimpleDateFormat parse loses timezone

tl;dr

what is the way to retrieve a Date object so that its always in GMT?

Instant.now() 

Details

You are using troublesome confusing old date-time classes that are now supplanted by the java.time classes.

Instant = UTC

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ; // Current moment in UTC.

ISO 8601

To exchange this data as text, use the standard ISO 8601 formats exclusively. These formats are sensibly designed to be unambiguous, easy to process by machine, and easy to read across many cultures by people.

The java.time classes use the standard formats by default when parsing and generating strings.

String output = instant.toString() ;  

2017-01-23T12:34:56.123456789Z

Time zone

If you want to see that same moment as presented in the wall-clock time of a particular region, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Asia/Singapore" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same simultaneous moment, same point on the timeline.

See this code live at IdeOne.com.

Notice the eight hour difference, as the time zone of Asia/Singapore currently has an offset-from-UTC of +08:00. Same moment, different wall-clock time.

instant.toString(): 2017-01-23T12:34:56.123456789Z

zdt.toString(): 2017-01-23T20:34:56.123456789+08:00[Asia/Singapore]

Convert

Avoid the legacy java.util.Date class. But if you must, you can convert. Look to new methods added to the old classes.

java.util.Date date = Date.from( instant ) ;

…going the other way…

Instant instant = myJavaUtilDate.toInstant() ;

Date-only

For date-only, use LocalDate.

LocalDate ld = zdt.toLocalDate() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Display unescaped HTML in Vue.js

You can use the directive v-html to show it. like this:

<td v-html="desc"></td>

Invalid shorthand property initializer

In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas "," after each property. but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

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

Look at

For Each c as DataColumn in dt.Columns
  '... = c.ColumnName
Next

or:

dt.GetDataTableSchema(...)

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

Replacing some characters in a string with another character

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

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

I would like to mention some of the possible ways here together with a pure javascript trick which works across all browsers:

// with jQuery 
$(document).ready(function(){ /* ... */ });

// shorter jQuery version 
$(function(){ /* ... */ });

// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){ 
    // your code goes here
}, false);

// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
    alert('DOM Ready!');
});

The trick here, as explained by the original author, is that we are checking the document.readyState property. If it contains the string in (as in uninitialized and loading, the first two DOM ready states out of 5) we set a timeout and check again. Otherwise, we execute the passed function.

And here's the jsFiddle for the trick which works across all browsers.

Thanks to Tutorialzine for including this in their book.

OR operator in switch-case?

dude do like this

    case R.id.someValue :
    case R.id.someOtherValue :
       //do stuff

This is same as using OR operator between two values Because of this case operator isn't there in switch case

Sequelize OR condition object

For Sequelize 4

Query

SELECT * FROM Student WHERE LastName='Doe' 
AND (FirstName = "John" or FirstName = "Jane") AND Age BETWEEN 18 AND 24 

Syntax with Operators

const Op = require('Sequelize').Op;

var r = await to (Student.findAll(
{
  where: {
    LastName: "Doe",
    FirstName: {
      [Op.or]: ["John", "Jane"]
    },
    Age: {
      // [Op.gt]: 18
      [Op.between]: [18, 24]
    }
  }
}
));

Notes

  • For better security Sequelize recommends dropping alias operators $ (e.g $and, $or ...)
  • Unless you have {freezeTableName: true} set in the table model then Sequelize will query against the plural form of its name ( Student -> Students )

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

Change image in HTML page every few seconds

You can load the images at the beginning and change the css attributes to show every image.

var images = array();
for( url in your_urls_array ){
   var img = document.createElement( "img" );
   //here the image attributes ( width, height, position, etc )
   images.push( img );
}

function player( position )
{
  images[position-1].style.display = "none" //be careful working with the first position
  images[position].style.display = "block";
  //reset position if needed
  timer = setTimeOut( "player( position )", time );
}

How to draw interactive Polyline on route google maps v2 android

Instead of creating too many short Polylines just create one like here:

PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
    LatLng point = list.get(z);
    options.add(point);
}
line = myMap.addPolyline(options);

I'm also not sure you should use geodesic when your points are so close to each other.

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

I present to you my ConcatenateRange VBA function (thanks Jean for the naming advice!) . It will take a range of cells (any dimension, any direction, etc.) and merge them together into a single string. As an optional third parameter, you can add a seperator (like a space, or commas sererated).

In this case, you'd write this to use it:

=ConcatenateRange(A1:A4)

Function ConcatenateRange(ByVal cell_range As range, _
                    Optional ByVal separator As String) As String

Dim newString As String
Dim cell As Variant

For Each cell in cell_range
    If Len(cell) <> 0 Then
        newString = newString & (separator & cell)
    End if
Next

If Len(newString) <> 0 Then
    newString = Right$(newString, (Len(newString) - Len(separator)))
End If

ConcatenateRange = newString

End Function

Saving timestamp in mysql table using php

Hey there, use the FROM_UNIXTIME() function for this.

Like this:

INSERT INTO table_name
(id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES
(1,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1'), 
(2,5,9,'2',FROM_UNIXTIME(1299762201428),5,10,20,'1')

Detect & Record Audio in Python

You might want to look at csounds, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.

Matplotlib scatter plot with different text at each data point

This might be useful when you need individually annotate in different time (I mean, not in a single for loop)

ax = plt.gca()
ax.annotate('your_lable', (x,y)) 

where x and y are the your target coordinate and type is float/int.

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

Component based game engine design

It is open-source, and available at http://codeplex.com/elephant

Some one’s made a working example of the gpg6-code, you can find it here: http://www.unseen-academy.de/componentSystem.html

or here: http://www.mcshaffry.com/GameCode/thread.php?threadid=732

regards

How do I count the number of occurrences of a char in a String?

String[] parts = text.split(".");
int occurances = parts.length - 1;

" It's a great day at O.S.G. Dallas! "
     -- Famous Last Words

Well, it's a case of knowing your Java, especially your basic foundational understanding of the collection classes already available in Java. If you look throughout the entire posting here, there is just about everything short of Stephen Hawking's explanation of the Origin of the Universe, Darwin's paperback on Evolution and Gene Roddenberry's Star Trek cast selection as to why they went with William Shatner short of how to do this quickly and easily...

... need I say anymore?

Eclipse - debugger doesn't stop at breakpoint

Make sure, under Run > Debug Configurations, that 'Stop in main' is selected, if applicable to your situation.

How can I tell what edition of SQL Server runs on the machine?

SELECT  CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
         WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
         WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
         WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
         WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
         WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
         WHEN SERVERPROPERTY('EditionID') = -2117995310  THEN 'Developer'
         WHEN SERVERPROPERTY('EditionID') = 610778273  THEN 'Windows Embedded SQL'
         WHEN SERVERPROPERTY('EditionID') = 4161255391   THEN 'Express with Advanced Services'
    END AS 'Edition'; 

Python popen command. Wait until the command is finished

Let the command you are trying to pass be

os.system('x')

then you covert it to a statement

t = os.system('x')

now the python will be waiting for the output from the commandline so that it could be assigned to the variable t.

fastest way to export blobs from table into individual files

I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:

declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1; 
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources

You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

Fastest way to serialize and deserialize .NET objects

Yet another serializer out there that claims to be super fast is netserializer.

The data given on their site shows performance of 2x - 4x over protobuf, I have not tried this myself, but if you are evaluating various options, try this as well

How do I do logging in C# without using 3rd party libraries?

If you are looking for a real simple way to log, you can use this one liner. If the file doesn't exist, it's created.

System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

Processing $http response in service

tosh shimayama have a solution but you can simplify a lot if you use the fact that $http returns promises and that promises can return a value:

app.factory('myService', function($http, $q) {
  myService.async = function() {
    return $http.get('test.json')
    .then(function (response) {
      var data = reponse.data;
      console.log(data);
      return data;
    });
  };

  return myService;
});

app.controller('MainCtrl', function( myService,$scope) {
  $scope.asyncData = myService.async();
  $scope.$watch('asyncData', function(asyncData) {
    if(angular.isDefined(asyncData)) {
      // Do something with the returned data, angular handle promises fine, you don't have to reassign the value to the scope if you just want to use it with angular directives
    }
  });

});

A little demonstration in coffeescript: http://plunker.no.de/edit/ksnErx?live=preview

Your plunker updated with my method: http://plnkr.co/edit/mwSZGK?p=preview

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

After nearly seven years this keeps getting different answers.† Many are similar--but none identical--to what worked for me. Here's what worked for me (Ubuntu server).

Moving a site to a new server, forgot to install the PHP MySQL module/extension. I ran a quick

apt-get install php-mysql

and then

apachectl restart

Bada bing. No php5, php7; just plain php-mysql.

What is the difference between the operating system and the kernel?

Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.

If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.

The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.

So the ultimate difference is:

  1. Kernel is responsible for Hardware level interactions at some specific range. But the OS is like hardware level interaction with full scope of computer.
  2. Kernel triggers SystemCalls to tell the OS that this resource is available at this point of time. The OS is responsible to handle those system calls in order to utilize the resource.

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

In my own case I have the following error

Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='

$this->db->select("users.username as matric_no, CONCAT(users.surname, ' ', users.first_name, ' ', users.last_name) as fullname") ->join('users', 'users.username=classroom_students.matric_no', 'left') ->where('classroom_students.session_id', $session) ->where('classroom_students.level_id', $level) ->where('classroom_students.dept_id', $dept);

After weeks of google searching I noticed that the two fields I am comparing consists of different collation name. The first one i.e username is of utf8_general_ci while the second one is of utf8_unicode_ci so I went back to the structure of the second table and changed the second field (matric_no) to utf8_general_ci and it worked like a charm.

How to pass a view's onClick event to its parent on Android?

Declare your TextView not clickable / focusable by using android:clickable="false" and android:focusable="false" or v.setClickable(false) and v.setFocusable(false). The click events should be dispatched to the TextView's parent now.

Note:

In order to achieve this, you have to add click to its direct parent. or set android:clickable="false" and android:focusable="false" to its direct parent to pass listener to further parent.

Efficient SQL test query or validation query that will work across all (or most) databases

After a little bit of research along with help from some of the answers here:

SELECT 1

  • H2
  • MySQL
  • Microsoft SQL Server (according to NimChimpsky)
  • PostgreSQL
  • SQLite

SELECT 1 FROM DUAL

  • Oracle

SELECT 1 FROM any_existing_table WHERE 1=0

or

SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS

or

CALL NOW()

  • HSQLDB (tested with version 1.8.0.10)

    Note: I tried using a WHERE 1=0 clause on the second query, but it didn't work as a value for Apache Commons DBCP's validationQuery, since the query doesn't return any rows


VALUES 1 or SELECT 1 FROM SYSIBM.SYSDUMMY1

SELECT 1 FROM SYSIBM.SYSDUMMY1

  • DB2

select count(*) from systables

  • Informix

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

@Valkyrie awesome answer. Thought I put in here a case when performing the same with a subquery insides a stored procedure, as I wondered if your answer works in this case, and it did awesome.

...WHERE fieldname COLLATE DATABASE_DEFAULT in (
          SELECT DISTINCT otherfieldname COLLATE DATABASE_DEFAULT
          FROM ...
          WHERE ...
        )

What are the differences between Mustache.js and Handlebars.js?

One more subtle difference is the treatment of falsy values in {{#property}}...{{/property}} blocks. Most mustache implementations will just obey JS falsiness here, not rendering the block if property is '' or '0'.

Handlebars will render the block for '' and 0, but not other falsy values. This can cause some trouble when migrating templates.

How to do a HTTP HEAD request from the windows command line?

There is a Win32 port of wget that works decently.

PowerShell's Invoke-WebRequest -Method Head would work as well.

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

There's a library for conversion:

npm install dateformat

Then write your requirement:

var dateFormat = require('dateformat');

Then bind the value:

var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");

see dateformat

JQuery .on() method with multiple event handlers to one selector

I learned something really useful and fundamental from here.

chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.

It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter

function showPhotos() {
    $(this).find("span").slideToggle();
}

$(".photos")
    .on("mouseenter", "li", showPhotos)
    .on("mouseleave", "li", showPhotos);

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

execute this

EXEC sp_MSforeachtable 'PRINT ''ALTER TABLE ? NOCHECK CONSTRAINT ALL'''
EXEC sp_MSforeachtable 'print ''DELETE FROM ?'''
EXEC sp_MSforeachtable 'print ''ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'''

After copy the printed result and paste it on Query field and Execute it. It will truncate all tables.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

How to deny access to a file in .htaccess

Within an htaccess file, the scope of the <Files> directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).

So you can have:

<Files "log.txt">  
  Order Allow,Deny
  Deny from all
</Files>

For Apache 2.4+, you'd use:

<Files "log.txt">  
  Require all denied
</Files>

In an htaccess file in your inscription directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:

RewriteRule /?\.htaccess$ - [F,L]

RewriteRule ^/?inscription/log\.txt$ - [F,L]

Enable vertical scrolling on textarea

You can try adding:

#aboutDescription
{
    height: 100px;
    max-height: 100px;  
}

How to use LocalBroadcastManager?

I'd rather like to answer comprehensively.

  1. LocalbroadcastManager included in android 3.0 and above so you have to use support library v4 for early releases. see instructions here

  2. Create a broadcast receiver:

    private BroadcastReceiver onNotice= new BroadcastReceiver() {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // intent can contain anydata
            Log.d("sohail","onReceive called");
            tv.setText("Broadcast received !");
    
        }
    };
    
  3. Register your receiver in onResume of activity like:

    protected void onResume() {
            super.onResume();
    
            IntentFilter iff= new IntentFilter(MyIntentService.ACTION);
            LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, iff);
        }
    
    //MyIntentService.ACTION is just a public static string defined in MyIntentService.
    
  4. unRegister receiver in onPause:

    protected void onPause() {
      super.onPause();
      LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
    }
    
  5. Now whenever a localbroadcast is sent from applications' activity or service, onReceive of onNotice will be called :).

Edit: You can read complete tutorial here LocalBroadcastManager: Intra application message passing

How to remove any URL within a string in Python

In order to remove any URL within a string in Python, you can use this RegEx function :

import re

def remove_URL(text):
    """Remove URLs from a text string"""
    return re.sub(r"http\S+", "", text)

How do I compare two hashes?

If you want to get what is the difference between two hashes, you can do this:

h1 = {:a => 20, :b => 10, :c => 44}
h2 = {:a => 2, :b => 10, :c => "44"}
result = {}
h1.each {|k, v| result[k] = h2[k] if h2[k] != v }
p result #=> {:a => 2, :c => "44"}

Convert Pandas Column to DateTime

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I would guess this is due to some chaining indexing.

Best way to get the max value in a Spark dataframe column

To just get the value use any of these

  1. df1.agg({"x": "max"}).collect()[0][0]
  2. df1.agg({"x": "max"}).head()[0]
  3. df1.agg({"x": "max"}).first()[0]

Alternatively we could do these for 'min'

from pyspark.sql.functions import min, max
df1.agg(min("id")).collect()[0][0]
df1.agg(min("id")).head()[0]
df1.agg(min("id")).first()[0]

Transmitting newline character "\n"

Try using %0A in the URL, just like you've used %20 instead of the space character.

How to get value from form field in django framework?

Take your pick:

def my_view(request):

    if request.method == 'POST':
        print request.POST.get('my_field')

        form = MyForm(request.POST)

        print form['my_field'].value()
        print form.data['my_field']

        if form.is_valid():

            print form.cleaned_data['my_field']
            print form.instance.my_field

            form.save()
            print form.instance.id  # now this one can access id/pk

Note: the field is accessed as soon as it's available.

Toggle Class in React

For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.

How to check if a user is logged in (how to properly use user.is_authenticated)?

If you want to check for authenticated users in your template then:

{% if user.is_authenticated %}
    <p>Authenticated user</p>
{% else %}
    <!-- Do something which you want to do with unauthenticated user -->
{% endif %}

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

What does it mean when MySQL is in the state "Sending data"?

This is quite a misleading status. It should be called "reading and filtering data".

This means that MySQL has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.

If you have a 1M records table (without an index) of which you need only one record, MySQL will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

The location of jfxrt.jar in JDK 1.8 (Windows) is:

C:\Program Files\Java\jdk1.8.0_05\jre\lib\ext\jfxrt.jar

How do I get rid of the b-prefix in a string in python?

****How to remove b' ' chars which is decoded string in python ****

import base64
a='cm9vdA=='
b=base64.b64decode(a).decode('utf-8')
print(b)

Javascript to sort contents of select element

Í think this is a better option (I use @Matty's code and improved!):

function sortSelect(selElem, bCase) {
                var tmpAry = new Array();
                bCase = (bCase ? true : false);
                for (var i=0;i<selElem.options.length;i++) {
                        tmpAry[i] = new Array();
                        tmpAry[i][0] = selElem.options[i].text;
                        tmpAry[i][1] = selElem.options[i].value;
                }
                if (bCase)
                    tmpAry.sort(function (a, b) {
                        var ret = 0;
                        var iPos = 0;
                        while (ret == 0 && iPos < a.length && iPos < b.length)
                        {
                            ret = (String(a).toLowerCase().charCodeAt(iPos) - String(b).toLowerCase().charCodeAt(iPos));
                            iPos ++;
                        }
                        if (ret == 0)
                        {
                            ret = (String(a).length - String(b).length);
                        }
                        return ret;
                        });
                else
                    tmpAry.sort();
                while (selElem.options.length > 0) {
                    selElem.options[0] = null;
                }
                for (var i=0;i<tmpAry.length;i++) {
                        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
                        selElem.options[i] = op;
                }
                return;
        }

Getting the WordPress Post ID of current post

global $post;
echo $post->ID;

Wampserver icon not going green fully, mysql services not starting up?

simplest this to do is find what other service is using the same service id as mysql does in windows.

When i looked through the list of services running on my pc (even after a restart...i still had the problem)

I quickly realised i had webmatrix installed on my computer previous to wamp server...webmatrix installed its own copy of mysql and set it to automatically startup another instance each time i logged in.

As soon as the other instance of mysql associated with web matrix was stopped (and changed from automatic startup to manual) my problem with WAMP mysql was solved.

Gson: How to exclude specific fields from Serialization without annotations

I ran into this issue, in which I had a small number of fields I wanted to exclude only from serialization, so I developed a fairly simple solution that uses Gson's @Expose annotation with custom exclusion strategies.

The only built-in way to use @Expose is by setting GsonBuilder.excludeFieldsWithoutExposeAnnotation(), but as the name indicates, fields without an explicit @Expose are ignored. As I only had a few fields I wanted to exclude, I found the prospect of adding the annotation to every field very cumbersome.

I effectively wanted the inverse, in which everything was included unless I explicitly used @Expose to exclude it. I used the following exclusion strategies to accomplish this:

new GsonBuilder()
        .addSerializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                final Expose expose = fieldAttributes.getAnnotation(Expose.class);
                return expose != null && !expose.serialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        })
        .addDeserializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                final Expose expose = fieldAttributes.getAnnotation(Expose.class);
                return expose != null && !expose.deserialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        })
        .create();

Now I can easily exclude a few fields with @Expose(serialize = false) or @Expose(deserialize = false) annotations (note that the default value for both @Expose attributes is true). You can of course use @Expose(serialize = false, deserialize = false), but that is more concisely accomplished by declaring the field transient instead (which does still take effect with these custom exclusion strategies).

SQL string value spanning multiple lines in query

I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:

string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
   *
FROM
   tableA
WHERE
   Name = '{0}' AND
   Gender = '{1}'", name, gender);

It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting

Find first element by predicate

However this seems inefficient to me, as the filter will scan the whole list

No it won't - it will "break" as soon as the first element satisfying the predicate is found. You can read more about laziness in the stream package javadoc, in particular (emphasis mine):

Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.

How to discard local commits in Git?

I had to do a :

git checkout -b master

as git said that it doesn't exists, because it's been wipe with the

git -D master

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Text overwrite in visual studio 2010

I'm using Visual Studio with Parallels/Win 7 on a MacBook laptop keyboard and the only thing that worked was Fn + Enter/Return (that's the Mac shortcut for Insert).

How to Scroll Down - JQuery

This can be used in to solve this problem

<div id='scrol'></div> 

in javascript use this

jQuery("div#scrol").scrollTop(jQuery("div#scrol")[0].scrollHeight);

How to select following sibling/xml tag using xpath

How would I accomplish the nextsibling and is there an easier way of doing this?

You may use:

tr/td[@class='name']/following-sibling::td

but I'd rather use directly:

tr[td[@class='name'] ='Brand']/td[@class='desc']

This assumes that:

  1. The context node, against which the XPath expression is evaluated is the parent of all tr elements -- not shown in your question.

  2. Each tr element has only one td with class attribute valued 'name' and only one td with class attribute valued 'desc'.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.

How can I use a batch file to write to a text file?

@echo off Title Writing using Batch Files color 0a

echo Example Text > Filename.txt echo Additional Text >> Filename.txt

@ECHO OFF
Title Writing Using Batch Files
color 0a

echo Example Text > Filename.txt
echo Additional Text >> Filename.txt

How can I change default dialog button text color in android 5

The simpliest solution is:

dialog.show(); //Only after .show() was called
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);

How to show particular image as thumbnail while implementing share on Facebook?

My tags were correct but Facebook only scrapes every 24 hours, according to their documentation. Using the Facebook Lint page got the image into Facebook.

Enter your URL here and FB will update the metadata from your page:

https://developers.facebook.com/tools/debug (updated link)

Connecting to a network folder with username/password in Powershell

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either use net use or the WScript.Network object, calling the MapNetworkDrive function:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

If you are using bootstrap that will be the problem. If you want to use same bootstrap file in two locations use it below the header section .(example - inside body)

Note : "specially when you use html editors. "

Thank you.

Change project name on Android Studio

I just went into the manifest and changed android:label="...." to the name of the application. Once Id changed this, the title and the actual app name changed to that :)

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

How to select the first element with a specific attribute using XPath

if namespace is provided on the given xml, its better to use this.

(/*[local-name() ='bookstore']/*[local-name()='book'][@location='US'])[1]

How to set the initial zoom/width for a webview

in Kotlin You can use,

webView.isScrollbarFadingEnabled = true
webView.setInitialScale(100)

Configure Log4net to write to multiple files

Yes, just add multiple FileAppenders to your logger. For example:

<log4net>
    <appender name="File1Appender" type="log4net.Appender.FileAppender">
        <file value="log-file-1.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %message%newline" />
        </layout>
    </appender>
    <appender name="File2Appender" type="log4net.Appender.FileAppender">
        <file value="log-file-2.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %message%newline" />
        </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="File1Appender" />
        <appender-ref ref="File2Appender" />
    </root>
</log4net>

Remove Rows From Data Frame where a Row matches a String

I had a column(A) in a data frame with 3 values in it (yes, no, unknown). I wanted to filter only those rows which had a value "yes" for which this is the code, hope this will help you guys as well --

df <- df [(!(df$A=="no") & !(df$A=="unknown")),]

How to create a new branch from a tag?

My branch list (only master now)

branch list

My tag list (have three tags)

tag list

Switch to new branch feature/codec from opus_codec tag

git checkout -b feature/codec opus_codec

switch to branch

Please run `npm cache clean`

This error can be due to many many things.

The key here seems the hint about error reading. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.

You could also try with sudo, that might solve a permission problem if that's the case.

Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...