Programs & Examples On #Qlineedit

QLineEdit is a component of the Qt library which is basically a text editor that has only one line, and which allows one to make inputting and editing of text. A related class is QTextEdit which allows multi-line, rich text editing.

How to get text in QlineEdit when QpushButton is pressed in a string?

Acepted solution implemented in PyQt5

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect")
        self.pb.clicked.connect(self.button_click)

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)
        self.setLayout(layout)

        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print (shost)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

Set QLineEdit to accept only numbers

QLineEdit::setValidator(), for example:

myLineEdit->setValidator( new QIntValidator(0, 100, this) );

or

myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );

See: QIntValidator, QDoubleValidator, QLineEdit::setValidator

How to place div in top right hand corner of page

You can use css float

<div style='float: left;'><a href="login.php">Log in</a></div>

<div style='float: right;'><a href="home.php">Back to Home</a></div>

Have a look at this CSS Positioning

Pinging servers in Python

  1 #!/usr/bin/python
  2
  3 import os
  4 import sys
  5 import time
  6
  7 os.system("clear")
  8 home_network = "172.16.23."
  9 mine = []
 10
 11 for i in range(1, 256):
 12         z =  home_network + str(i)
 13         result = os.system("ping -c 1 "+ str(z))
 14         os.system("clear")
 15         if result == 0:
 16                 mine.append(z)
 17
 18 for j in mine:
 19         print "host ", j ," is up"

A simple one i just cooked up in a minute..using icmplib needs root privs the below works pretty good! HTH

How to do vlookup and fill down (like in Excel) in R?

You could use mapvalues() from the plyr package.

Initial data:

dat <- data.frame(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"))

> dat
  HouseType
1      Semi
2    Single
3       Row
4    Single
5 Apartment
6 Apartment
7       Row

Lookup / crosswalk table:

lookup <- data.frame(type_text = c("Semi", "Single", "Row", "Apartment"), type_num = c(1, 2, 3, 4))
> lookup
  type_text type_num
1      Semi        1
2    Single        2
3       Row        3
4 Apartment        4

Create the new variable:

dat$house_type_num <- plyr::mapvalues(dat$HouseType, from = lookup$type_text, to = lookup$type_num)

Or for simple replacements you can skip creating a long lookup table and do this directly in one step:

dat$house_type_num <- plyr::mapvalues(dat$HouseType,
                                      from = c("Semi", "Single", "Row", "Apartment"),
                                      to = c(1, 2, 3, 4))

Result:

> dat
  HouseType house_type_num
1      Semi              1
2    Single              2
3       Row              3
4    Single              2
5 Apartment              4
6 Apartment              4
7       Row              3

Where can I get Google developer key

You should be able to generate a Youtube API key there.

The recommended way to authorize your API call is to use OAuth 2.0 (without API key), as pointed by the documentation an API key is only necessary when using OAuth 1.0 credentials.

The API key for your application can be found in the Google APIs Console in API Access > Simple API.

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

Instead of messing up your pom file, I would suggest you to go to Show View ? Markers in Eclipse, select and delete the markers of appropriate errors.

How to set a selected option of a dropdown list control using angular JS

It can be usefull. Bindings dose not always work.

<select id="product" class="form-control" name="product" required
        ng-model="issue.productId"
        ng-change="getProductVersions()"
        ng-options="p.id as p.shortName for p in products">
</select>

For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".

$scope.issue.productId = productId;
function activate() {
   $http.get('/product/list')
     .then(function (response) {
       $scope.products = response.data;

       if (productId) {
           console.log("" + $("#product option").length);//for clarity                       
           $timeout(function () {
               console.log("" + $("#product option").length);//for clarity
               $('#product').val('number:'+productId);
               //$scope.issue.productId = productId;//not work at all
           }, 200);
       }
   });
}

Namespace for [DataContract]

DataContractAttribute Class is in the System.Runtime.Serialization namespace.

You should add a reference to System.Runtime.Serialization.dll. That assembly isn't referenced by default though. To add the reference to your project you have to go to References -> Add Reference in the Solution Explorer and add an assembly reference manually.

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

if you use .Values while creating the matrix X and Y vectors it will fix the problem.

y=dataset.iloc[:, 4].values

X=dataset.iloc[:, 0:4].values

when you use .Values it creates a Object representation of the created matrix will be returned with the axes removed. Check the below link for more information

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html

How to run Python script on terminal?

If you are working with Ubuntu, sometimes you need to run as sudo:

For Python2:

sudo python gameover.py

For Python3:

sudo python3 gameover.py

How can I convert an HTML element to a canvas element?

You can use dom-to-image library (I'm the maintainer).
Here's how you could approach your problem:

var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');

var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;

domtoimage.toPng(node).then(function (pngDataUrl) {
    var img = new Image();
    img.onload = function () {
        var context = canvas.getContext('2d');

        context.translate(canvas.width, 0);
        context.scale(-1, 1);
        context.drawImage(img, 0, 0);

        parent.removeChild(node);
        parent.appendChild(canvas);
    };

    img.src = pngDataUrl;
});

And here is jsfiddle

Display loading image while post with ajax

Let's say you have a tag someplace on the page which contains your loading message:

<div id='loadingmessage' style='display:none'>
  <img src='loadinggraphic.gif'/>
</div>

You can add two lines to your ajax call:

function getData(p){
    var page=p;
    $('#loadingmessage').show();  // show the loading message.
    $.ajax({
        url: "loadData.php?id=<? echo $id; ?>",
        type: "POST",
        cache: false,
        data: "&page="+ page,
        success : function(html){
            $(".content").html(html);
            $('#loadingmessage').hide(); // hide the loading message
        }
    });

An App ID with Identifier '' is not available. Please enter a different string

If not the AppId's business,just try to change the Team in TARGETS/identity to your company's team.

When do I use the PHP constant "PHP_EOL"?

No, PHP_EOL does not handle endline issues, because the system where you use that constant is not the same system where you send the output to.

I would not recommend using PHP_EOL at all. Unix/Linux use \n, MacOS / OS X changed from \r to \n too and on Windows many applications (especially browsers) can display it correctly too. On Windows, it is also easy change existing client-side code to use \n only and still maintain backward-compatibility: Just change the delimiter for line trimming from \r\n to \n and wrap it in a trim() like function.

Generating Random Number In Each Row In Oracle Query

you don’t need a select … from dual, just write:

SELECT t.*, dbms_random.value(1,9) RandomNumber
  FROM myTable t

How to link C++ program with Boost using CMake

Two ways, using system default install path, usually /usr/lib/x86_64-linux-gnu/:

find_package(Boost REQUIRED regex date_time system filesystem thread graph)
include_directories(${BOOST_INCLUDE_DIRS})
message("boost lib: ${Boost_LIBRARIES}")
message("boost inc:${Boost_INCLUDE_DIR}")

add_executable(use_boost use_boost.cpp)
target_link_libraries(use_boost
        ${Boost_LIBRARIES}
        )

If you install Boost in a local directory or choose local install instead of system install, you can do it by this:

set( BOOST_ROOT "/home/xy/boost_install/lib/" CACHE PATH "Boost library path" )
set( Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost" )

find_package(Boost REQUIRED regex date_time system filesystem thread graph)
include_directories(${BOOST_INCLUDE_DIRS})
message("boost lib: ${Boost_LIBRARIES}, inc:${Boost_INCLUDE_DIR}")

add_executable(use_boost use_boost.cpp)
target_link_libraries(use_boost
        ${Boost_LIBRARIES}
        )

Note the above dir /home/xy/boost_install/lib/ is where I install Boost:

xy@xy:~/boost_install/lib$ ll -th
total 16K
drwxrwxr-x 2 xy xy 4.0K May 28 19:23 lib/
drwxrwxr-x 3 xy xy 4.0K May 28 19:22 include/

xy@xy:~/boost_install/lib$ ll -th lib/
total 57M
drwxrwxr-x 2 xy xy 4.0K May 28 19:23 ./
-rw-rw-r-- 1 xy xy 2.3M May 28 19:23 libboost_test_exec_monitor.a
-rw-rw-r-- 1 xy xy 2.2M May 28 19:23 libboost_unit_test_framework.a
.......

xy@xy:~/boost_install/lib$ ll -th include/
total 20K
drwxrwxr-x 110 xy xy  12K May 28 19:22 boost/

If you are interested in how to use a local installed Boost, you can see this question How can I get CMake to find my alternative Boost installation?.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Your entity may not listed in hibernate configuration file.

ProgressDialog is deprecated.What is the alternate one to use?

Yes, ProgressDialog is deprecated but Dialog isn't.

You can inflate your own XML file ( containing a progress bar and a loading text) into your dialog object and then display or hide it using the show() and dismiss() functions. Here is an example (Kotlin):

ProgressDialog class:

class ProgressDialog {
companion object {
    fun progressDialog(context: Context): Dialog{
        val dialog = Dialog(context)
        val inflate = LayoutInflater.from(context).inflate(R.layout.progress_dialog, null)
        dialog.setContentView(inflate)
        dialog.setCancelable(false)
        dialog.window!!.setBackgroundDrawable(
                ColorDrawable(Color.TRANSPARENT))
        return dialog
    }
  }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:background="#fff"
android:padding="13dp"
android:layout_height="wrap_content">
<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyle"
    android:layout_width="100dp"
    android:layout_margin="7dp"
    android:layout_height="100dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_margin="7dp"
    android:layout_toEndOf="@+id/progressBar"
    android:text="Loading..." />
</RelativeLayout>

In your code: Just do var dialog = ProgressDialog.progressDialog(context)

To show: dialog.show()

To hide: dialog.dismiss()

How do I set the background color of Excel cells using VBA?

or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.

There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.

How to change bower's default components folder?

Something worth mentioning...

As noted above by other contributors, using a .bowerrc file with the JSON

{ "directory": "some/path" }

is necessary -- HOWEVER, you may run into an issue on Windows while creating that file. If Windows gives you a message imploring you to add a "file name", simply use a text editor / IDE such as Notepad++.

Add the JSON to an unnamed file, save it as .bowerrc -- you're good to go!

Probably an easy assumption, but I hope this save others the unnecessary headache :)

fetch in git doesn't get all branches

To make it more specific Create a tracking branch, which means you are now tracking a remote branch.

git branch --track branch remote-branch
git branch --track exp remotes/origin/experimental

After which you can

git branch   # to see the remote tracking branch "exp" created .

Then to work on that branch do

git checkout branchname
git checkout exp

After you have made changes to the branch. You can git fetch and git merge with your remote tracking branch to merge your changes and push to the remote branch as below.

git fetch origin
git merge origin/experimental  
git push origin/experimental

Hope it helps and gives you an idea, how this works.

Can you control how an SVG's stroke-width is drawn?

As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.

The specification for strokes in Adobe's PostScript Manual 2nd edition states: "4.5.1 Stroking: The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)

The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.

Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.

How to send post request to the below post method using postman rest client

1.Open postman app 2.Enter the URL in the URL bar in postman app along with the name of the design.Use slash(/) after URL to give the design name. 3.Select POST from the dropdown list from URL textbox. 4.Select raw from buttons available below the URL textbox. 5.Select JSON from the dropdown. 6.In the text area enter your data to be updated and enter send. 7.Select GET from dropdown list from URL textbox and enter send to see the updated result.

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

hope this helps someone. this worked for me on Ubuntu 18.10

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver', options=chrome_options)
driver.get('http://www.google.com')
print('test')
driver.close()

MVVM: Tutorial from start to finish?

I read Josh Smith's article and found it very difficult. Once understood, I wrote a very simple one that should get you really started on it. Get it here.

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the minimum version of the Android operating system required to run your application.

The target sdk version is the version of Android that your app was created to run on.

The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.

Usually the compile sdk version and the target sdk version are the same.

How to move from one fragment to another fragment on click of an ImageView in Android?

you can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existance of activities.

You can call another fragment by writing the code below:

        FragmentTransaction t = this.getFragmentManager().beginTransaction();
        Fragment mFrag = new MyFragment();
        t.replace(R.id.content_frame, mFrag);
        t.commit();

here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.

you can also add the other fragment incase of replace.

What's with the dollar sign ($"string")

It's the new feature in C# 6 called Interpolated Strings.

The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.

For more details about this, please take a look at MSDN.

Now, think a little bit more about it. Why this feature is great?

For example, you have class Point:

public class Point
{
    public int X { get; set; }

    public int Y { get; set; }
}

Create 2 instances:

var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };

Now, you want to output it to the screen. The 2 ways that you usually use:

Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");

As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:

Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));

This creates a new problem:

  1. You have to maintain the number of arguments and index yourself. If the number of arguments and index are not the same, it will generate a runtime error.

For those reasons, we should use new feature:

Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");

The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

For the full post, please read this blog.

Check line for unprintable characters while reading text file

Just found out that with the Java NIO (java.nio.file.*) you can easily write:

List<String> lines=Files.readAllLines(Paths.get("/tmp/test.csv"), StandardCharsets.UTF_8);
for(String line:lines){
  System.out.println(line);
}

instead of dealing with FileInputStreams and BufferedReaders...

python pandas extract year from datetime: df['year'] = df['date'].year is not working

Probably already too late to answer but since you have already parse the dates while loading the data, you can just do this to get the day

df['date'] = pd.DatetimeIndex(df['date']).year

How to make program go back to the top of the code instead of closing

Python has control flow statements instead of goto statements. One implementation of control flow is Python's while loop. You can give it a boolean condition (boolean values are either True or False in Python), and the loop will execute repeatedly until that condition becomes false. If you want to loop forever, all you have to do is start an infinite loop.

Be careful if you decide to run the following example code. Press Control+C in your shell while it is running if you ever want to kill the process. Note that the process must be in the foreground for this to work.

while True:
    # do stuff here
    pass

The line # do stuff here is just a comment. It doesn't execute anything. pass is just a placeholder in python that basically says "Hi, I'm a line of code, but skip me because I don't do anything."

Now let's say you want to repeatedly ask the user for input forever and ever, and only exit the program if the user inputs the character 'q' for quit.

You could do something like this:

while True:
    cmd = raw_input('Do you want to quit? Enter \'q\'!')
    if cmd == 'q':
        break

cmd will just store whatever the user inputs (the user will be prompted to type something and hit enter). If cmd stores just the letter 'q', the code will forcefully break out of its enclosing loop. The break statement lets you escape any kind of loop. Even an infinite one! It is extremely useful to learn if you ever want to program user applications which often run on infinite loops. If the user does not type exactly the letter 'q', the user will just be prompted repeatedly and infinitely until the process is forcefully killed or the user decides that he's had enough of this annoying program and just wants to quit.

How to get PID of process by specifying process name and store it in a variable to use further?

pids=$(pgrep <name>)

will get you the pids of all processes with the given name. To kill them all, use

kill -9 $pids

To refrain from using a variable and directly kill all processes with a given name issue

pkill -9 <name>

How to count items in JSON object using command line?

The shortest expression is

curl 'http://…' | jq length

Regular expression replace in C#

You can do it this with two replace's

//let stw be "John Smith $100,000.00 M"

sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"

sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"

sw.WriteLine(sb_trim);

Determine the line of code that causes a segmentation fault?

Lucas's answer about core dumps is good. In my .cshrc I have:

alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"'

to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.

Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.

Cheap way to search a large text file for a string

I've had a go at putting together a multiprocessing example of file text searching. This is my first effort at using the multiprocessing module; and I'm a python n00b. Comments quite welcome. I'll have to wait until at work to test on really big files. It should be faster on multi core systems than single core searching. Bleagh! How do I stop the processes once the text has been found and reliably report line number?

import multiprocessing, os, time
NUMBER_OF_PROCESSES = multiprocessing.cpu_count()

def FindText( host, file_name, text):
    file_size = os.stat(file_name ).st_size 
    m1 = open(file_name, "r")

    #work out file size to divide up to farm out line counting

    chunk = (file_size / NUMBER_OF_PROCESSES ) + 1
    lines = 0
    line_found_at = -1

    seekStart = chunk * (host)
    seekEnd = chunk * (host+1)
    if seekEnd > file_size:
        seekEnd = file_size

    if host > 0:
        m1.seek( seekStart )
        m1.readline()

    line = m1.readline()

    while len(line) > 0:
        lines += 1
        if text in line:
            #found the line
            line_found_at = lines
            break
        if m1.tell() > seekEnd or len(line) == 0:
            break
        line = m1.readline()
    m1.close()
    return host,lines,line_found_at

# Function run by worker processes
def worker(input, output):
    for host,file_name,text in iter(input.get, 'STOP'):
        output.put(FindText( host,file_name,text ))

def main(file_name,text):
    t_start = time.time()
    # Create queues
    task_queue = multiprocessing.Queue()
    done_queue = multiprocessing.Queue()
    #submit file to open and text to find
    print 'Starting', NUMBER_OF_PROCESSES, 'searching workers'
    for h in range( NUMBER_OF_PROCESSES ):
        t = (h,file_name,text)
        task_queue.put(t)

    #Start worker processes
    for _i in range(NUMBER_OF_PROCESSES):
        multiprocessing.Process(target=worker, args=(task_queue, done_queue)).start()

    # Get and print results

    results = {}
    for _i in range(NUMBER_OF_PROCESSES):
        host,lines,line_found = done_queue.get()
        results[host] = (lines,line_found)

    # Tell child processes to stop
    for _i in range(NUMBER_OF_PROCESSES):
        task_queue.put('STOP')
#        print "Stopping Process #%s" % i

    total_lines = 0
    for h in range(NUMBER_OF_PROCESSES):
        if results[h][1] > -1:
            print text, 'Found at', total_lines + results[h][1], 'in', time.time() - t_start, 'seconds'
            break
        total_lines += results[h][0]

if __name__ == "__main__":
    main( file_name = 'testFile.txt', text = 'IPI1520' )

Up, Down, Left and Right arrow keys do not trigger KeyDown event

See Rodolfo Neuber's reply for the best answer


(My original answer):

Derive from a control class and you can override the ProcessCmdKey method. Microsoft chose to omit these keys from KeyDown events because they affect multiple controls and move the focus, but this makes it very difficult to make an app react to these keys in any other way.

How to create JSON Object using String?

If you use the gson.JsonObject you can have something like that:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)

What are CN, OU, DC in an LDAP search?

  • CN = Common Name
  • OU = Organizational Unit
  • DC = Domain Component

These are all parts of the X.500 Directory Specification, which defines nodes in a LDAP directory.

You can also read up on LDAP data Interchange Format (LDIF), which is an alternate format.

You read it from right to left, the right-most component is the root of the tree, and the left most component is the node (or leaf) you want to reach.

Each = pair is a search criteria.

With your example query

("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");

In effect the query is:

From the com Domain Component, find the google Domain Component, and then inside it the gl Domain Component and then inside it the gp Domain Component.

In the gp Domain Component, find the Organizational Unit called Distribution Groups and then find the the object that has a common name of Dev-India.

In Chart.js set chart title, name of x axis and y axis?

just use this:

<script>
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ["1","2","3","4","5","6","7","8","9","10","11",],
      datasets: [{
        label: 'YOUR LABEL',
        backgroundColor: [
          "#566573",
          "#99a3a4",
          "#dc7633",
          "#f5b041",
          "#f7dc6f",
          "#82e0aa",
          "#73c6b6",
          "#5dade2",
          "#a569bd",
          "#ec7063",
          "#a5754a"
        ],
        data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],            
      },]
    },
    //HERE COMES THE AXIS Y LABEL
    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }
  });
</script>

Django: Display Choice Value

Others have pointed out that a get_FOO_display method is what you need. I'm using this:

def get_type(self):
    return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]

which iterates over all of the choices that a particular item has until it finds the one that matches the items type

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

In Retrofit2, When you want to send your parameters in raw you must use Scalars.

first add this in your gradle:

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

    public interface ApiInterface {

    String URL_BASE = "http://10.157.102.22/rest/";

    @Headers("Content-Type: application/json")
    @POST("login")
    Call<User> getUser(@Body String body);

}

my SampleActivity :

   public class SampleActivity extends AppCompatActivity implements Callback<User> {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.URL_BASE)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);


        // prepare call in Retrofit 2.0
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("email", "[email protected]");
            paramObject.put("pass", "4384984938943");

            Call<User> userCall = apiInterface.getUser(paramObject.toString());
            userCall.enqueue(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
    }
}

Reference: [How to POST raw whole JSON in the body of a Retrofit request?

Convert list to dictionary using linq and not worrying about duplicates

        DataTable DT = new DataTable();
        DT.Columns.Add("first", typeof(string));
        DT.Columns.Add("second", typeof(string));

        DT.Rows.Add("ss", "test1");
        DT.Rows.Add("sss", "test2");
        DT.Rows.Add("sys", "test3");
        DT.Rows.Add("ss", "test4");
        DT.Rows.Add("ss", "test5");
        DT.Rows.Add("sts", "test6");

        var dr = DT.AsEnumerable().GroupBy(S => S.Field<string>("first")).Select(S => S.First()).
            Select(S => new KeyValuePair<string, string>(S.Field<string>("first"), S.Field<string>("second"))).
           ToDictionary(S => S.Key, T => T.Value);

        foreach (var item in dr)
        {
            Console.WriteLine(item.Key + "-" + item.Value);
        }

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

How can I compare time in SQL Server?

Just change convert datetime to time that should do the trick:

SELECT timeEvent 
FROM tbEvents 
WHERE convert(time, startHour) >= convert(time, @startHour)

How to align td elements in center

Give a style inside the td element or in your scss file, like this:

vertical-align: 
    middle;

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.

For that need to add the 2021 partition into that table

ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS

Bash: Echoing a echo command with a variable in bash

echo "echo "we are now going to work with ${ser}" " >> $servfile

Escape all " within quotes with \. Do this with variables like \$servicetest too:

echo "echo \"we are now going to work with \${ser}\" " >> $servfile    
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile

how to get date of yesterday using php?

Step 1

We need set format data in function date(): Function date() returns a string formatted according to the givenformat string using the given integer timestamp or the current time ifno timestamp is given. In other words, timestampis optional anddefaults to the value of time().

<?php
echo date("F j, Y");
?>

result: March 30, 2010

Step 2

For "yesterday" date use php function mktime(): Function mktime() returns the Unix timestamp corresponding to thearguments given. This timestamp is a long integer containing the numberof seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and thetime specified. Arguments may be left out in order from right to left; any argumentsthus omitted will be set to the current value according to the localdate and time.

<?php
echo mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));
?>

result: 1269820800

Step 3

Now merge all and look at this:

<?php
$yesterday = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));
echo $yesterday;
?>

result: March 29, 2010

Operating similarly, it is possible to receive time hour back.

<?php
$yesterday = date("H:i:s",mktime(date("H"), 0, 0, date("m"),date("d"), date("Y")));
echo $yesterday;
?>

result: 20:00:00

or 7 days ago:

<?php
$week = date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-7,date("Y")));
echo $week;
?>

result: 2010-03-23

How to close current tab in a browser window?

<button class="closeButton" style="cursor: pointer" onclick="window.close();">Close Window</button>

this did the work for me

How could I create a function with a completion handler in Swift?

Swift 5.0 + , Simple and Short

example:

Style 1

    func methodName(completionBlock: () -> Void)  {

          print("block_Completion")
          completionBlock()
    }

Style 2

    func methodName(completionBlock: () -> ())  {

        print("block_Completion")
        completionBlock()
    }

Use:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        methodName {

            print("Doing something after Block_Completion!!")
        }
    }

Output

block_Completion

Doing something after Block_Completion!!

Display a RecyclerView in Fragment

You should retrieve RecyclerView in a Fragment after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    }).start();

    return view;
}

What is a practical use for a closure in JavaScript?

The JavaScript module pattern uses closures. Its nice pattern allows you to have something alike "public" and "private" variables.

var myNamespace = (function () {

  var myPrivateVar, myPrivateMethod;

  // A private counter variable
  myPrivateVar = 0;

  // A private function which logs any arguments
  myPrivateMethod = function(foo) {
      console.log(foo);
  };

  return {

    // A public variable
    myPublicVar: "foo",

    // A public function utilizing privates
    myPublicFunction: function(bar) {

      // Increment our private counter
      myPrivateVar++;

      // Call our private method using bar
      myPrivateMethod(bar);
    }
  };

})();

Is it possible to start a shell session in a running container (without ssh)

first, get the container id of the desired container by

docker ps

you will get something like this:

CONTAINER ID        IMAGE                  COMMAND             CREATED             STATUS                          PORTS                    NAMES
3ac548b6b315        frontend_react-web     "npm run start"     48 seconds ago      Up 47 seconds                   0.0.0.0:3000->3000/tcp   frontend_react-web_1

now copy this container id and run the following command:

docker exec -it container_id sh

docker exec -it 3ac548b6b315 sh

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

The above solution works perfectly. I prefer to choose Web API option while selecting the project template as shown in the picture below

Note: The solution works with Visual Studio 2013 or higher. The original question was asked in 2012 and it is 2016, therefore adding a solution Visual Studio 2013 or higher.

Project template showing web API option

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

case in sql stored procedure on SQL Server

(SELECT CASE WHEN (SELECT  Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 )=0 THEN 'Pending'
WHEN (SELECT  Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 AND )<>0 THEN (SELECT CASE  WHEN ISNULL(ChequeNo,0) IS NOT NULL   THEN 'Deposit' ELSE 'Pending' END AS Deposite FROM tbl_EEsi WHERE  AND (Month= 1) AND (Year = 2020) AND )END AS Stat)

Detect Close windows event by jQuery

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

<script type="text/javascript">
$(document).ready(function() {
  $(document).mousemove(function(e) {
    if(e.pageY <= 5)
    {
        //this condition would occur when the user brings their cursor on address bar 
        //do something here 
    }
  });
});
</script>

Wavy shape with css

I'm not sure it's your shape but it's close - you can play with the values:

https://jsfiddle.net/7fjSc/9/

_x000D_
_x000D_
#wave {_x000D_
  position: relative;_x000D_
  height: 70px;_x000D_
  width: 600px;_x000D_
  background: #e0efe3;_x000D_
}_x000D_
#wave:before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100% 50%;_x000D_
  width: 340px;_x000D_
  height: 80px;_x000D_
  background-color: white;_x000D_
  right: -5px;_x000D_
  top: 40px;_x000D_
}_x000D_
#wave:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100% 50%;_x000D_
  width: 300px;_x000D_
  height: 70px;_x000D_
  background-color: #e0efe3;_x000D_
  left: 0;_x000D_
  top: 27px;_x000D_
}
_x000D_
<div id="wave"></div>
_x000D_
_x000D_
_x000D_

Failed to load AppCompat ActionBar with unknown error in android studio

Replace implementation 'com.android.support:appcompat-v7:28.0.0-beta01' with

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1' 

in build.gradle (Module:app). It fixed my red mark in Android Studio 3.1.3

Pytorch reshape tensor dimension

Use torch.unsqueeze(input, dim, out=None)

>>> import torch
>>> a = torch.Tensor([1,2,3,4,5])
>>> a

 1
 2
 3
 4
 5
[torch.FloatTensor of size 5]

>>> a = a.unsqueeze(0)
>>> a

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

Sorting a Dictionary in place with respect to keys

While Dictionary is implemented as a hash table, SortedDictionary is implemented as a Red-Black Tree.

If you don't take advantage of the order in your algorithm and only need to sort the data before output, using SortedDictionary would have negative impact on performance.

You can "sort" the dictionary like this:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
// algorithm
return new SortedDictionary<string, int>(dictionary);

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

How to kill a child process after a given timeout in Bash?

Here's an attempt which tries to avoid killing a process after it has already exited, which reduces the chance of killing another process with the same process ID (although it's probably impossible to avoid this kind of error completely).

run_with_timeout ()
{
  t=$1
  shift

  echo "running \"$*\" with timeout $t"

  (
  # first, run process in background
  (exec sh -c "$*") &
  pid=$!
  echo $pid

  # the timeout shell
  (sleep $t ; echo timeout) &
  waiter=$!
  echo $waiter

  # finally, allow process to end naturally
  wait $pid
  echo $?
  ) \
  | (read pid
     read waiter

     if test $waiter != timeout ; then
       read status
     else
       status=timeout
     fi

     # if we timed out, kill the process
     if test $status = timeout ; then
       kill $pid
       exit 99
     else
       # if the program exited normally, kill the waiting shell
       kill $waiter
       exit $status
     fi
  )
}

Use like run_with_timeout 3 sleep 10000, which runs sleep 10000 but ends it after 3 seconds.

This is like other answers which use a background timeout process to kill the child process after a delay. I think this is almost the same as Dan's extended answer (https://stackoverflow.com/a/5161274/1351983), except the timeout shell will not be killed if it has already ended.

After this program has ended, there will still be a few lingering "sleep" processes running, but they should be harmless.

This may be a better solution than my other answer because it does not use the non-portable shell feature read -t and does not use pgrep.

Equivalent of *Nix 'which' command in PowerShell?

I like Get-Command | Format-List, or shorter, using aliases for the two and only for powershell.exe:

gcm powershell | fl

You can find aliases like this:

alias -definition Format-List

Tab completion works with gcm.

Wireshark localhost traffic capture

If you're using Windows it's not possible - read below. You can use the local address of your machine instead and then you'll be able to capture stuff. See CaptureSetup/Loopback.

Summary: you can capture on the loopback interface on Linux, on various BSDs including Mac OS X, and on Digital/Tru64 UNIX, and you might be able to do it on Irix and AIX, but you definitely cannot do so on Solaris, HP-UX....

Although the page mentions that this is not possible on Windows using Wireshark alone, you can actually record it using a workaround as mentioned in a different answer.


EDIT: Some 3 years later, this answer is no longer completely correct. The linked page contains instructions for capturing on the loopback interface.

Correct way to initialize empty slice

Empty slice and nil slice are initialized differently in Go:

var nilSlice []int 
emptySlice1 := make([]int, 0)
emptySlice2 := []int{}

fmt.Println(nilSlice == nil)    // true
fmt.Println(emptySlice1 == nil) // false
fmt.Println(emptySlice2 == nil) // false

As for all three slices, len and cap are 0.

How to add element to C++ array?

Initialize all your array elements to null first, then look for the null to find the empty slot

C: socket connection timeout

This one has parametrized ip, port, timeout in seconds, handle connection errors and give you connection time in milliseconds:

#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

int main(int argc, char **argv) {
    struct sockaddr_in addr_s;
    char *addr;
    short int fd=-1;
    int port;
    fd_set fdset;
    struct timeval tv;
    int rc;
    int so_error;
    socklen_t len;
    struct timespec tstart={0,0}, tend={0,0};
    int seconds;

    if (argc != 4) {
        fprintf(stderr, "Usage: %s <ip> <port> <timeout_seconds>\n", argv[0]);
        return 1;
    }

    addr = argv[1];
    port = atoi(argv[2]);
    seconds = atoi(argv[3]);

    addr_s.sin_family = AF_INET; // utilizzo IPv4
    addr_s.sin_addr.s_addr = inet_addr(addr);
    addr_s.sin_port = htons(port);

    clock_gettime(CLOCK_MONOTONIC, &tstart);

    fd = socket(AF_INET, SOCK_STREAM, 0);
    fcntl(fd, F_SETFL, O_NONBLOCK); // setup non blocking socket

    // make the connection
    rc = connect(fd, (struct sockaddr *)&addr_s, sizeof(addr_s));
    if ((rc == -1) && (errno != EINPROGRESS)) {
        fprintf(stderr, "Error: %s\n", strerror(errno));
        close(fd);
        return 1;
    }
    if (rc == 0) {
        // connection has succeeded immediately
        clock_gettime(CLOCK_MONOTONIC, &tend);
        printf("socket %s:%d connected. It took %.5f seconds\n",
            addr, port, (((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec)));

        close(fd);
        return 0;
    } /*else {
        // connection attempt is in progress
    } */

    FD_ZERO(&fdset);
    FD_SET(fd, &fdset);
    tv.tv_sec = seconds;
    tv.tv_usec = 0;

    rc = select(fd + 1, NULL, &fdset, NULL, &tv);
    switch(rc) {
    case 1: // data to read
        len = sizeof(so_error);

        getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_error, &len);

        if (so_error == 0) {
            clock_gettime(CLOCK_MONOTONIC, &tend);
            printf("socket %s:%d connected. It took %.5f seconds\n",
                addr, port, (((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec)));
            close(fd);
            return 0;
        } else { // error
            printf("socket %s:%d NOT connected: %s\n", addr, port, strerror(so_error));
        }
        break;
    case 0: //timeout
        fprintf(stderr, "connection timeout trying to connect to %s:%d\n", addr, port);
        break;
    }

    close(fd);
    return 0;
}

For files in directory, only echo filename (no path)

Another approach is to use ls when reading the file list within a directory so as to give you what you want, i.e. "just the file name/s". As opposed to reading the full file path and then extracting the "file name" component in the body of the for loop.

Example below that follows your original:

for filename in $(ls /home/user/)
do
  echo $filename
done;

If you are running the script in the same directory as the files, then it simply becomes:

for filename in $(ls)
do
  echo $filename
done;

How can I pipe stderr, and not stdout?

You can use the rc shell.

First install the package (it's less than 1 MB).

This an example of how you would discard standard output and pipe standard error to grep in rc:

find /proc/ >[1] /dev/null |[2] grep task

You can do it without leaving Bash:

rc -c 'find /proc/ >[1] /dev/null |[2] grep task'

As you may have noticed, you can specify which file descriptor you want piped by using brackets after the pipe.

Standard file descriptors are numerated as such:

  • 0 : Standard input
  • 1 : Standard output
  • 2 : Standard error

How to make a <svg> element expand or contract to its parent container?

@robertc has it right, but you also need to notice that svg, #container causes the svg to be scaled exponentially for anything but 100% (once for #container and once for svg).

In other words, if I applied 50% h/w to both elements, it's actually 50% of 50%, or .5 * .5, which equals .25, or 25% scale.

One selector works fine when used as @robertc suggests.

svg {
  width:50%;
  height:50%;
}

How to filter by object property in angularJS

We have Collection as below:


enter image description here

Syntax:

{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}

Example:

{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}

-OR-

Syntax:

ng-bind="(input | filter)"

Example:

ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"

Swift do-try-catch syntax

Create enum like this:

//Error Handling in swift
enum spendingError : Error{
case minus
case limit
}

Create method like:

 func calculateSpending(morningSpending:Double,eveningSpending:Double) throws ->Double{
if morningSpending < 0 || eveningSpending < 0{
    throw spendingError.minus
}
if (morningSpending + eveningSpending) > 100{
    throw spendingError.limit
}
return morningSpending + eveningSpending
}

Now check error is there or not and handle it:

do{
try calculateSpending(morningSpending: 60, eveningSpending: 50)
} catch spendingError.minus{
print("This is not possible...")
} catch spendingError.limit{
print("Limit reached...")
}

How to implement 2D vector array?

If you know the (maximum) number of rows and columns beforehand, you can use resize() to initialize a vector of vectors and then modify (and access) elements with operator[]. Example:

int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;

std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));

// Read from matrix.
int value = matrix[1][2];

// Save to matrix.
matrix[3][1] = 5;

Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column].

ORDER BY using Criteria API

This is what you have to do since sess.createCriteria is deprecated:

CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> usr = q.from(User.class);
ParameterExpression<String> p = builder.parameter(String.class);
q.select(usr).where(builder.like(usr.get("name"),p))
  .orderBy(builder.asc(usr.get("name")));
TypedQuery<User> query = getSession().createQuery(q);
query.setParameter(p, "%" + Main.filterName + "%");
List<User> list = query.getResultList();

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I came across this one while debugging a virtualmin/apache related error.

In my case, I am running virtualmin and had in my virtual machine's php.ini safe_mode=On.

In my Virtual Machine's error log, I was getting the fcgi Connection reset by peer: mod_fcgid: error reading data from FastCGI server

In my main apache error log I was getting: PHP Fatal error: Directive 'safe_mode' is no longer available in PHP in Unknown on line 0

In my case, I simply set safe_mode = Off in my php.ini and restarted apache.

stackoverflow.com/questions/18683177/where-to-start-with-deprecated-directive-safe-mode-on-line-0-in-apache-error

Add class to an element in Angular 4

Here is a plunker showing how you can use it with the ngClass directive.

I'm demonstrating with divs instead of imgs though.

Template:

<ul>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 1}" (click)="setSelected(1)"> </div></li>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 2}" (click)="setSelected(2)"> </div></li>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 3}" (click)="setSelected(3)"> </div></li>
</ul>

TS:

export class App {
  selectedIndex = -1;

  setSelected(id: number) {
    this.selectedIndex = id;
  }
}

mailto link with HTML body

It is worth pointing out that on Safari on the iPhone, at least, inserting basic HTML tags such as <b>, <i>, and <img> (which ideally you shouldn't use in other circumstances anymore anyway, preferring CSS) into the body parameter in the mailto: does appear to work - they are honored within the email client. I haven't done exhaustive testing to see if this is supported by other mobile or desktop browser/email client combos. It's also dubious whether this is really standards-compliant. Might be useful if you are building for that platform, though.

As other responses have noted, you should also use encodeURIComponent on the entire body before embedding it in the mailto: link.

Create an array of integers property in Objective-C

You can put this in your .h file for your class and define it as property, in XCode 7:

@property int  (*stuffILike) [10];

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I encountered this problem with Java 1.6. Running under Java 1.7 fixed my particular rendition of the problem. I think the underlying cause was that the server I was connecting to must have required stronger encryption than was available under 1.6.

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

This issue arises when you don't give sufficient permissions to .git folder. To solve this problem-

  1. First navigate to your working directory.
  2. Enter this command-

    sudo chmod a+rw .git -R

Hope it helps..!!

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

What is the largest TCP/IP network port number allowable for IPv4?

It depends on which range you're talking about, but the dynamic range goes up to 65535 or 2^16-1 (16 bits).

http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

Android Text over image

That is how I did it and it worked exactly as you asked for inside a RelativeLayout:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativelayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/myImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/myImageSouce" />

    <TextView
        android:id="@+id/myImageViewText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/myImageView"
        android:layout_alignTop="@id/myImageView"
        android:layout_alignRight="@id/myImageView"
        android:layout_alignBottom="@id/myImageView"
        android:layout_margin="1dp"
        android:gravity="center"
        android:text="Hello"
        android:textColor="#000000" />

</RelativeLayout>

Inline Form nested within Horizontal Form in Bootstrap 3

This Bootply example seems like a much better option. Only thing is that the labels are a little too high so I added padding-top:5px to center them with my inputs.

<div class="container">
<h2>Bootstrap Mixed Form <p class="lead">with horizontal and inline fields</p></h2>
<form role="form" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-1" for="inputEmail1">Email</label>
        <div class="col-sm-5"><input type="email" class="form-control" id="inputEmail1" placeholder="Email"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-1" for="inputPassword1">Password</label>
        <div class="col-sm-5"><input type="password" class="form-control" id="inputPassword1" placeholder="Password"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-12" for="TextArea">Textarea</label>
        <div class="col-sm-6"><textarea class="form-control" id="TextArea"></textarea></div>
    </div>
    <div class="form-group">
        <div class="col-sm-3"><label>First name</label><input type="text" class="form-control" placeholder="First"></div>
        <div class="col-sm-3"><label>Last name</label><input type="text" class="form-control" placeholder="Last"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-12">Phone number</label>
        <div class="col-sm-1"><input type="text" class="form-control" placeholder="000"><div class="help">area</div></div>
        <div class="col-sm-1"><input type="text" class="form-control" placeholder="000"><div class="help">local</div></div>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="1111"><div class="help">number</div></div>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="123"><div class="help">ext</div></div>
    </div>
    <div class="form-group">
        <label class="col-sm-1">Options</label>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="Option 1"></div>
        <div class="col-sm-3"><input type="text" class="form-control" placeholder="Option 2"></div>
    </div>
    <div class="form-group">
        <div class="col-sm-6">
            <button type="submit" class="btn btn-info pull-right">Submit</button>
        </div>
    </div>
</form>
<hr>
</div>

How to generate a QR Code for an Android application?

Here is my simple and working function to generate a Bitmap! I Use ZXing1.3.jar only! I've also set Correction Level to High!

PS: x and y are reversed, it's normal, because bitMatrix reverse x and y. This code works perfectly with a square image.

public static Bitmap generateQrCode(String myCodeText) throws WriterException {
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage

    QRCodeWriter qrCodeWriter = new QRCodeWriter();

    int size = 256;

    ByteMatrix bitMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
    int width = bitMatrix.width();
    Bitmap bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < width; y++) {
            bmp.setPixel(y, x, bitMatrix.get(x, y)==0 ? Color.BLACK : Color.WHITE);
        }
    }
    return bmp;
}

EDIT

It's faster to use bitmap.setPixels(...) with a pixel int array instead of bitmap.setPixel one by one:

        BitMatrix bitMatrix = writer.encode(inputValue, BarcodeFormat.QR_CODE, size, size);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
            }
        }

        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

Pandas - Get first row value of a given column

Another way to do this:

first_value = df['Btime'].values[0]

This way seems to be faster than using .iloc:

In [1]: %timeit -n 1000 df['Btime'].values[20]
5.82 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [2]: %timeit -n 1000 df['Btime'].iloc[20]
29.2 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

HTML table headers always visible at top of window when viewing a large table

Check out jQuery.floatThead (demos available) which is very cool, can work with DataTables too, and can even work inside an overflow: auto container.

Send data from a textbox into Flask?

Unless you want to do something more complicated, feeding data from a HTML form into Flask is pretty easy.

  • Create a view that accepts a POST request (my_form_post).
  • Access the form elements in the dictionary request.form.

templates/my-form.html:

<form method="POST">
    <input name="text">
    <input type="submit">
</form>
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('my-form.html')

@app.route('/', methods=['POST'])
def my_form_post():
    text = request.form['text']
    processed_text = text.upper()
    return processed_text

This is the Flask documentation about accessing request data.

If you need more complicated forms that need validation then you can take a look at WTForms and how to integrate them with Flask.

Note: unless you have any other restrictions, you don't really need JavaScript at all to send your data (although you can use it).

How to include route handlers in multiple files in Express?

I know this is an old question, but I was trying to figure out something like for myself and this is the place I ended up on, so I wanted to put my solution to a similar problem in case someone else has the same issues I'm having. There's a nice node module out there called consign that does a lot of the file system stuff that is seen here for you (ie - no readdirSync stuff). For example:

I have a restful API application I'm trying to build and I want to put all of the requests that go to '/api/*' to be authenticated and I want to store all of my routes that go in api into their own directory (let's just call it 'api'). In the main part of the app:

app.use('/api', [authenticationMiddlewareFunction], require('./routes/api'));

Inside of the routes directory, I have a directory called "api" and a file called api.js. In api.js, I simply have:

var express = require('express');
var router = express.Router();
var consign = require('consign');

// get all routes inside the api directory and attach them to the api router
// all of these routes should be behind authorization
consign({cwd: 'routes'})
  .include('api')
  .into(router);

module.exports = router;

Everything worked as expected. Hope this helps someone.

How can I de-install a Perl module installed via `cpan`?

Update 2013: This code is obsolescent. Upvote bsb's late-coming answer instead.


I don't need to uninstall modules often, but the .packlist file based approach has never failed me so far.

use 5.010;
use ExtUtils::Installed qw();
use ExtUtils::Packlist qw();

die "Usage: $0 Module::Name Module::Name\n" unless @ARGV;

for my $mod (@ARGV) {
    my $inst = ExtUtils::Installed->new;

    foreach my $item (sort($inst->files($mod))) {
        say "removing $item";
        unlink $item or warn "could not remove $item: $!\n";
    }

    my $packfile = $inst->packlist($mod)->packlist_file;
    print "removing $packfile\n";
    unlink $packfile or warn "could not remove $packfile: $!\n";
}

Sort a Map<Key, Value> by values

The answer voted for the most does not work when you have 2 items that equals. the TreeMap leaves equal values out.

the exmaple: unsorted map

key/value: D/67.3
key/value: A/99.5
key/value: B/67.4
key/value: C/67.5
key/value: E/99.5

results

key/value: A/99.5
key/value: C/67.5
key/value: B/67.4
key/value: D/67.3

So leaves out E!!

For me it worked fine to adjust the comparator, if it equals do not return 0 but -1.

in the example:

class ValueComparator implements Comparator {

Map base; public ValueComparator(Map base) { this.base = base; }

public int compare(Object a, Object b) {

if((Double)base.get(a) < (Double)base.get(b)) {
  return 1;
} else if((Double)base.get(a) == (Double)base.get(b)) {
  return -1;
} else {
  return -1;
}

} }

now it returns:

unsorted map:

key/value: D/67.3
key/value: A/99.5
key/value: B/67.4
key/value: C/67.5
key/value: E/99.5

results:

key/value: A/99.5
key/value: E/99.5
key/value: C/67.5
key/value: B/67.4
key/value: D/67.3

as a response to Aliens (2011 nov. 22): I Am using this solution for a map of Integer Id's and names, but the idea is the same, so might be the code above is not correct (I will write it in a test and give you the correct code), this is the code for a Map sorting, based on the solution above:

package nl.iamit.util;

import java.util.Comparator;
import java.util.Map;

public class Comparators {


    public static class MapIntegerStringComparator implements Comparator {

        Map<Integer, String> base;

        public MapIntegerStringComparator(Map<Integer, String> base) {
            this.base = base;
        }

        public int compare(Object a, Object b) {

            int compare = ((String) base.get(a))
                    .compareTo((String) base.get(b));
            if (compare == 0) {
                return -1;
            }
            return compare;
        }
    }


}

and this is the test class (I just tested it, and this works for the Integer, String Map:

package test.nl.iamit.util;

import java.util.HashMap;
import java.util.TreeMap;
import nl.iamit.util.Comparators;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;

public class TestComparators {


    @Test
    public void testMapIntegerStringComparator(){
        HashMap<Integer, String> unSoretedMap = new HashMap<Integer, String>();
        Comparators.MapIntegerStringComparator bvc = new Comparators.MapIntegerStringComparator(
                unSoretedMap);
        TreeMap<Integer, String> sorted_map = new TreeMap<Integer, String>(bvc);
        //the testdata:
        unSoretedMap.put(new Integer(1), "E");
        unSoretedMap.put(new Integer(2), "A");
        unSoretedMap.put(new Integer(3), "E");
        unSoretedMap.put(new Integer(4), "B");
        unSoretedMap.put(new Integer(5), "F");

        sorted_map.putAll(unSoretedMap);

        Object[] targetKeys={new Integer(2),new Integer(4),new Integer(3),new Integer(1),new Integer(5) };
        Object[] currecntKeys=sorted_map.keySet().toArray();

        assertArrayEquals(targetKeys,currecntKeys);
    }
}

here is the code for the Comparator of a Map:

public static class MapStringDoubleComparator implements Comparator {

    Map<String, Double> base;

    public MapStringDoubleComparator(Map<String, Double> base) {
        this.base = base;
    }

    //note if you want decending in stead of ascending, turn around 1 and -1
    public int compare(Object a, Object b) {
        if ((Double) base.get(a) == (Double) base.get(b)) {
            return 0;
        } else if((Double) base.get(a) < (Double) base.get(b)) {
            return -1;
        }else{
            return 1;
        }
    }
}

and this is the testcase for this:

@Test
public void testMapStringDoubleComparator(){
    HashMap<String, Double> unSoretedMap = new HashMap<String, Double>();
    Comparators.MapStringDoubleComparator bvc = new Comparators.MapStringDoubleComparator(
            unSoretedMap);
    TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);
    //the testdata:
    unSoretedMap.put("D",new Double(67.3));
    unSoretedMap.put("A",new Double(99.5));
    unSoretedMap.put("B",new Double(67.4));
    unSoretedMap.put("C",new Double(67.5));
    unSoretedMap.put("E",new Double(99.5));

    sorted_map.putAll(unSoretedMap);

    Object[] targetKeys={"D","B","C","E","A"};
    Object[] currecntKeys=sorted_map.keySet().toArray();

    assertArrayEquals(targetKeys,currecntKeys);
}

of cource you can make this a lot more generic, but I just needed it for 1 case (the Map)

Sending command line arguments to npm script

Note: This approach modifies your package.json on the fly, use it if you have no alternative.

I had to pass command line arguments to my scripts which were something like:

"scripts": {
    "start": "npm run build && npm run watch",
    "watch": "concurrently  \"npm run watch-ts\" \"npm run watch-node\"",
    ...
}

So, this means I start my app with npm run start.

Now if I want to pass some arguments, I would start with maybe:

npm run start -- --config=someConfig

What this does is: npm run build && npm run watch -- --config=someConfig. Problem with this is, it always appends the arguments to the end of the script. This means all the chained scripts don't get these arguments(Args maybe or may not be required by all, but that's a different story.). Further when the linked scripts are called then those scripts won't get the passed arguments. i.e. The watch script won't get the passed arguments.

The production usage of my app is as an .exe, so passing the arguments in the exe works fine but if want to do this during development, it gets problamatic.

I couldn't find any proper way to achieve this, so this is what I have tried.

I have created a javascript file: start-script.js at the parent level of the application, I have a "default.package.json" and instead of maintaining "package.json", I maintain "default.package.json". The purpose of start-script.json is to read default.package.json, extract the scripts and look for npm run scriptname then append the passed arguments to these scripts. After this, it will create a new package.json and copy the data from default.package.json with modified scripts and then call npm run start.

const fs = require('fs');
const { spawn } = require('child_process');

// open default.package.json
const defaultPackage = fs.readFileSync('./default.package.json');
try {
    const packageOb = JSON.parse(defaultPackage);
    // loop over the scripts present in this object, edit them with flags
    if ('scripts' in packageOb && process.argv.length > 2) {

        const passedFlags = ` -- ${process.argv.slice(2).join(' ')}`;
        // assuming the script names have words, : or -, modify the regex if required.
        const regexPattern = /(npm run [\w:-]*)/g;
        const scriptsWithFlags = Object.entries(packageOb.scripts).reduce((acc, [key, value]) => {
            const patternMatches = value.match(regexPattern);
            // loop over all the matched strings and attach the desired flags.
            if (patternMatches) {
                for (let eachMatchedPattern of patternMatches) {
                    const startIndex = value.indexOf(eachMatchedPattern);
                    const endIndex = startIndex + eachMatchedPattern.length;
                    // save the string which doen't fall in this matched pattern range.
                    value = value.slice(0, startIndex) + eachMatchedPattern + passedFlags + value.slice(endIndex);
                }
            }
            acc[key] = value;
            return acc;
        }, {});
        packageOb.scripts = scriptsWithFlags;
    }

    const modifiedJSON = JSON.stringify(packageOb, null, 4);
    fs.writeFileSync('./package.json', modifiedJSON);

    // now run your npm start script
    let cmd = 'npm';
    // check if this works in your OS
    if (process.platform === 'win32') {
        cmd = 'npm.cmd';    // https://github.com/nodejs/node/issues/3675
    }
    spawn(cmd, ['run', 'start'], { stdio: 'inherit' });

} catch(e) {
    console.log('Error while parsing default.package.json', e);
}

Now, instead of doing npm run start, I do node start-script.js --c=somethis --r=somethingElse

The initial run looks fine, but haven't tested thoroughly. Use it, if you like for you app development.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I don't think that solution would work anyways because you will see some error message in your error log file.

The solution was a lot easier than what I thought.

simply, open the following path to your php5-fpm

sudo nano /etc/php5/fpm/pool.d/www.conf

or if you're the admin 'root'

nano /etc/php5/fpm/pool.d/www.conf

Then find this line and uncomment it:

listen.allowed_clients = 127.0.0.1

This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks

like this: fastcgi_pass 127.0.0.1:9000;

after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm

Php5-fpm

sudo service php5-fpm restart

or

sudo service php5-fpm reload

Nginx

sudo service nginx restart

or

sudo service nginx reload

From the comments:

Also comment

;listen = /var/run/php5-fpm.sock 

and add

listen = 9000

Parsing JSON giving "unexpected token o" error

cur_ques_details is already a JS object, you don't need to parse it

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

Try installing this, it's a known workaround for enabling the C++ compiler for Python 2.7.

In my experience, when pip does not find vcvarsall.bat compiler, all I do is opening a Visual Studio console as it set the path variables to call vcvarsall.bat directly and then I run pip on this command line.

JavaScript blob filename without link

window.location.assign did not work for me. it downloads fine but downloads without an extension for a CSV file on Windows platform. The following worked for me.

    var blob = new Blob([csvString], { type: 'text/csv' });
    //window.location.assign(window.URL.createObjectURL(blob));
    var link = window.document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    // Construct filename dynamically and set to link.download
    link.download = link.href.split('/').pop() + '.' + extension; 
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

excel - if cell is not blank, then do IF statement

Your formula is wrong. You probably meant something like:

=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Another equivalent:

=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Or even shorter:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))

OR EVEN SHORTER:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))

Convert string into integer in bash script - "Leading Zero" number error

The leading 0 is leading to bash trying to interpret your number as an octal number, but octal numbers are 0-7, and 8 is thus an invalid token.

If I were you, I would add some logic to remove a leading 0, add one, and re-add the leading 0 if the result is < 10.

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

How to get local server host and port in Spring Boot?

An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequest in the signature of one of the controller's methods. Once you have the HttpServletRequest instance is straightforward to get the baseUrl with this: request.getRequestURL().toString()

Have a look at this code:

@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO, 
    HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}

Apply multiple functions to multiple groupby columns

As an alternative (mostly on aesthetics) to Ted Petrou's answer, I found I preferred a slightly more compact listing. Please don't consider accepting it, it's just a much-more-detailed comment on Ted's answer, plus code/data. Python/pandas is not my first/best, but I found this to read well:

df.groupby('group') \
  .apply(lambda x: pd.Series({
      'a_sum'       : x['a'].sum(),
      'a_max'       : x['a'].max(),
      'b_mean'      : x['b'].mean(),
      'c_d_prodsum' : (x['c'] * x['d']).sum()
  })
)

          a_sum     a_max    b_mean  c_d_prodsum
group                                           
0      0.530559  0.374540  0.553354     0.488525
1      1.433558  0.832443  0.460206     0.053313

I find it more reminiscent of dplyr pipes and data.table chained commands. Not to say they're better, just more familiar to me. (I certainly recognize the power and, for many, the preference of using more formalized def functions for these types of operations. This is just an alternative, not necessarily better.)


I generated data in the same manner as Ted, I'll add a seed for reproducibility.

import numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df

          a         b         c         d  group
0  0.374540  0.950714  0.731994  0.598658      0
1  0.156019  0.155995  0.058084  0.866176      0
2  0.601115  0.708073  0.020584  0.969910      1
3  0.832443  0.212339  0.181825  0.183405      1

Git: Find the most recent common ancestor of two branches

git diff master...feature

shows all the new commits of your current (possibly multi-commit) feature branch.

man git-diff documents that:

git diff A...B

is the same as:

git diff $(git merge-base A B) B

but the ... is easier to type and remember.

As mentioned by Dave, the special case of HEAD can be omitted. So:

git diff master...HEAD

is the same as:

git diff master...

which is enough if the current branch is feature.

Finally, remember that order matters! Doing git diff feature...master will show changes that are on master not on feature.

I wish more git commands would support that syntax, but I don't think they do. And some even have different semantics for ...: What are the differences between double-dot ".." and triple-dot "..." in Git commit ranges?

How to bind a List<string> to a DataGridView control?

Try this :

//i have a 
List<string> g_list = new List<string>();

//i put manually the values... (for this example)
g_list.Add("aaa");
g_list.Add("bbb");
g_list.Add("ccc");

//for each string add a row in dataGridView and put the l_str value...
foreach (string l_str in g_list)
{
    dataGridView1.Rows.Add(l_str);
}

How to echo out the values of this array?

Here is a simple routine for an array of primitive elements:

for ($i = 0; $i < count($mySimpleArray); $i++)
{
   echo $mySimpleArray[$i] . "\n";
}

How to stop tracking and ignore changes to a file in Git?

There are 3 options, you probably want #3

1. This will keep the local file for you, but will delete it for anyone else when they pull.

git rm --cached <file-name> or git rm -r --cached <folder-name>

2. This is for optimization, like a folder with a large number of files, e.g. SDKs that probably won't ever change. It tells git to stop checking that huge folder every time for changes, locally, since it won't have any. The assume-unchanged index will be reset and file(s) overwritten if there are upstream changes to the file/folder (when you pull).

git update-index --assume-unchanged <path-name>

3. This is to tell git you want your own independent version of the file or folder. For instance, you don't want to overwrite (or delete) production/staging config files.

git update-index --skip-worktree <path-name>

It's important to know that git update-index will not propagate with git, and each user will have to run it independently.

sendUserActionEvent() is null

Even i face similar problem after I did some modification in code related to Cursor.

public boolean onContextItemSelected(MenuItem item) 
{
        AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
        Cursor c = (Cursor)adapter.getItem(info.position);
        long id = c.getLong(...);
        String tempCity = c.getString(...);
            //c.close();
...
}

After i commented out //c.close(); It is working fine. Try out at your end and update Initial setup is as... I have a list view in Fragment, and trying to delete and item from list via contextMenu.

<!--[if !IE]> not working

You need to put a space for the <!-- [if !IE] --> My full css block goes as follows, since IE8 is terrible with media queries

<!-- IE 8 or below -->   
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css"  href="/Resources/css/master1300.css" />        
<![endif]-->
<!-- IE 9 or above -->
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" media="(max-width: 100000px) and (min-width:481px)"
    href="/Resources/css/master1300.css" />
<link rel="stylesheet" type="text/css" media="(max-width: 480px)"
    href="/Resources/css/master480.css" />        
<![endif]-->
<!-- Not IE -->
<!-- [if !IE] -->
<link rel="stylesheet" type="text/css" media="(max-width: 100000px) and (min-width:481px)"
    href="/Resources/css/master1300.css" />
<link rel="stylesheet" type="text/css" media="(max-width: 480px)"
    href="/Resources/css/master480.css" />
<!-- [endif] -->

angularjs ng-style: background-image isn't working

For those who are struggling to get this working with IE11

HTML

<div ng-style="getBackgroundStyle(imagepath)"></div>

JS

$scope.getBackgroundStyle = function(imagepath){
    return {
        'background-image':'url(' + imagepath + ')'
    }
}

string encoding and decoding?

Aside from getting decode and encode backwards, I think part of the answer here is actually don't use the ascii encoding. It's probably not what you want.

To begin with, think of str like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.

Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.

The problem is that in practice, you run into both. Some libraries give you a str, and some expect a str. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.

Enter codecs: it's the translation library between these two data types. You use encode to generate a sequence of bytes (str) from a text string (unicode), and you use decode to get a text string (unicode) from a sequence of bytes (str).

For example:

>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"

What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode version of this, given that this sequence of bytes is in 'utf-8'." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.

Let's go the other way around:

>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"

I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8' encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.

We can work with other encodings, too, of course:

>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True

>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'

('\xa7' is the section character, in both Unicode and Latin-1.)

So for your question, you first need to figure out what encoding your str is in.

  • Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode.

    s = [get from external source]
    u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
    
  • Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str. UTF-8 is a good choice for plain text documents; most things can read it.

    u = u'My string'
    s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
    [Write s out somewhere]
    
  • Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8' is probably the best choice for that:

    u = u'My string'
    s = codecs.encode(u, 'utf-8')
    newu = codecs.decode(s, 'utf-8')
    

In modern programming, you probably never want to use the 'ascii' encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.

Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str was replaced with bytes, and unicode was replaced with str.

Converting HTML to XML

Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.

This link is helpful: How to read HTML as XML?

More here - difference between HTML and XML

how to check if a form is valid programmatically using jQuery Validation Plugin

@mikemaccana answer is useful.

And I also used https://github.com/ryanseddon/H5F. Found on http://microjs.com. It's some kind of polyfill and you can use it as follows (jQuery is used in example):

if ( $('form')[0].checkValidity() ) {
    // the form is valid
}

How do you remove the title text from the Android ActionBar?

ActionBar actionBar = getActionBar();
actionBar.setTitle("");

Check if two unordered lists are equal

One liner answer to the above question is :-

let the two lists be list1 and list2, and your requirement is to ensure whether two lists have the same elements, then as per me, following will be the best approach :-

if ((len(list1) == len(list2)) and
   (all(i in list2 for i in list1))):
    print 'True'
else:
    print 'False'

The above piece of code will work per your need i.e. whether all the elements of list1 are in list2 and vice-verse.

But if you want to just check whether all elements of list1 are present in list2 or not, then you need to use the below code piece only :-

if all(i in list2 for i in list1):
    print 'True'
else:
    print 'False'

The difference is, the later will print True, if list2 contains some extra elements along with all the elements of list1. In simple words, it will ensure that all the elements of list1 should be present in list2, regardless of whether list2 has some extra elements or not.

$('body').on('click', '.anything', function(){})

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

How to set a Postgresql default value datestamp like 'YYYYMM'?

Just in case Milen A. Radev doesn't get around to posting his solution, this is it:

CREATE TABLE foo (
    key     int PRIMARY KEY,
    foo     text NOT NULL DEFAULT TO_CHAR(CURRENT_TIMESTAMP,'YYYYMM')
);

Runtime vs. Compile time

As an add-on to the other answers, here's how I'd explain it to a layman:

Your source code is like the blueprint of a ship. It defines how the ship should be made.

If you hand off your blueprint to the shipyard, and they find a defect while building the ship, they'll stop building and report it to you immediately, before the ship has ever left the drydock or touched water. This is a compile-time error. The ship was never even actually floating or using its engines. The error was found because it prevented the ship even being made.

When your code compiles, it's like the ship being completed. Built and ready to go. When you execute your code, that's like launching the ship on a voyage. The passengers are boarded, the engines are running and the hull is on the water, so this is runtime. If your ship has a fatal flaw that sinks it on its maiden voyage (or maybe some voyage after for extra headaches) then it suffered a runtime error.

How to "flatten" a multi-dimensional array to simple one in PHP?

Use array_walk_recursive

<?php

$aNonFlat = array(
    1,
    2,
    array(
        3,
        4,
        5,
        array(
            6,
            7
        ),
        8,
        9,
    ),
    10,
    11
);

$objTmp = (object) array('aFlat' => array());

array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);

var_dump($objTmp->aFlat);

/*
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
  [10]=>
  int(11)
}
*/

?>

Tested with PHP 5.5.9-1ubuntu4.24 (cli) (built: Mar 16 2018 12:32:06)

How can I ignore a property when serializing using the DataContractSerializer?

Additionally, DataContractSerializer will serialize items marked as [Serializable] and will also serialize unmarked types in .NET 3.5 SP1 and later, to allow support for serializing anonymous types.

So, it depends on how you've decorated your class as to how to keep a member from serializing:

  • If you used [DataContract], then remove the [DataMember] for the property.
  • If you used [Serializable], then add [NonSerialized] in front of the field for the property.
  • If you haven't decorated your class, then you should add [IgnoreDataMember] to the property.

Get program path in VB.NET?

You can also use:

Dim strPath As String = AppDomain.CurrentDomain.BaseDirectory

Create mysql table directly from CSV file using the CSV Storage engine?

This is not possible. To create a table you need a table schema. What you have is a data file. A schema cannot be created with it.

What you can do is check if your file has a header row, and, in that case, you can manually create a table using that header row.

However, there is a way to generate a create table statement using a batch file as described by John Swapceinski in the comment section of the MySQL manual.

Posted by John Swapceinski on September 5 2011 5:33am.
Create a table using the .csv file's header:

#!/bin/sh
# pass in the file name as an argument: ./mktable filename.csv
echo "create table $1 ( "
head -1 $1 | sed -e 's/,/ varchar(255),\n/g'
echo " varchar(255) );"

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

Iterating Over Dictionary Key Values Corresponding to List in Python

You have several options for iterating over a dictionary.

If you iterate over the dictionary itself (for team in league), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league) itself, or league.keys():

for team in league.keys():
    runs_scored, runs_allowed = map(float, league[team])

You can also iterate over both the keys and the values at once by iterating over league.items():

for team, runs in league.items():
    runs_scored, runs_allowed = map(float, runs)

You can even perform your tuple unpacking while iterating:

for team, (runs_scored, runs_allowed) in league.items():
    runs_scored = float(runs_scored)
    runs_allowed = float(runs_allowed)

How to append new data onto a new line

I had the same issue. And I was able to solve it by using a formatter.

file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()

I hope this helps.

addEventListener, "change" and option selection

You need a click listener which calls addActivityItem if less than 2 options exist:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)
    {
        addActivityItem();
    }
});

activities.addEventListener("change", function() {
    if(activities.value == "addNew")
    {
        addActivityItem();
    }
});

function addActivityItem() {
    // ... Code to add item here
}

A live demo is here on JSfiddle.

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Referencing assemblies that are not used during build is not the correct practice. You should augment your build file so it will copy the additional files. Either by using a post build event or by updating the property group.

Some examples can be found in other post

Detecting Enter keypress on VB.NET

Use KeyDown Event instead of KeyPress

If e.KeyCode = Keys.Enter Then
   MsgBox ("You pressed enter")
End if

Note: Make sure you don't have ACCEPT BUTTON set on your form. AcceptButton set it to 'none'

How to handle the `onKeyPress` event in ReactJS?

Keypress event is deprecated, You should use Keydown event instead.

https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

handleKeyDown(event) {
    if(event.keyCode === 13) { 
        console.log('Enter key pressed')
  }
}

render() { 
    return <input type="text" onKeyDown={this.handleKeyDown} /> 
}

How to detect Adblock on my website?

this worked for me the document has to be ready before you look for adblock hope this help someone!

jQuery(document).ready(function() {

var adBlockEnabled = false;
var testAd = document.createElement('div');
testAd.innerHTML = '&nbsp;';
testAd.className = 'adsbox';
document.body.appendChild(testAd);
window.setTimeout(function() {
  if (testAd.offsetHeight === 0) {
    adBlockEnabled = true;
  }
  testAd.remove();
  console.log('AdBlock Enabled? ', adBlockEnabled)
}, 100);


});

How to find all positions of the maximum value in a list?

Here is the max value and the indexes it appears at:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> for i, x in enumerate(a):
...     d[x].append(i)
... 
>>> k = max(d.keys())
>>> print k, d[k]
55 [9, 12]

Later: for the satisfaction of @SilentGhost

>>> from itertools import takewhile
>>> import heapq
>>> 
>>> def popper(heap):
...     while heap:
...         yield heapq.heappop(heap)
... 
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> h = [(-x, i) for i, x in enumerate(a)]
>>> heapq.heapify(h)
>>> 
>>> largest = heapq.heappop(h)
>>> indexes = [largest[1]] + [x[1] for x in takewhile(lambda large: large[0] == largest[0], popper(h))]
>>> print -largest[0], indexes
55 [9, 12]

Android ListView Divider

set android:dividerHeight="1dp"

<ListView
            android:id="@+id/myphnview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@drawable/dividerheight"
            android:background="#E9EAEC"
            android:clickable="true"
    android:divider="@color/white"
                android:dividerHeight="1dp"
                android:headerDividersEnabled="true" >
    </ListView>

Insert line break in wrapped cell via code

Just do Ctrl + Enter inside the text box

set gvim font in .vimrc file

I use the following (Uses Consolas size 11 on Windows, Menlo Regular size 14 on Mac OS X and Inconsolata size 12 everywhere else):

if has("gui_running")
  if has("gui_gtk2")
    set guifont=Inconsolata\ 12
  elseif has("gui_macvim")
    set guifont=Menlo\ Regular:h14
  elseif has("gui_win32")
    set guifont=Consolas:h11:cANSI
  endif
endif

Edit: And while you're at it, you could take a look at Coding Horror's Programming Fonts blog post.

Edit²: Added MacVim.

Setting a checkbox as checked with Vue.js

Let's say you want to pass a prop to a child component and that prop is a boolean that will determine if the checkbox is checked or not, then you have to pass the boolean value to the v-bind:checked="booleanValue" or the shorter way :checked="booleanValue", for example:

<input
    id="checkbox"
    type="checkbox"
    :value="checkboxVal"
    :checked="booleanValue"
    v-on:input="checkboxVal = $event.target.value"
/>

That should work and the checkbox will display the checkbox with it's current boolean state (if true checked, if not unchecked).

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

Escape single quote character for use in an SQLite query

In bash scripts, I found that escaping double quotes around the value was necessary for values that could be null or contained characters that require escaping (like hyphens).

In this example, columnA's value could be null or contain hyphens.:

sqlite3 $db_name "insert into foo values (\"$columnA\", $columnB)";

char initial value in Java

Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.

If you want the char equivalent of 0, it's just Unicode 0, which can be written as

char c = '\0';

That's also the default value for an instance (or static) variable of type char.

Mongoose query where value is not null

total count the documents where the value of the field is not equal to the specified value.

async function getRegisterUser() {
    return Login.count({"role": { $ne: 'Super Admin' }}, (err, totResUser) => {
        if (err) {
            return err;
        }
        return totResUser;
    })
}

Clear form after submission with jQuery

Better way to reset your form with jQuery is Simply trigger a reset event on your form.

$("#btn1").click(function () {
        $("form").trigger("reset");
    });

What is the use of hashCode in Java?

From the Javadoc:

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)

Dynamic creation of table with DOM

You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:

var table = document.createElement('table');
for (var i = 1; i < 4; i++){
    var tr = document.createElement('tr');   

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    var text1 = document.createTextNode('Text1');
    var text2 = document.createTextNode('Text2');

    td1.appendChild(text1);
    td2.appendChild(text2);
    tr.appendChild(td1);
    tr.appendChild(td2);

    table.appendChild(tr);
}
document.body.appendChild(table);

How to get all selected values of a multiple select box?

Same as the earlier answer but using underscore.js.

function getSelectValues(select) {
    return _.map(_.filter(select.options, function(opt) { 
        return opt.selected; }), function(opt) { 
            return opt.value || opt.text; });
}

Clone private git repo with dockerfile

You often do not want to perform a git clone of a private repo from within the docker build. Doing the clone there involves placing the private ssh credentials inside the image where they can be later extracted by anyone with access to your image.

Instead, the common practice is to clone the git repo from outside of docker in your CI tool of choice, and simply COPY the files into the image. This has a second benefit: docker caching. Docker caching looks at the command being run, environment variables it includes, input files, etc, and if they are identical to a previous build from the same parent step, it reuses that previous cache. With a git clone command, the command itself is identical, so docker will reuse the cache even if the external git repo is changed. However, a COPY command will look at the files in the build context and can see if they are identical or have been updated, and use the cache only when it's appropriate.


If you are going to add credentials into your build, consider doing so with a multi-stage build, and only placing those credentials in an early stage that is never tagged and pushed outside of your build host. The result looks like:

FROM ubuntu as clone

# Update aptitude with new repo
RUN apt-get update \
 && apt-get install -y git
# Make ssh dir
# Create known_hosts
# Add bitbuckets key
RUN mkdir /root/.ssh/ \
 && touch /root/.ssh/known_hosts \
 && ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Copy over private key, and set permissions
# Warning! Anyone who gets their hands on this image will be able
# to retrieve this private key file from the corresponding image layer
COPY id_rsa /root/.ssh/id_rsa

# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git

FROM ubuntu as release
LABEL maintainer="Luke Crooks <[email protected]>"

COPY --from=clone /repo /repo
...

More recently, BuildKit has been testing some experimental features that allow you to pass an ssh key in as a mount that never gets written to the image:

# syntax=docker/dockerfile:experimental
FROM ubuntu as clone
LABEL maintainer="Luke Crooks <[email protected]>"

# Update aptitude with new repo
RUN apt-get update \
 && apt-get install -y git

# Make ssh dir
# Create known_hosts
# Add bitbuckets key
RUN mkdir /root/.ssh/ \
 && touch /root/.ssh/known_hosts \
 && ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Clone the conf files into the docker container
RUN --mount=type=secret,id=ssh_id,target=/root/.ssh/id_rsa \
    git clone [email protected]:User/repo.git

And you can build that with:

$ DOCKER_BUILDKIT=1 docker build -t your_image_name \
  --secret id=ssh_id,src=$(pwd)/id_rsa .

Note that this still requires your ssh key to not be password protected, but you can at least run the build in a single stage, removing a COPY command, and avoiding the ssh credential from ever being part of an image.


BuildKit also added a feature just for ssh which allows you to still have your password protected ssh keys, the result looks like:

# syntax=docker/dockerfile:experimental
FROM ubuntu as clone
LABEL maintainer="Luke Crooks <[email protected]>"

# Update aptitude with new repo
RUN apt-get update \
 && apt-get install -y git

# Make ssh dir
# Create known_hosts
# Add bitbuckets key
RUN mkdir /root/.ssh/ \
 && touch /root/.ssh/known_hosts \
 && ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Clone the conf files into the docker container
RUN --mount=type=ssh \
    git clone [email protected]:User/repo.git

And you can build that with:

$ eval $(ssh-agent)
$ ssh-add ~/.ssh/id_rsa
(Input your passphrase here)
$ DOCKER_BUILDKIT=1 docker build -t your_image_name \
  --ssh default=$SSH_AUTH_SOCK .

Again, this is injected into the build without ever being written to an image layer, removing the risk that the credential could accidentally leak out.


To force docker to run the git clone even when the lines before have been cached, you can inject a build ARG that changes with each build to break the cache. That looks like:

# inject a datestamp arg which is treated as an environment variable and
# will break the cache for the next RUN command
ARG DATE_STAMP
# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git

Then you inject that changing arg in the docker build command:

date_stamp=$(date +%Y%m%d-%H%M%S)
docker build --build-arg DATE_STAMP=$date_stamp .

MongoDB Show all contents from all collections

This will do:

db.getCollectionNames().forEach(c => {
    db[c].find().forEach(d => {
        print(c); 
        printjson(d)
    })
})

How to recover a dropped stash in Git?

My favorite is this one-liner:

git log --oneline  $( git fsck --no-reflogs | awk '/dangling commit/ {print $3}' )

This is basically the same idea as this answer but much shorter. Of course, you can still add --graph to get a tree-like display.

When you have found the commit in the list, apply with

git stash apply THE_COMMIT_HASH_FOUND

For me, using --no-reflogs did reveal the lost stash entry, but --unreachable (as found in many other answers) did not.

Run it on git bash when you are under Windows.

Credits: The details of the above commands are taken from https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf

Is there a way to detect if an image is blurry?

Matlab code of two methods that have been published in highly regarded journals (IEEE Transactions on Image Processing) are available here: https://ivulab.asu.edu/software

check the CPBDM and JNBM algorithms. If you check the code it's not very hard to be ported and incidentally it is based on the Marzialiano's method as basic feature.

Determining whether an object is a member of a collection in VBA

I did it like this, a variation on Vadims code but to me a bit more readable:

' Returns TRUE if item is already contained in collection, otherwise FALSE

Public Function Contains(col As Collection, item As String) As Boolean

    Dim i As Integer

    For i = 1 To col.Count

    If col.item(i) = item Then
        Contains = True
        Exit Function
    End If

    Next i

    Contains = False

End Function

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

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

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

How to convert an image to base64 encoding?

You can also do this via curl, just you need a path to an image file and pass it to the function given below..

public static function getImageDataFromUrl($url)
{
    $urlParts = pathinfo($url);
    $extension = $urlParts['extension'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $base64 = 'data:image/' . $extension . ';base64,' . base64_encode($response);
    return $base64;

}

Pass multiple values with onClick in HTML link

Please try this

for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"

When to throw an exception?

I think you should only throw an exception when there's nothing you can do to get out of your current state. For example if you are allocating memory and there isn't any to allocate. In the cases you mention you can clearly recover from those states and can return an error code back to your caller accordingly.


You will see plenty of advice, including in answers to this question, that you should throw exceptions only in "exceptional" circumstances. That seems superficially reasonable, but is flawed advice, because it replaces one question ("when should I throw an exception") with another subjective question ("what is exceptional"). Instead, follow the advice of Herb Sutter (for C++, available in the Dr Dobbs article When and How to Use Exceptions, and also in his book with Andrei Alexandrescu, C++ Coding Standards): throw an exception if, and only if

  • a precondition is not met (which typically makes one of the following impossible) or
  • the alternative would fail to meet a post-condition or
  • the alternative would fail to maintain an invariant.

Why is this better? Doesn't it replace the question with several questions about preconditions, postconditions and invariants? This is better for several connected reasons.

  • Preconditions, postconditions and invariants are design characteristics of our program (its internal API), whereas the decision to throw is an implementation detail. It forces us to bear in mind that we must consider the design and its implementation separately, and our job while implementing a method is to produce something that satisfies the design constraints.
  • It forces us to think in terms of preconditions, postconditions and invariants, which are the only assumptions that callers of our method should make, and are expressed precisely, enabling loose coupling between the components of our program.
  • That loose coupling then allows us to refactor the implementation, if necessary.
  • The post-conditions and invariants are testable; it results in code that can be easily unit tested, because the post-conditions are predicates our unit-test code can check (assert).
  • Thinking in terms of post-conditions naturally produces a design that has success as a post-condition, which is the natural style for using exceptions. The normal ("happy") execution path of your program is laid out linearly, with all the error handling code moved to the catch clauses.

How to add empty spaces into MD markdown readme on GitHub?

Markdown gets converted into HTML/XHMTL.

John Gruber created the Markdown language in 2004 in collaboration with Aaron Swartz on the syntax, with the goal of enabling people to write using an easy-to-read, easy-to-write plain text format, and optionally convert it to structurally valid HTML (or XHTML).

HTML is completely based on using &nbsp; for adding extra spaces if it doesn't externally define/use JavaScript or CSS for elements.

Markdown is a lightweight markup language with plain text formatting syntax. It is designed so that it can be converted to HTML and many other formats using a tool by the same name.


If you want to use »

  1. only one space » either use &nbsp; or just hit Spacebar (2nd one is good choice in this case)

  2. more than one space » use &nbsp;+space (for 2 consecutive spaces)


eg. If you want to add 10 spaces contiguously then you should use

&nbsp;   &nbsp;   &nbsp;   &nbsp;   &nbsp;  

&nbsp;space&nbsp;space&nbsp;space&nbsp;space&nbsp;space

instead of using 10 &nbsp; one after one as the below one

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;


For more details check

  1. Adding multiple spaces between text in Markdown,
  2. How to create extra space in HTML or web page.

HTML checkbox - allow to check only one checkbox

 $(function () {
     $('input[type=checkbox]').click(function () {
         var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
         for (i = 0; i < chks.length; i++) {
            chks[i].checked = false;
         }
         if (chks.length > 1)
            $(this)[0].checked = true;
     });
 });

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

We were getting this same error in Fiddler when trying to figure out why our Silverlight ArcGIS map viewer wasn't loading the map. In our case it was a typo in the URL in the code. There was an equal sign in there for some reason.
http:=//someurltosome/awesome/place
instead of
http://someurltosome/awesome/place

After taking out that equal sign it worked great (of course).

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

Uncaught TypeError: Cannot read property 'length' of undefined

You are accessing an object that is not defined.

The solution is check for null or undefined (to see whether the object exists) and only then iterate.

Detecting superfluous #includes in C/C++?

It's not automatic, but doxygen will produce dependency diagrams for #included files. You will have to go through them visually, but they can be very useful for getting a picture of what is using what.

Get today date in google appScript

The following can be used to get the date:

function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1;  if(month.toString().length==1){var month = 
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

How to convert OutputStream to InputStream?

There seem to be many links and other such stuff, but no actual code using pipes. The advantage of using java.io.PipedInputStream and java.io.PipedOutputStream is that there is no additional consumption of memory. ByteArrayOutputStream.toByteArray() returns a copy of the original buffer, so that means that whatever you have in memory, you now have two copies of it. Then writing to an InputStream means you now have three copies of the data.

The code:

// take the copy of the stream and re-write it to an InputStream
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
new Thread(new Runnable() {
    public void run () {
        try {
            // write the original OutputStream to the PipedOutputStream
            // note that in order for the below method to work, you need
            // to ensure that the data has finished writing to the
            // ByteArrayOutputStream
            originalByteArrayOutputStream.writeTo(out);
        }
        catch (IOException e) {
            // logging and exception handling should go here
        }
        finally {
            // close the PipedOutputStream here because we're done writing data
            // once this thread has completed its run
            if (out != null) {
                // close the PipedOutputStream cleanly
                out.close();
            }
        }   
    }
}).start();

This code assumes that the originalByteArrayOutputStream is a ByteArrayOutputStream as it is usually the only usable output stream, unless you're writing to a file. I hope this helps! The great thing about this is that since it's in a separate thread, it also is working in parallel, so whatever is consuming your input stream will be streaming out of your old output stream too. That is beneficial because the buffer can remain smaller and you'll have less latency and less memory usage.

How to identify all stored procedures referring a particular table

Try This

   SELECT DISTINCT so.name
    FROM syscomments sc
    INNER JOIN sysobjects so ON sc.id=so.id
    WHERE sc.TEXT LIKE '%your table name%'

UICollectionView cell selection and cell reuse

Only @stefanB solution worked for me on iOS 9.3

Here what I have to change for Swift 2

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        //prepare your cell here..

        //Add background view for normal cell
        let backgroundView: UIView = UIView(frame: cell!.bounds)
        backgroundView.backgroundColor = UIColor.lightGrayColor()
        cell!.backgroundView = backgroundView

        //Add background view for selected cell
        let selectedBGView: UIView = UIView(frame: cell!.bounds)
        selectedBGView.backgroundColor = UIColor.redColor()
        cell!.selectedBackgroundView = selectedBGView

        return cell!
 }

 func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
 }

 func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
 }

How do I encode and decode a base64 string?

Based on the answers by Andrew Fox and Cebe, I turned it around and made them string extensions instead of Base64String extensions.

public static class StringExtensions
{
    public static string ToBase64(this string text)
    {
        return ToBase64(text, Encoding.UTF8);
    }

    public static string ToBase64(this string text, Encoding encoding)
    {
        if (string.IsNullOrEmpty(text))
        {
            return text;
        }

        byte[] textAsBytes = encoding.GetBytes(text);
        return Convert.ToBase64String(textAsBytes);
    }

    public static bool TryParseBase64(this string text, out string decodedText)
    {
        return TryParseBase64(text, Encoding.UTF8, out decodedText);
    }

    public static bool TryParseBase64(this string text, Encoding encoding, out string decodedText)
    {
        if (string.IsNullOrEmpty(text))
        {
            decodedText = text;
            return false;
        }

        try
        {
            byte[] textAsBytes = Convert.FromBase64String(text);
            decodedText = encoding.GetString(textAsBytes);
            return true;
        }
        catch (Exception)
        {
            decodedText = null;
            return false;
        }
    }
}

finding first day of the month in python

This is a pithy solution.

import datetime 

todayDate = datetime.date.today()
if todayDate.day > 25:
    todayDate += datetime.timedelta(7)
print todayDate.replace(day=1)

One thing to note with the original code example is that using timedelta(30) will cause trouble if you are testing the last day of January. That is why I am using a 7-day delta.

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Here is another way you can change the selected option of a <select> element in javascript. You can use

document.getElementById('salesperson').selectedIndex=1;

Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.

Here is a sample code. Check if you can use this type of approach:

<html>
<head>
<script language="javascript">

function changeSelected() { 
document.getElementById('salesperson').selectedIndex=1;

} 

</script>
</head>
<body>
<form name="f1">

<select id="salesperson" > 
   <option value"">james</option>
   <option value"">john</option>  
</select> 
<input type="button" value="Change Selected" onClick="changeSelected();">

</form>
</body>
</html>

Side-by-side list items as icons within a div (css)

add this line in your css file:

.classname ul li {
    float: left;
}

Is Python strongly typed?

There are some important issues that I think all of the existing answers have missed.


Weak typing means allowing access to the underlying representation. In C, I can create a pointer to characters, then tell the compiler I want to use it as a pointer to integers:

char sz[] = "abcdefg";
int *i = (int *)sz;

On a little-endian platform with 32-bit integers, this makes i into an array of the numbers 0x64636261 and 0x00676665. In fact, you can even cast pointers themselves to integers (of the appropriate size):

intptr_t i = (intptr_t)&sz;

And of course this means I can overwrite memory anywhere in the system.*

char *spam = (char *)0x12345678
spam[0] = 0;

* Of course modern OS's use virtual memory and page protection so I can only overwrite my own process's memory, but there's nothing about C itself that offers such protection, as anyone who ever coded on, say, Classic Mac OS or Win16 can tell you.

Traditional Lisp allowed similar kinds of hackery; on some platforms, double-word floats and cons cells were the same type, and you could just pass one to a function expecting the other and it would "work".

Most languages today aren't quite as weak as C and Lisp were, but many of them are still somewhat leaky. For example, any OO language that has an unchecked "downcast",* that's a type leak: you're essentially telling the compiler "I know I didn't give you enough information to know this is safe, but I'm pretty sure it is," when the whole point of a type system is that the compiler always has enough information to know what's safe.

* A checked downcast doesn't make the language's type system any weaker just because it moves the check to runtime. If it did, then subtype polymorphism (aka virtual or fully-dynamic function calls) would be the same violation of the type system, and I don't think anyone wants to say that.

Very few "scripting" languages are weak in this sense. Even in Perl or Tcl, you can't take a string and just interpret its bytes as an integer.* But it's worth noting that in CPython (and similarly for many other interpreters for many languages), if you're really persistent, you can use ctypes to load up libpython, cast an object's id to a POINTER(Py_Object), and force the type system to leak. Whether this makes the type system weak or not depends on your use cases—if you're trying to implement an in-language restricted execution sandbox to ensure security, you do have to deal with these kinds of escapes…

* You can use a function like struct.unpack to read the bytes and build a new int out of "how C would represent these bytes", but that's obviously not leaky; even Haskell allows that.


Meanwhile, implicit conversion is really a different thing from a weak or leaky type system.

Every language, even Haskell, has functions to, say, convert an integer to a string or a float. But some languages will do some of those conversions for you automatically—e.g., in C, if you call a function that wants a float, and you pass it in int, it gets converted for you. This can definitely lead to bugs with, e.g., unexpected overflows, but they're not the same kinds of bugs you get from a weak type system. And C isn't really being any weaker here; you can add an int and a float in Haskell, or even concatenate a float to a string, you just have to do it more explicitly.

And with dynamic languages, this is pretty murky. There's no such thing as "a function that wants a float" in Python or Perl. But there are overloaded functions that do different things with different types, and there's a strong intuitive sense that, e.g., adding a string to something else is "a function that wants a string". In that sense, Perl, Tcl, and JavaScript appear to do a lot of implicit conversions ("a" + 1 gives you "a1"), while Python does a lot fewer ("a" + 1 raises an exception, but 1.0 + 1 does give you 2.0*). It's just hard to put that sense into formal terms—why shouldn't there be a + that takes a string and an int, when there are obviously other functions, like indexing, that do?

* Actually, in modern Python, that can be explained in terms of OO subtyping, since isinstance(2, numbers.Real) is true. I don't think there's any sense in which 2 is an instance of the string type in Perl or JavaScript… although in Tcl, it actually is, since everything is an instance of string.


Finally, there's another, completely orthogonal, definition of "strong" vs. "weak" typing, where "strong" means powerful/flexible/expressive.

For example, Haskell lets you define a type that's a number, a string, a list of this type, or a map from strings to this type, which is a perfectly way to represent anything that can be decoded from JSON. There's no way to define such a type in Java. But at least Java has parametric (generic) types, so you can write a function that takes a List of T and know that the elements are of type T; other languages, like early Java, forced you to use a List of Object and downcast. But at least Java lets you create new types with their own methods; C only lets you create structures. And BCPL didn't even have that. And so on down to assembly, where the only types are different bit lengths.

So, in that sense, Haskell's type system is stronger than modern Java's, which is stronger than earlier Java's, which is stronger than C's, which is stronger than BCPL's.

So, where does Python fit into that spectrum? That's a bit tricky. In many cases, duck typing allows you to simulate everything you can do in Haskell, and even some things you can't; sure, errors are caught at runtime instead of compile time, but they're still caught. However, there are cases where duck typing isn't sufficient. For example, in Haskell, you can tell that an empty list of ints is a list of ints, so you can decide that reducing + over that list should return 0*; in Python, an empty list is an empty list; there's no type information to help you decide what reducing + over it should do.

* In fact, Haskell doesn't let you do this; if you call the reduce function that doesn't take a start value on an empty list, you get an error. But its type system is powerful enough that you could make this work, and Python's isn't.

Switching to landscape mode in Android Emulator

Not sure about your question - "sideways" is the same as "landscape".

If you mean how to switch during runtime:

  • Switch to previous layout orientation (for example, portrait, landscape): KEYPAD_7, Ctrl + F11
  • Switch to next layout orientation (for example, portrait, landscape): KEYPAD_9, Ctrl + F12

From docs.

'python3' is not recognized as an internal or external command, operable program or batch file

Yes, I think for Windows users you need to change all the python3 calls to python to solve your original error. This change will run the Python version set in your current environment. If you need to keep this call as it is (aka python3) because you are working in cross-platform or for any other reason, then a work around is to create a soft link. To create it, go to the folder that contains the Python executable and create the link. For example, this worked in my case in Windows 10 using mklink:

cd C:\Python3
mklink python3.exe python.exe

Use a (soft) symbolic link in Linux:

cd /usr/bin/python3
ln -s python.exe python3.exe

VBA Count cells in column containing specified value

Not what you asked but may be useful nevertheless.

Of course you can do the same thing with matrix formulas. Just read the result of the cell that contains:

Cell A1="Text to search"
Cells A2:C20=Range to search for

=COUNT(SEARCH(A1;A2:C20;1))

Remember that entering matrix formulas needs CTRL+SHIFT+ENTER, not just ENTER. After, it should look like :

{=COUNT(SEARCH(A1;A2:C20;1))}

Print specific part of webpage

Try this awesome ink-html library

import print from 'ink-html'
// const print = require('ink-html').default

// js
print(window.querySelector('#printable'))
// Vue.js
print(this.$refs.printable.$el)

How do I convert a Swift Array to a String?

To change an array of Optional/Non-Optional Strings

//Array of optional Strings
let array : [String?] = ["1",nil,"2","3","4"]

//Separator String
let separator = ","

//flatMap skips the nil values and then joined combines the non nil elements with the separator
let joinedString = array.flatMap{ $0 }.joined(separator: separator)


//Use Compact map in case of **Swift 4**
    let joinedString = array.compactMap{ $0 }.joined(separator: separator

print(joinedString)

Here flatMap, compactMap skips the nil values in the array and appends the other values to give a joined string.

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

How to create image slideshow in html?

Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.

Here is the one I most liked.

http://www.zurb.com/playground/orbit-jquery-image-slider

How do I count a JavaScript object's attributes?

For those which will read this question/answers, here is a JavaScript implementation of Dictionary collection very similar as functionality as .NET one: JavaScript Dictionary

Android custom Row Item for ListView

you can follow BaseAdapter and create your custome Xml file and bind it with you BaseAdpter and populate it with Listview see here need to change xml file as Require.

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Update in July 2020:

During the last 16 months, maybe the most notable change in the React community is React hooks.

According to what I observe, in order to gain better compatibility with functional components and hooks, projects (even those large ones) would tend to use:

  1. hook + async thunk (hook makes everything very flexible so you could actually place async thunk in where you want and use it as normal functions, for example, still write thunk in action.ts and then useDispatch() to trigger the thunk: https://stackoverflow.com/a/59991104/5256695),
  2. useRequest,
  3. GraphQL/Apollo useQuery useMutation
  4. react-fetching-library
  5. other popular choices of data fetching/API call libraries, tools, design patterns, etc

In comparison, redux-saga doesn't really provide significant benefit in most normal cases of API calls comparing to the above approaches for now, while increasing project complexity by introducing many saga files/generators (also because the last release v1.1.1 of redux-saga was on 18 Sep 2019, which was a long time ago).

But still, redux-saga provides some unique features such as racing effect and parallel requests. Therefore, if you need these special functionalities, redux-saga is still a good choice.


Original post in March 2019:

Just some personal experience:

  1. For coding style and readability, one of the most significant advantages of using redux-saga in the past is to avoid callback hell in redux-thunk — one does not need to use many nesting then/catch anymore. But now with the popularity of async/await thunk, one could also write async code in sync style when using redux-thunk, which may be regarded as an improvement in redux-thunk.

  2. One may need to write much more boilerplate codes when using redux-saga, especially in Typescript. For example, if one wants to implement a fetch async function, the data and error handling could be directly performed in one thunk unit in action.js with one single FETCH action. But in redux-saga, one may need to define FETCH_START, FETCH_SUCCESS and FETCH_FAILURE actions and all their related type-checks, because one of the features in redux-saga is to use this kind of rich “token” mechanism to create effects and instruct redux store for easy testing. Of course one could write a saga without using these actions, but that would make it similar to a thunk.

  3. In terms of the file structure, redux-saga seems to be more explicit in many cases. One could easily find an async related code in every sagas.ts, but in redux-thunk, one would need to see it in actions.

  4. Easy testing may be another weighted feature in redux-saga. This is truly convenient. But one thing that needs to be clarified is that redux-saga “call” test would not perform actual API call in testing, thus one would need to specify the sample result for the steps which may be used after the API call. Therefore before writing in redux-saga, it would be better to plan a saga and its corresponding sagas.spec.ts in detail.

  5. Redux-saga also provides many advanced features such as running tasks in parallel, concurrency helpers like takeLatest/takeEvery, fork/spawn, which are far more powerful than thunks.

In conclusion, personally, I would like to say: in many normal cases and small to medium size apps, go with async/await style redux-thunk. It would save you many boilerplate codes/actions/typedefs, and you would not need to switch around many different sagas.ts and maintain a specific sagas tree. But if you are developing a large app with much complex async logic and the need for features like concurrency/parallel pattern, or have a high demand for testing and maintenance (especially in test-driven development), redux-sagas would possibly save your life.

Anyway, redux-saga is not more difficult and complex than redux itself, and it does not have a so-called steep learning curve because it has well-limited core concepts and APIs. Spending a small amount of time learning redux-saga may benefit yourself one day in the future.

Bootstrap 3 offset on right not left

Based on WeNeigh's answer! here is a LESS example

.col-offset-right(@i, @type) when (@i >= 0) {
    .col-@{type}-offset-right-@{i} {
        margin-right: percentage((@i / @grid-columns));
    }
    .col-offset-right(@i - 1, @type);
};
.col-offset-right(@grid-columns, xs);
.col-offset-right(@grid-columns, sm);
.col-offset-right(@grid-columns, md);
.col-offset-right(@grid-columns, lg);

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

MAX_EXECUTION_TIME is also an important parameter for long running queries.Will work for MySQL 5.7 or later.

Check the current value

SELECT @@GLOBAL.MAX_EXECUTION_TIME, @@SESSION.MAX_EXECUTION_TIME;

Then set it according to your needs.

SET SESSION MAX_EXECUTION_TIME=2000;
SET GLOBAL MAX_EXECUTION_TIME=2000;

Regular Expression Validation For Indian Phone Number and Mobile number

you can implement following regex regex = '^[6-9][0-9]{9}$'

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

Getting list of items inside div using Selenium Webdriver

Follow the code below exactly matched with your case.

  1. Create an interface of the web element for the div under div with class as facetContainerDiv

ie for

<div class="facetContainerDiv">
    <div>

    </div>
</div>

2. Create an IList with all the elements inside the second div i.e for,

<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>

3. Access each check boxes using the index

Please find the code below

using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace SeleniumTests
{
  class ChechBoxClickWthIndex
    {
        static void Main(string[] args)
        {

            IWebDriver driver = new FirefoxDriver();

            driver.Navigate().GoToUrl("file:///C:/Users/chery/Desktop/CheckBox.html");

            // Create an interface WebElement of the div under div with **class as facetContainerDiv**
            IWebElement WebElement =    driver.FindElement(By.XPath("//div[@class='facetContainerDiv']/div"));
            // Create an IList and intialize it with all the elements of div under div with **class as facetContainerDiv**
            IList<IWebElement> AllCheckBoxes = WebElement.FindElements(By.XPath("//label/input"));
            int RowCount = AllCheckBoxes.Count;
            for (int i = 0; i < RowCount; i++)
            {
            // Check the check boxes based on index
               AllCheckBoxes[i].Click();

            }
            Console.WriteLine(RowCount);
            Console.ReadLine(); 

        }
    }
}

Text File Parsing in Java

While calling/invoking your programme you can use this command : java [-options] className [args...]
in place of [-options] provide more memory e.g -Xmx1024m or more. but this is just a workaround, u have to change ur parsing mechanism.

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

What are the differences between Abstract Factory and Factory design patterns?

Allow me to put it precisely. Most of the answers have already explained, provided diagrams and examples as well.

So my answer would just be a one-liner. My own words: “An abstract factory pattern adds on the abstract layer over multiple factory method implementations. It means an abstract factory contains or composite one or more than one factory method pattern”

Where is android studio building my .apk file?

in android 3.1.0 Above use below path to find signed version of APK

home/AndroidStudioProjects/<projedct name>/app/app-release.apk

and in windows

AndroidStudioProjects\{project name}\app\release\app-release.apk

Count the items from a IEnumerable<T> without iterating?

Just adding extra some info:

The Count() extension doesn't always iterate. Consider Linq to Sql, where the count goes to the database, but instead of bringing back all the rows, it issues the Sql Count() command and returns that result instead.

Additionally, the compiler (or runtime) is smart enough that it will call the objects Count() method if it has one. So it's not as other responders say, being completely ignorant and always iterating in order to count elements.

In many cases where the programmer is just checking if( enumerable.Count != 0 ) using the Any() extension method, as in if( enumerable.Any() ) is far more efficient with linq's lazy evaluation as it can short-circuit once it can determine there are any elements. It's also more readable

How to subtract n days from current date in java?

You don't have to use Calendar. You can just play with timestamps :

Date d = initDate();//intialize your date to any date 
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 l ); //Subtract n days   

UPDATE DO NOT FORGET TO ADD "l" for long by the end of 1000.

Please consider the below WARNING:

Adding 1000*60*60*24 milliseconds to a java date will once in a great while add zero days or two days to the original date in the circumstances of leap seconds, daylight savings time and the like. If you need to be 100% certain only one day is added, this solution is not the one to use.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

ax.axis('off'), will as Joe Kington pointed out, remove everything except the plotted line.

For those wanting to only remove the frame (border), and keep labels, tickers etc, one can do that by accessing the spines object on the axis. Given an axis object ax, the following should remove borders on all four sides:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

And, in case of removing x and y ticks from the plot:

 ax.get_xaxis().set_ticks([])
 ax.get_yaxis().set_ticks([])

ORA-01882: timezone region not found

I ran into this problem with Tomcat. Setting the following in $CATALINA_BASE/bin/setenv.sh solved the issue:

JAVA_OPTS=-Doracle.jdbc.timezoneAsRegion=false

I'm sure that using one of the Java parameter suggestions from the other answers would work in the same way.

How often should Oracle database statistics be run?

What Oracle version are you using? Check this page which refers to Oracle 10:

http://www.acs.ilstu.edu/docs/Oracle/server.101/b10752/stats.htm

It says:

The recommended approach to gathering statistics is to allow Oracle to automatically gather the statistics. Oracle gathers statistics on all database objects automatically and maintains those statistics in a regularly-scheduled maintenance job.

convert epoch time to date

Please take care that the epoch time is in second and Date object accepts Long value which is in milliseconds. Hence you would have to multiply epoch value with 1000 to use it as long value . Like below :-

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
Long dateLong=Long.parseLong(sdf.format(epoch*1000));

What is "android.R.layout.simple_list_item_1"?

Zakaria, that is a reference to an built-in XML layout document that is part of the Android OS, rather than one of your own XML layouts.

Here is a further list of layouts that you can use: http://developer.android.com/reference/android/R.layout.html
(Updated link thanks @Estel: https://github.com/android/platform_frameworks_base/tree/master/core/res/res/layout )

You can actually view the code for the layouts.

How to get the first word in the string

If you want to feel especially sly, you can write it as this:

(firstWord, rest) = yourLine.split(maxsplit=1)

This is supposed to bring the best from both worlds:

I kind of fell in love with this solution and it's general unpacking capability, so I had to share it.

Is it possible to run CUDA on AMD GPUs?

Nope, you can't use CUDA for that. CUDA is limited to NVIDIA hardware. OpenCL would be the best alternative.

Khronos itself has a list of resources. As does the StreamComputing.eu website. For your AMD specific resources, you might want to have a look at AMD's APP SDK page.

Note that at this time there are several initiatives to translate/cross-compile CUDA to different languages and APIs. One such an example is HIP. Note however that this still does not mean that CUDA runs on AMD GPUs.

Using NotNull Annotation in method argument

If you are using Spring, you can force validation by annotating the class with @Validated:

import org.springframework.validation.annotation.Validated;

More info available here: Javax validation @NotNull annotation usage

Integer value comparison

To figure out if an Integer is greater than 0, you can:

  • check if compareTo(O) returns a positive number:

    if (count.compareTo(0) > 0)
         ...
    

    But that looks pretty silly, doesn't it? Better just...

  • use autoboxing1:

    if (count > 0)
        ....
    

    This is equivalent to:

    if (count.intValue() > 0)
        ...
    

    It is important to note that "==" is evaluated like this, with the Integer operand unboxed rather than the int operand boxed. Otherwise, count == 0 would return false when count was initialized as new Integer(0) (because "==" tests for reference equality).

1Technically, the first example uses autoboxing (before Java 1.5 you couldn't pass an int to compareTo) and the second example uses unboxing. The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology.

Android RatingBar change star colors

2015 Update

Now you can use DrawableCompat to tint all kind of drawables. For example:

Drawable progress = ratingBar.getProgressDrawable();
DrawableCompat.setTint(progress, Color.WHITE);

This is backwards compatible up to API 4