Programs & Examples On #God object

God object is an object that knows too much or does too much. The god object is an example of an anti-pattern.

How can I export the schema of a database in PostgreSQL?

In Linux you can do like this

pg_dump -U postgres -s postgres > exportFile.dmp

Maybe it can work in Windows too, if not try the same with pg_dump.exe

pg_dump.exe -U postgres -s postgres > exportFile.dmp

jQuery posting JSON

In case you are sending this post request to a cross domain, you should check out this link.

https://stackoverflow.com/a/1320708/969984

Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

Windows 7: unable to register DLL - Error Code:0X80004005

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type regsvr32 MyComobject.dll

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

How do I remove a comma off the end of a string?

A simple regular expression would work

$string = preg_replace("/,$/", "", $string)

How to close a Tkinter window by pressing a Button?

You can associate directly the function object window.destroy to the command attribute of your button:

button = Button (frame, text="Good-bye.", command=window.destroy)

This way you will not need the function close_window to close the window for you.

How to debug .htaccess RewriteRule not working

Generally any change in the .htaccess should have visible effects. If no effect, check your configuration apache files, something like:

<Directory ..>
    ...
    AllowOverride None
    ...
</Directory>

Should be changed to

AllowOverride All

And you'll be able to change directives in .htaccess files.

How to open a new form from another form

Use this.Hide() instead of this.Close()

How to add users to Docker container?

The trick is to use useradd instead of its interactive wrapper adduser. I usually create users with:

RUN useradd -ms /bin/bash newuser

which creates a home directory for the user and ensures that bash is the default shell.

You can then add:

USER newuser
WORKDIR /home/newuser

to your dockerfile. Every command afterwards as well as interactive sessions will be executed as user newuser:

docker run -t -i image
newuser@131b7ad86360:~$

You might have to give newuser the permissions to execute the programs you intend to run before invoking the user command.

Using non-privileged users inside containers is a good idea for security reasons. It also has a few drawbacks. Most importantly, people deriving images from your image will have to switch back to root before they can execute commands with superuser privileges.

How to save LogCat contents to file?

If you are in the console window for the device and if you use Teraterm, then from the Menu do a File | Log and it will automatically save to file.

In SQL Server, how to create while loop in select

No functions, no cursors. Try this

with cte as(
select CHAR(65) chr, 65 i 
union all
select CHAR(i+1) chr, i=i+1 from cte
where CHAR(i) <'Z'
)
select * from(
SELECT id, Case when LEN(data)>len(REPLACE(data, chr,'')) then chr+chr end data 
FROM table1, cte) x
where Data is not null

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

how to convert object to string in java

Might not be so related to the issue above. However if you are looking for a way to serialize Java object as string, this could come in hand

package pt.iol.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;

public class ObjectUtil {

    static final Base64 base64 = new Base64();

    public static String serializeObjectToString(Object object) throws IOException {
        try (
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);) {
            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
            return new String(base64.encode(arrayOutputStream.toByteArray()));
        }
    }

    public static Object deserializeObjectFromString(String objectString) throws IOException, ClassNotFoundException {
        try (
                ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(base64.decode(objectString));
                GZIPInputStream gzipInputStream = new GZIPInputStream(arrayInputStream);
                ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
            return objectInputStream.readObject();
        }
    }
}

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Find duplicate characters in a String and count the number of occurances using Java

If your string only contains alphabets then you can use some thing like this.

public class StringExample {
public static void main(String[] args) {
    String str = "abcdabghplhhnfl".toLowerCase();
    // create a integer array for 26 alphabets.
    // where index 0,1,2.. will be the container for frequency of a,b,c...
    Integer[] ar = new Integer[26];
    // fill the integer array with character frequency.
    for(int i=0;i<str.length();i++) {
        int j = str.charAt(i) -'a';
        if(ar[j]==null) {
            ar[j]= 1;
        }else {
            ar[j]+= 1;
        }
    }   
    // print only those alphabets having frequency greater then 1.
    for(int i=0;i<ar.length;i++) {
        if(ar[i]!=null && ar[i]>1) {
            char c = (char) (97+i);
            System.out.println("'"+c+"' comes "+ar[i]+" times.");
        }
    }
}
}

Output:

 'a' comes 2 times.
 'b' comes 2 times.
 'h' comes 3 times.
 'l' comes 2 times.

Convert char * to LPWSTR

This version, using the Windows API function MultiByteToWideChar(), handles the memory allocation for arbitrarily long input strings.

int lenA = lstrlenA(input);
int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0);
if (lenW>0)
{
    output = new wchar_t[lenW];
    ::MultiByteToWideChar(CP_ACP, 0, input, lenA, output, lenW);
} 

How can I access an internal class from an external assembly?

I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.

Saying that there is a way to allow "Friend" assemblies access to internals:

In the AssemblyInfo.cs file of the project you add a line for each assembly.

[assembly: InternalsVisibleTo("name of assembly here")]

this info is available here.

Hope this helps.

Using :before CSS pseudo element to add image to modal

http://caniuse.com/#search=::after

::after and ::before with content are better to use as they're supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8.

Is this what you're looking for?

.Modal::after{
  content:url('blackCarrot.png'); /* with class ModalCarrot ??*/
  position:relative; /*or absolute*/
  z-index:100000; /*a number that's more than the modal box*/
  left:-50px;
  top:10px;
}

.ModalCarrot{
   position:absolute;
   left:50%;
   margin-left:-8px;
   top:-16px;
}

If not, can you explain a little better?

or you could use jQuery, like Joshua said:

$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");

How to ALTER multiple columns at once in SQL Server

As lots of others have said, you will need to use multiple ALTER COLUMN statements, one for each column you want to modify.

If you want to modify all or several of the columns in your table to the same datatype (such as expanding a VARCHAR field from 50 to 100 chars), you can generate all the statements automatically using the query below. This technique is also useful if you want to replace the same character in multiple fields (such as removing \t from all columns).

SELECT
     TABLE_CATALOG
    ,TABLE_SCHEMA
    ,TABLE_NAME
    ,COLUMN_NAME
    ,'ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ALTER COLUMN ['+COLUMN_NAME+'] VARCHAR(300)' as 'code'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'your_table' AND TABLE_SCHEMA = 'your_schema'

This generates an ALTER TABLE statement for each column for you.

How can I one hot encode in Python?

Short Answer

Here is a function to do one-hot-encoding without using numpy, pandas, or other packages. It takes a list of integers, booleans, or strings (and perhaps other types too).

import typing


def one_hot_encode(items: list) -> typing.List[list]:
    results = []
    # find the unique items (we want to unique items b/c duplicate items will have the same encoding)
    unique_items = list(set(items))
    # sort the unique items
    sorted_items = sorted(unique_items)
    # find how long the list of each item should be
    max_index = len(unique_items)

    for item in items:
        # create a list of zeros the appropriate length
        one_hot_encoded_result = [0 for i in range(0, max_index)]
        # find the index of the item
        one_hot_index = sorted_items.index(item)
        # change the zero at the index from the previous line to a one
        one_hot_encoded_result[one_hot_index] = 1
        # add the result
        results.append(one_hot_encoded_result)

    return results

Example:

one_hot_encode([2, 1, 1, 2, 5, 3])

# [[0, 1, 0, 0],
#  [1, 0, 0, 0],
#  [1, 0, 0, 0],
#  [0, 1, 0, 0],
#  [0, 0, 0, 1],
#  [0, 0, 1, 0]]
one_hot_encode([True, False, True])

# [[0, 1], [1, 0], [0, 1]]
one_hot_encode(['a', 'b', 'c', 'a', 'e'])

# [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1]]

Long(er) Answer

I know there are already a lot of answers to this question, but I noticed two things. First, most of the answers use packages like numpy and/or pandas. And this is a good thing. If you are writing production code, you should probably be using robust, fast algorithms like those provided in the numpy/pandas packages. But, for the sake of education, I think someone should provide an answer which has a transparent algorithm and not just an implementation of someone else's algorithm. Second, I noticed that many of the answers do not provide a robust implementation of one-hot encoding because they do not meet one of the requirements below. Below are some of the requirements (as I see them) for a useful, accurate, and robust one-hot encoding function:

A one-hot encoding function must:

  • handle list of various types (e.g. integers, strings, floats, etc.) as input
  • handle an input list with duplicates
  • return a list of lists corresponding (in the same order as) to the inputs
  • return a list of lists where each list is as short as possible

I tested many of the answers to this question and most of them fail on one of the requirements above.

Node.js project naming conventions for files & folders

After some years with node, I can say that there are no conventions for the directory/file structure. However most (professional) express applications use a setup like:

/
  /bin - scripts, helpers, binaries
  /lib - your application
  /config - your configuration
  /public - your public files
  /test - your tests

An example which uses this setup is nodejs-starter.

I personally changed this setup to:

/
  /etc - contains configuration
  /app - front-end javascript files
    /config - loads config
    /models - loads models
  /bin - helper scripts
  /lib - back-end express files
    /config - loads config to app.settings
    /models - loads mongoose models
    /routes - sets up app.get('..')...
  /srv - contains public files
  /usr - contains templates
  /test - contains test files

In my opinion, the latter matches better with the Unix-style directory structure (whereas the former mixes this up a bit).

I also like this pattern to separate files:

lib/index.js

var http = require('http');
var express = require('express');

var app = express();

app.server = http.createServer(app);

require('./config')(app);

require('./models')(app);

require('./routes')(app);

app.server.listen(app.settings.port);

module.exports = app;

lib/static/index.js

var express = require('express');

module.exports = function(app) {

  app.use(express.static(app.settings.static.path));

};

This allows decoupling neatly all source code without having to bother dependencies. A really good solution for fighting nasty Javascript. A real-world example is nearby which uses this setup.

Update (filenames):

Regarding filenames most common are short, lowercase filenames. If your file can only be described with two words most JavaScript projects use an underscore as the delimiter.

Update (variables):

Regarding variables, the same "rules" apply as for filenames. Prototypes or classes, however, should use camelCase.

Update (styleguides):

Django - Did you forget to register or load this tag?

For Django 2.2 up to 3, you have to load staticfiles in html template first before use static keyword

{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

For other versions use static

{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

Also you have to check that you defined STATIC_URL in setting.py

At last, make sure the static files exist in the defined folder

Bash: Strip trailing linebreak from output

If you assign its output to a variable, bash automatically strips whitespace:

linecount=`wc -l < log.txt`

Why use def main()?

Everyone else has already answered it, but I think I still have something else to add.

Reasons to have that if statement calling main() (in no particular order):

  • Other languages (like C and Java) have a main() function that is called when the program is executed. Using this if, we can make Python behave like them, which feels more familiar for many people.

  • Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)

  • It will be possible to import that python code as a module without nasty side-effects.

  • This means it will be possible to run tests against that code.

  • This means we can import that code into an interactive python shell and test/debug/run it.

  • Variables inside def main are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.

But, you are not required to write a main() function and call it inside an if statement.

I myself usually start writing small throwaway scripts without any kind of function. If the script grows big enough, or if I feel putting all that code inside a function will benefit me, then I refactor the code and do it. This also happens when I write bash scripts.

Even if you put code inside the main function, you are not required to write it exactly like that. A neat variation could be:

import sys

def main(argv):
    # My code here
    pass

if __name__ == "__main__":
    main(sys.argv)

This means you can call main() from other scripts (or interactive shell) passing custom parameters. This might be useful in unit tests, or when batch-processing. But remember that the code above will require parsing of argv, thus maybe it would be better to use a different call that pass parameters already parsed.

In an object-oriented application I've written, the code looked like this:

class MyApplication(something):
    # My code here

if __name__ == "__main__":
    app = MyApplication()
    app.run()

So, feel free to write the code that better suits you. :)

Android: Rotate image in imageview by an angle

I have a solution to this. Actually it is a solution to a problem that arises after rotation(Rectangular image doesn't fit ImagView) but it covers your problem too.. Although this Solution has Animation for better or for worse

    int h,w;
    Boolean safe=true;

Getting the parameters of imageView is not possible at initialisation of activity To do so please refer to this solution OR set the dimensions at onClick of a Button Like this

    rotateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(imageView.getRotation()/90%2==0){
                h=imageView.getHeight();
                w=imageView.getWidth();

            }
        .
        .//Insert the code Snippet below here 
       }

And the code to be run when we want to rotate ImageView

if(safe)     
imageView.animate().rotationBy(90).scaleX(imageView.getRotation()/90%2==0?(w*1.0f/h):1).scaleY(imageView.getRotation()/90%2==0?(w*1.0f/h):1).setDuration(2000).setInterpolator(new LinearInterpolator()).setListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                      safe=false;
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                      safe=true;

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            }).start();
        }
    });

This solution is sufficient for the Problem above.Although it will shrink the imageView even if it is not necessary(when height is smaller than Width).If it bothers you,you can add another ternary operator inside scaleX/scaleY.

Javascript onload not working

You are missing the ()

<body onload="imageRefreshBig();">

How to prepend a string to a column value in MySQL?

Many string update functions in MySQL seems to be working like this: If one argument is null, then concatenation or other functions return null too. So, to update a field with null value, first set it to a non-null value, such as ''

For example:

update table set field='' where field is null;
update table set field=concat(field,' append');

Is the NOLOCK (Sql Server hint) bad practice?

The better solutions, when possible are:

  • Replicate your data (using log-replication) to a reporting database.
  • Use SAN snapshots and mount a consistent version of the DB
  • Use a database which has a better fundamental transaction isolation level

The SNAPSHOT transaction isolation level was created because MS was losing sales to Oracle. Oracle uses undo/redo logs to avoid this problem. Postgres uses MVCC. In the future MS's Heckaton will use MVCC, but that's years away from being production ready.

HTML Table cellspacing or padding just top / bottom

Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top, padding-bottom, padding-left, and padding-right; or padding: [top] [right] [bottom] [left];).

How to debug a Flask app

Install python-dotenv in your virtual environment.

Create a .flaskenv in your project root. By project root, I mean the folder which has your app.py file

Inside this file write the following:

FLASK_APP=myapp 
FLASK_ENV=development

Now issue the following command:

flask run

CSS image resize percentage of itself?

Try zoom property

<img src="..." style="zoom: 0.5" />

Edit: Apparently, FireFox doesn't support zoom property. You should use;

-moz-transform: scale(0.5);

for FireFox.

Rotating a Div Element in jQuery

I doubt you can rotate an element using DOM/CSS. Your best bet would be to render to a canvas and rotate that (not sure on the specifics).

Setting unique Constraint with fluent API?

As an addition to Yorro's answer, it can also be done by using attributes.

Sample for int type unique key combination:

[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }

[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }

If the data type is string, then MaxLength attribute must be added:

[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }

[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }

If there is a domain/storage model separation concern, using Metadatatype attribute/class can be an option: https://msdn.microsoft.com/en-us/library/ff664465%28v=pandp.50%29.aspx?f=255&MSPPError=-2147217396


A quick console app example:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace EFIndexTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new AppDbContext())
            {
                var newUser = new User { UniqueKeyIntPart1 = 1, UniqueKeyIntPart2 = 1, UniqueKeyStringPart1 = "A", UniqueKeyStringPart2 = "A" };
                context.UserSet.Add(newUser);
                context.SaveChanges();
            }
        }
    }

    [MetadataType(typeof(UserMetadata))]
    public class User
    {
        public int Id { get; set; }
        public int UniqueKeyIntPart1 { get; set; }
        public int UniqueKeyIntPart2 { get; set; }
        public string UniqueKeyStringPart1 { get; set; }
        public string UniqueKeyStringPart2 { get; set; }
    }

    public class UserMetadata
    {
        [Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
        public int UniqueKeyIntPart1 { get; set; }

        [Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
        public int UniqueKeyIntPart2 { get; set; }

        [Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
        [MaxLength(50)]
        public string UniqueKeyStringPart1 { get; set; }

        [Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
        [MaxLength(50)]
        public string UniqueKeyStringPart2 { get; set; }
    }

    public class AppDbContext : DbContext
    {
        public virtual DbSet<User> UserSet { get; set; }
    }
}

Issue with background color in JavaFX 8

Both these work for me. Maybe post a complete example?

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class PaneBackgroundTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();
        VBox vbox = new VBox();
        root.setCenter(vbox);

        ToggleButton toggle = new ToggleButton("Toggle color");
        HBox controls = new HBox(5, toggle);
        controls.setAlignment(Pos.CENTER);
        root.setBottom(controls);

//        vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
//                .then("-fx-background-color: cornflowerblue;")
//                .otherwise("-fx-background-color: white;"));

        vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
                .then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
                .otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

How to remove line breaks from a file in Java?

org.apache.commons.lang.StringUtils#chopNewline

How to upload files to server using JSP/Servlet?

Here's an example using apache commons-fileupload:

// apache commons-fileupload to handle file upload
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(DataSources.TORRENTS_DIR()));
ServletFileUpload fileUpload = new ServletFileUpload(factory);

List<FileItem> items = fileUpload.parseRequest(req.raw());
FileItem item = items.stream()
  .filter(e ->
  "the_upload_name".equals(e.getFieldName()))
  .findFirst().get();
String fileName = item.getName();

item.write(new File(dir, fileName));
log.info(fileName);

Reverse a string in Java

public String reverseWords(String s) {

    String reversedWords = "";

    if(s.length()<=0) {
        return reversedWords;
    }else if(s.length() == 1){
        if(s == " "){
            return "";
        }
        return s;
    }

    char arr[] = s.toCharArray();
    int j = arr.length-1;
    while(j >= 0 ){
        if( arr[j] == ' '){
            reversedWords+=arr[j];
        }else{
            String temp="";
            while(j>=0 && arr[j] != ' '){
                temp+=arr[j];
                j--;
            }
            j++;
            temp = reverseWord(temp);
            reversedWords+=temp;
        }
        j--;

    }

    String[] chk = reversedWords.split(" ");

    if(chk == null || chk.length == 0){
        return "";
    }

    return reversedWords;



}

public String reverseWord(String s){

    char[] arr = s.toCharArray();

    for(int i=0,j=arr.length-1;i<=j;i++,j--){
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    return String.valueOf(arr);

}

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

List files committed for a revision

To just get the list of the changed files with the paths, use

svn diff --summarize -r<rev-of-commit>:<rev-of-commit - 1>

For example:

svn diff --summarize -r42:41

should result in something like

M       path/to/modifiedfile
A       path/to/newfile

Same Navigation Drawer in different Activities

With @Kevin van Mierlo 's answer, you are also capable of implementing several drawers. For instance, the default menu located on the left side (start), and a further optional menu, located on the right side, which is only shown when determinate fragments are loaded.

I've been able to do that.

How do I find the difference between two values without knowing which is larger?

Just use abs(x - y). This'll return the net difference between the two as a positive value, regardless of which value is larger.

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
    echo "Sorry you are Offline"
    exit 1
fi

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

getResources().getColor() is deprecated

well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor function. You can get current theme with getTheme().

This will do the trick in fragment, you can replace getActivity() with getBaseContext(), yourContext, etc which hold your current context

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
    yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}

*p.s : color is deprecated in M, but drawable is deprecated in L

submit form on click event using jquery

Using jQuery button click

$('#button_id').on('click',function(){
     $('#form_id').submit();
 });

Transmitting newline character "\n"

Use %0A (URL encoding) instead of \n (C encoding).

How does `scp` differ from `rsync`?

scp is best for one file.
OR a combination of tar & compression for smaller data sets like source code trees with small resources (ie: images, sqlite etc).


Yet, when you begin dealing with larger volumes say:

  • media folders (40 GB)
  • database backups (28 GB)
  • mp3 libraries (100 GB)

It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.

As an exercise, you can do some gymnastics like piping tar into ssh and redirecting the results into a remote file. (saving the need to build a swap or temporary clone aka zip or tar.gz)

However,

rsync simplify's this process and allows you to transfer data without consuming any additional disc space.

Also,

Continuous (cron?) updates use minimal changes vs full cloned copies speed up large data migrations over time.

tl;dr
scp == small scale (with room to build compressed files on the same drive)
rsync == large scale (with the necessity to backup large data and no room left)

HTTP test server accepting GET/POST requests

Just set one up yourself. Copy this snippet to your webserver.


echo "<pre>";
print_r($_POST);
echo "</pre>";

Just post what you want to that page. Done.

Git Bash doesn't see my PATH

Restart the computer after has added new value to PATH.

Resize image in the wiki of GitHub using Markdown

GitHub Pages now uses kramdown as its markdown engine so you can use the following syntax:

Here is an inline ![smiley](smiley.png){:height="36px" width="36px"}.

http://kramdown.gettalong.org/syntax.html#images

I haven't tested it on GitHub wiki though.

What determines the monitor my app runs on?

I'm fairly sure the primary monitor is the default. If the app was coded decently, when it's closed, it'll remember where it was last at and will reopen there, but -- as you've noticed -- it isn't a default behavior.

EDIT: The way I usually do it is to have the location stored in the app's settings. On load, if there is no value for them, it defaults to the center of the screen. On closing of the form, it records its position. That way, whenever it opens, it's where it was last. I don't know of a simple way to tell it to launch onto the second monitor the first time automatically, however.

-- Kevin Fairchild

Testing pointers for validity (C/C++)

On Unix you should be able to utilize a kernel syscall that does pointer checking and returns EFAULT, such as:

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdbool.h>

bool isPointerBad( void * p )
{
   int fh = open( p, 0, 0 );
   int e = errno;

   if ( -1 == fh && e == EFAULT )
   {
      printf( "bad pointer: %p\n", p );
      return true;
   }
   else if ( fh != -1 )
   {
      close( fh );
   }

   printf( "good pointer: %p\n", p );
   return false;
}

int main()
{
   int good = 4;
   isPointerBad( (void *)3 );
   isPointerBad( &good );
   isPointerBad( "/tmp/blah" );

   return 0;
}

returning:

bad pointer: 0x3
good pointer: 0x7fff375fd49c
good pointer: 0x400793

There's probably a better syscall to use than open() [perhaps access], since there's a chance that this could lead to actual file creation codepath, and a subsequent close requirement.

how to open a jar file in Eclipse

The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)

Use:

System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);

From the docs:

public static class EnvironmentVariablesExample
{
    [FunctionName("GetEnvironmentVariables")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
        log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
    }

    public static string GetEnvironmentVariable(string name)
    {
        return name + ": " +
            System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
    }
}

App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.

The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.

How to remove constraints from my MySQL table?

Mysql has a special syntax for dropping foreign key constraints:

ALTER TABLE tbl_magazine_issue
  DROP FOREIGN KEY FK_tbl_magazine_issue_mst_users

How to unpublish an app in Google Play Developer Console

Go to "Pricing & Distribution" and choose "Unpublish" option for "App Availability", please refer below youtube video

https://www.youtube.com/watch?v=XaH3X8ZD-l8

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

What is `related_name` used for in Django?

To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material

@with_author 
class BOM(models.Model): 
    name = models.CharField(max_length=200,null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tomaterial =  models.ForeignKey(Material, related_name = 'tomaterial')
    frommaterial =  models.ForeignKey(Material, related_name = 'frommaterial')
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    quantity = models.DecimalField(max_digits=19, decimal_places=10)

So when you will have to access this data you only can use related name

 bom = material.tomaterial.all().order_by('-creation_time')

It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)

Remove all elements contained in another array

If you're using Typescript and want to match on a single property value, this should work based on Craciun Ciprian's answer above.

You could also make this more generic by allowing non-object matching and / or multi-property value matching.

/**
 *
 * @param arr1 The initial array
 * @param arr2 The array to remove
 * @param propertyName the key of the object to match on
 */
function differenceByPropVal<T>(arr1: T[], arr2: T[], propertyName: string): T[] {
  return arr1.filter(
    (a: T): boolean =>
      !arr2.find((b: T): boolean => b[propertyName] === a[propertyName])
  );
}

Random number c++ in some range

Since nobody posted the modern C++ approach yet,

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(gen) << ' '; // generate numbers
}

How to push both key and value into an Array in Jquery

There are no keys in JavaScript arrays. Use objects for that purpose.

var obj = {};

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        obj[news.title] = news.link;
    });                      
});

// later:
$.each(obj, function (index, value) {
    alert( index + ' : ' + value );
});

In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).

However, In your case it is not really clear to me why you transfer data from the original object (data.news) at all. Why do you not simply pass a reference to that object around?


You can combine objects and arrays to achieve predictable iteration and key/value behavior:

var arr = [];

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        arr.push({
            title: news.title, 
            link:  news.link
        });
    });                      
});

// later:
$.each(arr, function (index, value) {
    alert( value.title + ' : ' + value.link );
});

Couldn't connect to server 127.0.0.1:27017

1.Create new folder in d drive D:/data/db

2.Open terminal on D:/data/db

3.Type mongod and enter.

4.Type mongo and enter.

and your mongodb has strated............

How can I check if a file exists in Perl?

if (-e $base_path)
{ 
 # code
}

-e is the 'existence' operator in Perl.

You can check permissions and other attributes using the code on this page.

OS X Framework Library not loaded: 'Image not found'

It was quite simple for me, i just added my framework to my embedded binaries under app targets

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

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

UserSelect =null

AlertDialog.Builder builder = new Builder(ImonaAndroidApp.LoginScreen);
            builder.setMessage("you message");
            builder.setPositiveButton("OK", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    UserSelect = true ;

                }
            });

            builder.setNegativeButton("Cancel", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    UserSelect = false ;

                }
            });
           // in UI thread
        builder.show();             
        // wait until the user select
            while(UserSelect ==null);

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Any time you get the...

"Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given"

...it is likely because there is an issue with your query. The prepare() or query() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!

First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:

error_reporting(E_ALL);
ini_set('display_errors', 1);

If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.

Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();

The error is generic and not very helpful to you in solving what is going on.

With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
    $query->bind_param('s', $definition);
    $query->execute();
    // any additional code you need would go here.
} else {
    $error = $mysqli->errno . ' ' . $mysqli->error; // 1054 Unknown column 'foo' in 'field list'
    // handle error
}

If something is wrong you can spit out an error message which takes you directly to the issue. In this case, there is no foo column in the table, solving the problem is trivial.

If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.

nginx upload client_max_body_size issue

nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size by sending a 413 response and closing the connection.

Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.

If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large response rather than 100 Continue if Content-Length exceeds the maximum body size.

Excel plot time series frequency with continuous xaxis

You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.

  1. Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.

  2. In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.) enter image description here

  3. You can format the x-axis options with this menu. (Chart->Design->Layout) enter image description here

  4. Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"

  5. Set up the options you wish. (Fix the starting and ending points.) enter image description here

  6. And you will get a graph such as the one below. enter image description here

You can then tweak many of the options, label the axes better etc, but this should get you started.

Hope this helps you move forward.

Putting GridView data in a DataTable

user this full solution to convert gridview to datatable

 public DataTable gridviewToDataTable(GridView gv)
        {

            DataTable dtCalculate = new DataTable("TableCalculator");

            // Create Column 1: Date
            DataColumn dateColumn = new DataColumn();
            dateColumn.DataType = Type.GetType("System.DateTime");
            dateColumn.ColumnName = "date";

            // Create Column 3: TotalSales
            DataColumn loanBalanceColumn = new DataColumn();
            loanBalanceColumn.DataType = Type.GetType("System.Double");
            loanBalanceColumn.ColumnName = "loanbalance";


            DataColumn offsetBalanceColumn = new DataColumn();
            offsetBalanceColumn.DataType = Type.GetType("System.Double");
            offsetBalanceColumn.ColumnName = "offsetbalance";


            DataColumn netloanColumn = new DataColumn();
            netloanColumn.DataType = Type.GetType("System.Double");
            netloanColumn.ColumnName = "netloan";


            DataColumn interestratecolumn = new DataColumn();
            interestratecolumn.DataType = Type.GetType("System.Double");
            interestratecolumn.ColumnName = "interestrate";

            DataColumn interestrateperdaycolumn = new DataColumn();
            interestrateperdaycolumn.DataType = Type.GetType("System.Double");
            interestrateperdaycolumn.ColumnName = "interestrateperday";

            // Add the columns to the ProductSalesData DataTable
            dtCalculate.Columns.Add(dateColumn);
            dtCalculate.Columns.Add(loanBalanceColumn);
            dtCalculate.Columns.Add(offsetBalanceColumn);
            dtCalculate.Columns.Add(netloanColumn);
            dtCalculate.Columns.Add(interestratecolumn);
            dtCalculate.Columns.Add(interestrateperdaycolumn);

            foreach (GridViewRow row in gv.Rows)
            {
                DataRow dr;
                dr = dtCalculate.NewRow();

                dr["date"] = DateTime.Parse(row.Cells[0].Text);
                dr["loanbalance"] = double.Parse(row.Cells[1].Text);
                dr["offsetbalance"] = double.Parse(row.Cells[2].Text);
                dr["netloan"] = double.Parse(row.Cells[3].Text);
                dr["interestrate"] = double.Parse(row.Cells[4].Text);
                dr["interestrateperday"] = double.Parse(row.Cells[5].Text);


                dtCalculate.Rows.Add(dr);
            }



            return dtCalculate;
        }

Python: avoiding pylint warnings about too many arguments

First, one of Perlis's epigrams:

"If you have a procedure with 10 parameters, you probably missed some."

Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.

Making an example up, because there's not enough information in the question to answer directly:

class PersonInfo(object):
  def __init__(self, name, age, iq):
    self.name = name
    self.age = age
    self.iq = iq

Then your 10 argument function:

def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7):
  ...

becomes:

def f(personinfo, x1, x2, x3, x4, x5, x6, x7):
  ...

and the caller changes to:

personinfo = PersonInfo(name, age, iq)
result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)

Run a php app using tomcat?

  1. Make sure you have php installed on your server
  2. Find the latest release of php-java-bridge off of sourceforge
  3. From the exploded directory on Sourceforge, download php-servlet.jar and JavaBridge.jar
  4. Place those jar files into webapp/WEB-INF/lib folder of your project
  5. Edit webapp/WEB-INF/web.xml to look like:

ok

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
   <filter>
      <filter-name>PhpCGIFilter</filter-name>
      <filter-class>php.java.servlet.PhpCGIFilter</filter-class>
   </filter>
   <filter-mapping>
      <filter-name>PhpCGIFilter</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
   <!-- the following adds the JSR223 listener. Remove it if you don't want to use the JSR223 API -->
   <listener>
      <listener-class>php.java.servlet.ContextLoaderListener</listener-class>
   </listener>
   <!-- the back end for external (console, Apache/IIS-) PHP scripts; remove it if you don't need this -->
   <servlet>
      <servlet-name>PhpJavaServlet</servlet-name>
      <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
   </servlet>
   <!-- runs PHP scripts in this web app; remove it if you don't need this -->
   <servlet>
      <servlet-name>PhpCGIServlet</servlet-name>
      <servlet-class>php.java.servlet.fastcgi.FastCGIServlet</servlet-class>
      <load-on-startup>0</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>PhpJavaServlet</servlet-name>
      <url-pattern>*.phpjavabridge</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
      <servlet-name>PhpCGIServlet</servlet-name>
      <url-pattern>*.php</url-pattern>
   </servlet-mapping>
</web-app>

You may have other content inside this file, just make sure you have added everything between the web-app tag.

  1. Add your php files to the webapp directory

You can do other special things with this as well. You cal learn more about it here: http://php-java-bridge.sourceforge.net/pjb/how_it_works.php

How to send an email with Gmail as provider using Python?

great answer from @David, here is for Python 3 without the generic try-except:

def send_email(user, password, recipient, subject, body):

    gmail_user = user
    gmail_pwd = password
    FROM = user
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_user, gmail_pwd)
    server.sendmail(FROM, TO, message)
    server.close()

Can't concatenate 2 arrays in PHP

Try array_merge.

$array1 = array('Item 1');

$array2 = array('Item 2');

$array3 = array_merge($array1, $array2);

I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.

how does Array.prototype.slice.call() work?

Let's assume you have: function.apply(thisArg, argArray )

The apply method invokes a function, passing in the object that will be bound to this and an optional array of arguments.

The slice() method selects a part of an array, and returns the new array.

So when you call Array.prototype.slice.apply(arguments, [0]) the array slice method is invoked (bind) on arguments.

How to define a variable in a Dockerfile?

To my knowledge, only ENV allows that, as mentioned in "Environment replacement"

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build.

In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.


This day, I use both ARG (docker 1.10+, and docker build --build-arg var=value) and ENV.
Using ARG alone means your variable is visible at build time, not at runtime.

My Dockerfile usually has:

ARG var
ENV var=${var}

In your case, ARG is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.

How to find foreign key dependencies in SQL Server?

After long search I found a working solution. My database does not use the sys.foreign_key_columns and the information_schema.key_column_usage only contain primary keys.

I use SQL Server 2015

SOLUTION 1 (rarely used)

If other solutions does not work, this will work fine:

        WITH CTE AS
        (
            SELECT 
                TAB.schema_id,
                TAB.name,
                COL.name AS COLNAME,
                COl.is_identity
            FROM 
                sys.tables TAB INNER JOIN sys.columns COL 
                    ON TAB.object_id = COL.object_id
        )
        SELECT 
            DB_NAME() AS [Database], 
            SCHEMA_NAME(Child.schema_id) AS 'Schema',
            Child.name AS 'ChildTable',
            Child.COLNAME AS 'ChildColumn',
            Parent.name AS 'ParentTable',
            Parent.COLNAME AS 'ParentColumn'
        FROM 
            cte Child INNER JOIN CTE Parent
                ON 
                    Child.COLNAME=Parent.COLNAME AND 
                    Child.name<>Parent.name AND 
                    Child.is_identity+1=Parent.is_identity

SOLUTION 2 (commonly used)

In most of the cases this will work just fine:

        SELECT
            DB_NAME() AS [Database], 
            SCHEMA_NAME(fk.schema_id) AS 'Schema',
            fk.name 'Name',
            tp.name 'ParentTable',
            cp.name 'ParentColumn',
            cp.column_id,
            tr.name 'ChildTable',
            cr.name 'ChildColumn',
            cr.column_id
        FROM
            sys.foreign_keys fk
        INNER JOIN
            sys.tables tp ON fk.parent_object_id = tp.object_id
        INNER JOIN
            sys.tables tr ON fk.referenced_object_id = tr.object_id
        INNER JOIN
            sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
        INNER JOIN
            sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
        INNER JOIN
            sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
        WHERE 
            -- CONCAT(SCHEMA_NAME(fk.schema_id), '.', tp.name, '.', cp.name) LIKE '%my_table_name%' OR
            -- CONCAT(SCHEMA_NAME(fk.schema_id), '.', tr.name, '.', cr.name) LIKE '%my_table_name%' 
        ORDER BY
            tp.name, cp.column_id

Listview Scroll to the end of the list after updating the list

Supposing you know when the list data has changed, you can manually tell the list to scroll to the bottom by setting the list selection to the last row. Something like:

private void scrollMyListViewToBottom() {
    myListView.post(new Runnable() {
        @Override
        public void run() {
            // Select the last row so it will scroll into view...
            myListView.setSelection(myListAdapter.getCount() - 1);
        }
    });
}

How to capture a JFrame's close button click event?

import javax.swing.JOptionPane;
import javax.swing.JFrame;

/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
        if (JOptionPane.showConfirmDialog(frame, 
            "Are you sure you want to close this window?", "Close Window?", 
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
            System.exit(0);
        }
    }
});

If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

What is cardinality in Databases?

Cardinality refers to the uniqueness of data contained in a column. If a column has a lot of duplicate data (e.g. a column that stores either "true" or "false"), it has low cardinality, but if the values are highly unique (e.g. Social Security numbers), it has high cardinality.

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

Visual Studio Code: Auto-refresh file changes

VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.

There is currently no way to disable this behaviour.

Printing Lists as Tabular Data

I found this just looking for a way to output simple columns. If you just need no-fuss columns, then you can use this:

print("Titlex\tTitley\tTitlez")
for x, y, z in data:
    print(x, "\t", y, "\t", z)

EDIT: I was trying to be as simple as possible, and thereby did some things manually instead of using the teams list. To generalize to the OP's actual question:

#Column headers
print("", end="\t")
for team in teams_list:
    print(" ", team, end="")
print()
# rows
for team, row in enumerate(data):
    teamlabel = teams_list[team]
    while len(teamlabel) < 9:
        teamlabel = " " + teamlabel
    print(teamlabel, end="\t")
    for entry in row:
        print(entry, end="\t")
    print()

Ouputs:

          Man Utd  Man City  T Hotspur
  Man Utd       1       2       1   
 Man City       0       1       0   
T Hotspur       2       4       2   

But this no longer seems any more simple than the other answers, with perhaps the benefit that it doesn't require any more imports. But @campkeith's answer already met that and is more robust as it can handle a wider variety of label lengths.

What is meant by the term "hook" in programming?

Essentially it's a place in code that allows you to tap in to a module to either provide different behavior or to react when something happens.

Format a datetime into a string with milliseconds

@Cabbi raised the issue that on some systems, the microseconds format %f may give "0", so it's not portable to simply chop off the last three characters.

The following code carefully formats a timestamp with milliseconds:

from datetime import datetime
(dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')
dt = "%s.%03d" % (dt, int(micro) / 1000)
print dt

Example Output:

2016-02-26 04:37:53.133

To get the exact output that the OP wanted, we have to strip punctuation characters:

from datetime import datetime
(dt, micro) = datetime.utcnow().strftime('%Y%m%d%H%M%S.%f').split('.')
dt = "%s%03d" % (dt, int(micro) / 1000)
print dt

Example Output:

20160226043839901

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution

  1. Right click on installer(.exe)
  2. Select properties option.
  3. Click on checkbox to check Unblock at the bottom of Properties.

This solution work for Heroku CLI (heroku-x64) installer(.exe)

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

How can I get a uitableViewCell by indexPath?

You can use the following code to get last cell.

UITableViewCell *cell = [tableView cellForRowAtIndexPath:lastIndexPath];

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Try

ALLOWED_HOSTS = ['*']

Less secure if you're not firewalled off or on a public LAN, but it's what I use and it works.

EDIT: Interestingly enough I've been needing to add this to a few of my 1.8 projects even when DEBUG = True. Very unsure why.

EDIT: This is due to a Django security update as mentioned in my comment.

Super-simple example of C# observer/observable with delegates

    /**********************Simple Example ***********************/    

class Program
        {
            static void Main(string[] args)
            {
                Parent p = new Parent();
            }
        }

        ////////////////////////////////////////////

        public delegate void DelegateName(string data);

        class Child
        {
            public event DelegateName delegateName;

            public void call()
            {
                delegateName("Narottam");
            }
        }

        ///////////////////////////////////////////

        class Parent
        {
            public Parent()
            {
                Child c = new Child();
                c.delegateName += new DelegateName(print);
                //or like this
                //c.delegateName += print;
                c.call();
            }

            public void print(string name)
            {
                Console.WriteLine("yes we got the name : " + name);
            }
        }

Using success/error/finally/catch with Promises in AngularJS

I think the previous answers are correct, but here is another example (just a f.y.i, success() and error() are deprecated according to AngularJS Main page:

$http
    .get('http://someendpoint/maybe/returns/JSON')
    .then(function(response) {
        return response.data;
    }).catch(function(e) {
        console.log('Error: ', e);
        throw e;
    }).finally(function() {
        console.log('This finally block');
    });

Check if enum exists in Java

You can also use Guava and do something like this:

// This method returns enum for a given string if it exists, otherwise it returns default enum.
private MyEnum getMyEnum(String enumName) {
  // It is better to return default instance of enum instead of null
  return hasMyEnum(enumName) ? MyEnum.valueOf(enumName) : MyEnum.DEFAULT;
}

// This method checks that enum for a given string exists.
private boolean hasMyEnum(String enumName) {
  return Iterables.any(Arrays.asList(MyEnum.values()), new Predicate<MyEnum>() {
    public boolean apply(MyEnum myEnum) {
      return myEnum.name().equals(enumName);
    }
  }); 
}

In second method I use guava (Google Guava) library which provides very useful Iterables class. Using the Iterables.any() method we can check if a given value exists in a list object. This method needs two parameters: a list and Predicate object. First I used Arrays.asList() method to create a list with all enums. After that I created new Predicate object which is used to check if a given element (enum in our case) satisfies the condition in apply method. If that happens, method Iterables.any() returns true value.

API vs. Webservice

another example: google map api vs google direction api web service, while the former serves (delivers) javascript file to the site (which can then be used as an api to make new functions) , the later is a Rest web service delivering data (in json or xml format), which can be processed (but not used in an api sense).

Android Studio Rendering Problems : The following classes could not be found

I faced this error when I created second activity in my project in the newly updated Android Studio,I solved it simply by copy pasting the whole xml code from first layout to the second and then I just removed the code that's unnecessary.

How to list only the file names that changed between two commits?

git diff --name-only SHA1 SHA2

where you only need to include enough of the SHA to identify the commits. You can also do, for example

git diff --name-only HEAD~10 HEAD~5

to see the differences between the tenth latest commit and the fifth latest (or so).

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

1067 error on attempt to start MySQL

I ran into the same errors. Similar approach for me. From what I can tell, there is something weird going on with the reference to the datadir in the my.ini file. Even when I manually edited it I could not seem to have any effect on it, until I blew EVERYTHING AWAY. Wish I had better news...do a DB backup first.

For me the key to getting this to work was:

1) Remove the previous installation from settings->control panel. Restart your machine.

2) Once machine comes back up, forcefully delete the previous installation directory. [mine is C:\apps\MySQL\MySQLServer-5.5\, as I REFUSE to use c:\program files\..]

3) Forcefully delete the previous datadir directory [mine was c:\data\mysql].

4) Forcefully delete the previous default data directory [C:\Documents and Settings\All Users\Application Data\MySQL].

5) Re-run the install, selected the same installation directory. Skip the instance configurator/wizard at the end of the install.

6) Make sure the ../bin directory gets added to the path. Verify it.

7) Manually run the instance configurator/wizard.
Set the root password, port [3306]. It will try to start it. Again, mine FAILED to start [duh! nothing new there!!!]

8) Now, manually edit the my.ini file in the install directory, and correct the datadir setting to be [datadir="C:/Data/MySQL/"] MATCH CAPITALIZATION !!!!

9) Verify the service is setup correctly via the command-prompt [sc qc mysql <enter>].
Should look like:

C:\dev\cmdz>sc qc mysql

[SC] GetServiceConfig SUCCESS

SERVICE_NAME: mysql
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : "C:\apps\MySQL\MySQLServer-5.5\bin\mysqld" --defaults-file="C:\apps\MySQL\MySQLServer-5.5\my.ini" MySQL
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : MySQL
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

10) Copy the contents of the default data-directory created under C:\Documents and Settings\All Users\Application Data\MySQL [basically everything in this directory to your desired data directory c:\data\mysql]. Make sure you get the C:\Documents and Settings\All Users\Application Data\MySQL\mysql directory. This has host.frm file, and others.
You should end up with a directory now of c:\data\MySQL\mysql...

11) Rename the default directory C:\Documents and Settings\All Users\Application Data\MySQL To C:\Documents and Settings\All Users\Application Data\MySQLxxx So it cannot find it...

12) Say a quick prayer...

13) Give it a kick start from command line with [net start mysql]

That got it working for me...

Best of Luck!

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

I ran in to this with React when setting state and using map.

In this case I was making an API fetch call and the value of the response wasn't known, but should have a value "Answer". I used a custom type for this, but because the value could be null, I got a TS error anyway. Allowing the type to be null doesn't fix it; alternatively you could use a default parameter value, but this was messy for my case.

I overcame it by providing a default value in the event the response was empty by just using a ternary operator:

this.setState({ record: (response.Answer) ? response.Answer : [{ default: 'default' }] });

PostgreSQL error: Fatal: role "username" does not exist

Use the operating system user postgres to create your database - as long as you haven't set up a database role with the necessary privileges that corresponds to your operating system user of the same name (h9uest in your case):

sudo -u postgres -i

As recommended here or here.

Then try again. Type exit when done with operating as system user postgres.

Or execute the single command createuser as postgres with sudo, like demonstrated by drees in another answer.

The point is to use the operating system user matching the database role of the same name to be granted access via ident authentication. postgres is the default operating system user to have initialized the database cluster. The manual:

In order to bootstrap the database system, a freshly initialized system always contains one predefined role. This role is always a ā€œsuperuserā€, and by default (unless altered when running initdb) it will have the same name as the operating system user that initialized the database cluster. Customarily, this role will be named postgres. In order to create more roles you first have to connect as this initial role.

I have heard of odd setups with non-standard user names or where the operating system user does not exist. You'd need to adapt your strategy there.

Read about database roles and client authentication in the manual.

Fastest way to determine if record exists

Don't think anyone has mentioned it yet, but if you are sure the data won't change underneath you, you may want to also apply the NoLock hint to ensure it is not blocked when reading.

SELECT CASE WHEN EXISTS (SELECT 1 
                     FROM dbo.[YourTable] WITH (NOLOCK)
                     WHERE [YourColumn] = [YourValue]) 
        THEN CAST (1 AS BIT) 
        ELSE CAST (0 AS BIT) END

SQL Server insert if not exists best practice

Another option is to left join your Results table with your existing competitors Table and find the new competitors by filtering the distinct records that donĀ“t match int the join:

INSERT Competitors (cName)
SELECT  DISTINCT cr.Name
FROM    CompResults cr left join
        Competitors c on cr.Name = c.cName
where   c.cName is null

New syntax MERGE also offer a compact, elegant and efficient way to do that:

MERGE INTO Competitors AS Target
USING (SELECT DISTINCT Name FROM CompResults) AS Source ON Target.Name = Source.Name
WHEN NOT MATCHED THEN
    INSERT (Name) VALUES (Source.Name);

SQL to LINQ Tool

Bill Horst's - Converting SQL to LINQ is a very good resource for this task (as well as LINQPad).

LINQ Tools has a decent list of tools as well but I do not believe there is anything else out there that can do what Linqer did.


Generally speaking, LINQ is a higher-level querying language than SQL which can cause translation loss when trying to convert SQL to LINQ. For one, LINQ emits shaped results and SQL flat result sets. The issue here is that an automatic translation from SQL to LINQ will often have to perform more transliteration than translation - generating examples of how NOT to write LINQ queries. For this reason, there are few (if any) tools that will be able to reliably convert SQL to LINQ. Analogous to learning C# 4 by first converting VB6 to C# 4 and then studying the resulting conversion.

How to show grep result with complete path or file name

For me

grep -b "searchsomething" *.log

worked as I wanted

How to use BOOLEAN type in SELECT statement

Compile this in your database and start using boolean statements in your querys.

note: the function get's a varchar2 param, so be sure to wrap any "strings" in your statement. It will return 1 for true and 0 for false;

select bool('''abc''<''bfg''') from dual;

CREATE OR REPLACE function bool(p_str in varchar2) return varchar2 
 is
 begin

 execute immediate ' begin if '||P_str||' then
          :v_res :=  1;
       else
          :v_res :=  0;
       end if; end;' using out v_res;

       return v_res;

 exception 
  when others then 
    return '"'||p_str||'" is not a boolean expr.';
 end;
/

Use own username/password with git and bitbucket

Run

git remote -v

and check whether your origin's URL has your co-worker's username hardcoded in there. If so, substitute it with your own:

git remote set-url origin <url-with-your-username>

Can I use VARCHAR as the PRIMARY KEY?

It is ok for sure. With just few hundred of entries, it will be fast.

You can add an unique id as as primary key (int autoincrement) ans set your coupon_code as unique. So if you need to do request in other tables it's better to use int than varchar

Hide div by default and show it on click with bootstrap

Try this one:

<button class="button" onclick="$('#target').toggle();">
    Show/Hide
</button>
<div id="target" style="display: none">
    Hide show.....
</div>

Detecting Enter keypress on VB.NET

I have test this code on Visual Studio 2019

Its working superb

Just Paste it into you form code

it will work on all textboxs on same form

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
    Dim keyCode As Keys = CType(msg.WParam, IntPtr).ToInt32
    Const WM_KEYDOWN As Integer = &H100

    If msg.Msg = WM_KEYDOWN AndAlso keyCode = Keys.Enter _
     AndAlso Me.ActiveControl.GetType.Name = "TextBox" Then
        Me.SelectNextControl(Me.ActiveControl, True, True, False, True)
        Return True

    End If
    Return MyBase.ProcessCmdKey(msg, keyData)


End Function

Float a DIV on top of another DIV

I know this post is little bit old but here is a potential solution for anyone who has the same problem:

First, I would change the CSS display for #popup to "none" instead of "hidden".

Second, I would change the HTML as follow:

<div id="overlay-back"></div>
<div id="popup">
    <div style="position: relative;">
        <img class="close-image" src="images/closebtn.png" />
        <span><img src="images/load_sign.png" width="400" height="566" /></span>
    </div>            
</div>

And for Style as follow:

.close-image
{
   display: block;
   float: right;
   cursor: pointer;
   z-index: 3;
   position: absolute;
   right: 0;
   top: 0;
}

I got this idea from this website (kessitek.com). A very good example on how to position elements,:

How to position a div on top of another div

I hope this helps,

Zag,

How can I jump to class/method definition in Atom text editor?

I believe the problem with "go to" packages is that they would work diferently for each language.

If you use Javascript js-hyperclick and hyperclick (since code-links is deprecated) may do what you need.


Use symbols-view package which let your search and jump to functions declaration but just of current opened file. Unfortunately, I don't know of any other language's equivalent.

There is also another package which could be useful for go-to in Python: python-tools

As of May 2016, recent version of Atom now support "Go-To" natively. At the GitHub repo for this module you get a list of the following keys:

  • symbols-view:toggle-file-symbols to Show all symbols in current file
  • symbols-view:toggle-project-symbols to Show all symbols in the project
  • symbols-view:go-to-declaration to Jump to the symbol under the cursor
  • symbols-view:return-from-declaration to Return from the jump

screenshot

I now only have one thing missing with Atom for this: mouse click bindings. There's an open issue on Github if anyone want to follow that feature.

Allowing Untrusted SSL Certificates with HttpClient

I don't have an answer, but I do have an alternative.

If you use Fiddler2 to monitor traffic AND enable HTTPS Decryption, your development environment will not complain. This will not work on WinRT devices, such as Microsoft Surface, because you cannot install standard apps on them. But your development Win8 computer will be fine.

To enable HTTPS encryption in Fiddler2, go to Tools > Fiddler Options > HTTPS (Tab) > Check "Decrypt HTTPS Traffic".

I'm going to keep my eye on this thread hoping for someone to have an elegant solution.

Converting stream of int's to char's in java

Simple casting:

int a = 99;
char c = (char) a;

Is there any reason this is not working for you?

libxml install error using pip

I solved this issue by increasing my server ram.

I was running only 512 MB and when I upgraded to 1 GB I had no problem.

I also installed every package manually prior to this in an attempt to fix the problem, but I'm not sure whether this is a necessary step.

Can you blur the content beneath/behind a div?

If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before

//HTML

<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
    <div class="morph-button morph-button-overlay morph-button-fixed">
        <button id="user-interface" type="button">MORE INFO</button>
        <!--a id="user-interface" href="javascript:void(0)">popup</a-->
        <div class="morph-content">
            <div>
                <div class="content-style-overlay">
                    <span class="icon icon-close">Close the overlay</span>
                    <h2>About Parsley</h2>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                </div>
            </div>
        </div>
    </div>
</div>

//CSS

/* Blur - doesn't work on IE */

.blur-on, .blur-element {
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    filter: blur(10px);

    -webkit-transition: all 5s linear;
    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}
.blur-off {
    -webkit-filter: blur(0px) !important;
    -moz-filter   : blur(0px) !important;
    -o-filter     : blur(0px) !important;
    -ms-filter    : blur(0px) !important;
    filter        : blur(0px) !important;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    height: 20%; width: 20%;
    background-size: cover;
    background: inherit;
    z-index: -1;

    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);       
    -moz-transform: scale(5);
    -moz-transform-origin: top left;
    -moz-filter: blur(2px);       
    -webkit-transform: scale(5);
    -webkit-transform-origin: top left;
    -webkit-filter: blur(2px);
    -o-transform: scale(5);
    -o-transform-origin: top left;
    -o-filter: blur(2px);       

    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}


//Javascript

function blurBehindPopup() {
    if(blurredElements.length == 0) {
        for(var i=0; i < document.body.children.length; i++) {
            var element = document.body.children[i];
            if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
                classie.addClass( element, 'blur-element' );
                blurredElements.push(element);
            }
        }
    } else {
        for(var i=0; i < blurredElements.length; i++) {
            classie.addClass( blurredElements[i], 'blur-element' );
        }
    }
}
function unblurBehindPopup() {
    for(var i=0; i < blurredElements.length; i++) {
        classie.removeClass( blurredElements[i], 'blur-element' );
    }
}

Full Working Example Link

How can I set a custom date time format in Oracle SQL Developer?

In my case the format set in Preferences/Database/NLS was [Date Format] = RRRR-MM-DD HH24:MI:SSXFF but in grid there were seen 8probably default format RRRR/MM/DD (even without time) The format has changed after changing the setting [Date Format] to: RRRR-MM-DD HH24:MI:SS (without 'XFF' at the end).

There were no errors, but format with xff at the end didn't work.

Note: in polish notation RRRR means YYYY

how to check if a datareader is null or empty

In addition to the suggestions given, you can do this directly from your query like this -

SELECT ISNULL([Additional], -1) AS [Additional]

This way you can write the condition to check whether the field value is < 0 or >= 0.

Oracle TNS names not showing when adding new connection to SQL Developer

None of the above changes made any difference in my case. I could run TNS_PING in the command window but SQL Developer couldn't figure out where tnsnames.ora was.

The issue in my case (Windows 7 - 64 bit - Enterprise ) was that the Oracle installer pointed the Start menu shortcut to the wrong version of SQL Developer. There appear to be three SQL Developer instances that accompany the installer. One is in %ORACLE_HOME%\client_1\sqldeveloper\ and two are in %ORACLE_HOME%\client_1\sqldeveloper\bin\ .

The installer installed a start menu shortcut that pointed at a version in the bin directory that simply did not function. It would ask for a password every time I started SQL Developer, not remember choices I had made and displayed a blank list when I chose TNS as the connection mechanism. It also does not have the TNS Directory field in the Database advanced settings referenced in other posts.

I tossed the old Start shortcut and installed a shortcut to %ORACLE_HOME%\client_1\sqldeveloper\sqldeveloper.exe . That change fixed the problem in my case.

How can I run PowerShell with the .NET 4 runtime?

Actually, you can get PowerShell to run using .NET 4 without affecting other .NET applications. I needed to do so to use the new HttpWebRequest "Host" property, however changing the "OnlyUseLatestCLR" broke Fiddler as that could not be used under .NET 4.

The developers of PowerShell obviously foresaw this happening, and they added a registry key to specify what version of the Framework it should use. One slight issue is that you need to take ownership of the registry key before changing it, as even administrators do not have access.

  • HKLM:\Software\Microsoft\Powershell\1\PowerShellEngine\RuntimeVersion (64 bit and 32 bit)
  • HKLM:\Software\Wow6432Node\Microsoft\Powershell\1\PowerShellEngine\RuntimeVersion (32 bit on 64 bit machine)

Change the value of that key to the required version. Keep in mind though that some snapins may no longer load unless they are .NET 4 compatible (WASP is the only one I have had trouble with, but I don't really use it anyway). VMWare, SQL Server 2008, PSCX, Active Directory (Microsoft and Quest Software) and SCOM all work fine.

How to initialize a two-dimensional array in Python?

You can use a list comprehension:

x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Just finally fixed this for my single solution that was having this. Two of the projects in the solution were set as sites in IIS. I went in and enabled ASP.Net Impersonation under Authentication for both projects...and VIOLA! FINALLY, no more of this annoying error!

It is more efficient to use if-return-return or if-else-return?

With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.

Why Response.Redirect causes System.Threading.ThreadAbortException?

Also I tried other solution, but some of the code executed after redirect.

public static void ResponseRedirect(HttpResponse iResponse, string iUrl)
    {
        ResponseRedirect(iResponse, iUrl, HttpContext.Current);
    }

    public static void ResponseRedirect(HttpResponse iResponse, string iUrl, HttpContext iContext)
    {
        iResponse.Redirect(iUrl, false);

        iContext.ApplicationInstance.CompleteRequest();

        iResponse.BufferOutput = true;
        iResponse.Flush();
        iResponse.Close();
    }

So if need to prevent code execution after redirect

try
{
   //other code
   Response.Redirect("")
  // code not to be executed
}
catch(ThreadAbortException){}//do there id nothing here
catch(Exception ex)
{
  //Logging
}

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Just adding some more info that solved the problem for me:

  • Make sure that the %M2% and %M2_HOME% variables doesn't have the semicolon (;) at the end. This should only be used if there are more than one location in that path, which is not the case;
  • Also, make sure that in the "Path" variable, there aren't any spaces between the various paths, separated by the semicolon.

Thanks to Pawan Valecha and Abhijeet Sawant for the tips.

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

The microsoft telnet.exe is not scriptable without using another script (which needs keyboard focus), as shown in another answer to this question, but there is a free

Telnet Scripting Tool v.1.0 by Albert Yale

that you can google for and which is both scriptable and loggable and can be launched from a batch file without needing keyboard focus.

The problem with telnet.exe and a second script when keyboard focus is being used is that if someone is using the computer at the time the script runs, then it is highly likely that the script will fail due to mouse clicks and keyboard use at that moment in time.

Reading Email using Pop3 in C#

I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.

Also, the project is mostly dormant... the last release was in 2004.

For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.

Transfer data between databases with PostgreSQL

Databases are isolated in PostgreSQL; when you connect to a PostgreSQL server you connect to just one database, you can't copy data from one database to another using a SQL query.

If you come from MySQL: what MySQL calls (loosely) "databases" are "schemas" in PostgreSQL - sort of namespaces. A PostgreSQL database can have many schemas, each one with its tables and views, and you can copy from one schema to another with the schema.table syntax.

If you really have two distinct PostgreSQL databases, the common way of transferring data from one to another would be to export your tables (with pg_dump -t ) to a file, and import them into the other database (with psql).

If you really need to get data from a distinct PostgreSQL database, another option - mentioned in Grant Johnson's answer - is dblink, which is an additional module (in contrib/).

Update:

Postgres introduced "foreign data wrapper" in 9.1 (which was released after the question was asked). Foreign data wrappers allow the creation of foreign tables through the Postgres FDW which makes it possible to access a remote table (on a different server and database) as if it was a local table.

AlertDialog.Builder with custom layout and EditText; cannot access view

Use this one

   AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    // Get the layout inflater
    LayoutInflater inflater = (activity).getLayoutInflater();
    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the
    // dialog layout
    builder.setTitle(title);
    builder.setCancelable(false);
    builder.setIcon(R.drawable.galleryalart);
    builder.setView(inflater.inflate(R.layout.dialogue, null))
    // Add action buttons
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    }
                }
            });
    builder.create();
    builder.show();

Overriding fields or properties in subclasses

If you are building a class and you want there to be a base value for the property, then use the virtual keyword in the base class. This allows you to optionally override the property.

Using your example above:

//you may want to also use interfaces.
interface IFather
{
    int MyInt { get; set; }
}


public class Father : IFather
{
    //defaulting the value of this property to 1
    private int myInt = 1;

    public virtual int MyInt
    {
        get { return myInt; }
        set { myInt = value; }
    }
}

public class Son : Father
{
    public override int MyInt
    {
        get {

            //demonstrating that you can access base.properties
            //this will return 1 from the base class
            int baseInt = base.MyInt;

            //add 1 and return new value
            return baseInt + 1;
        }
        set
        {
            //sets the value of the property
            base.MyInt = value;
        }
    }
}

In a program:

Son son = new Son();
//son.MyInt will equal 2

How to install and run phpize

Step - 1: If you are unsure about the php version installed, then first run the following command in terminal

php -v

Output: the above command will output the php version installed on your machine, mine is 7.2

PHP 7.2.3-1ubuntu1 (cli) (built: Mar 14 2018 22:03:58) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.3-1ubuntu1, Copyright (c) 1999-2018, by Zend Technologies

Step 2: Then to install phpize run the following command, Since my php version is 7.2.3. i will replace it with 7.2, so the command will be,

sudo apt-get install php7.2-dev

Step 3: Done!

Alternate method(Optional): To automatically install the phpize version based on the php version installed on your machine run the following command.

sudo apt-get install php-dev

This command will automatically detect the appropriate version of php installed and will install the matching phpize for the same.

How to sort a data frame by alphabetic order of a character variable in R?

This really belongs with @Ramnath's answer but I can't comment as I don't have enough reputation yet. You can also use the arrange function from the dplyr package in the same way as the plyr package.

library(dplyr)
arrange(DF, ID, desc(num))

C# Passing Function as Argument

Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:

public delegate double MyFunction(double x);

public double Diff(double x, MyFunction f)
{
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

public double MyFunctionMethod(double x)
{
    // Can add more complicated logic here
    return x + 10;
}

public void Client()
{
    double result = Diff(1.234, x => x * 456.1234);
    double secondResult = Diff(2.345, MyFunctionMethod);
}

How to force open links in Chrome not download them?

Just found your question whilst trying to solve another problem I'm having, you will find that currently Google isn't able to perform a temporary download so therefore you have to download instead.

See: http://productforums.google.com/forum/#!topic/chrome/Drge_Zrwg-c

How to display two digits after decimal point in SQL Server

You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.

SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name

Window.open and pass parameters by post method

I created a function to generate a form, based on url, target and an object as the POST/GET data and submit method. It supports nested and mixed types within that object, so it can fully replicate any structure you feed it: PHP automatically parses it and returns it as a nested array. However, there is a single restriction: the brackets [ and ] must not be part of any key in the object (like {"this [key] is problematic" : "hello world"}). If someone knows how to escape it properly, please do tell!

Without further ado, here is the source:

_x000D_
_x000D_
function getForm(url, target, values, method) {_x000D_
  function grabValues(x) {_x000D_
    var path = [];_x000D_
    var depth = 0;_x000D_
    var results = [];_x000D_
_x000D_
    function iterate(x) {_x000D_
      switch (typeof x) {_x000D_
        case 'function':_x000D_
        case 'undefined':_x000D_
        case 'null':_x000D_
          break;_x000D_
        case 'object':_x000D_
          if (Array.isArray(x))_x000D_
            for (var i = 0; i < x.length; i++) {_x000D_
              path[depth++] = i;_x000D_
              iterate(x[i]);_x000D_
            }_x000D_
          else_x000D_
            for (var i in x) {_x000D_
              path[depth++] = i;_x000D_
              iterate(x[i]);_x000D_
            }_x000D_
          break;_x000D_
        default:_x000D_
          results.push({_x000D_
            path: path.slice(0),_x000D_
            value: x_x000D_
          })_x000D_
          break;_x000D_
      }_x000D_
      path.splice(--depth);_x000D_
    }_x000D_
    iterate(x);_x000D_
    return results;_x000D_
  }_x000D_
  var form = document.createElement("form");_x000D_
  form.method = method;_x000D_
  form.action = url;_x000D_
  form.target = target;_x000D_
_x000D_
  var values = grabValues(values);_x000D_
_x000D_
  for (var j = 0; j < values.length; j++) {_x000D_
    var input = document.createElement("input");_x000D_
    input.type = "hidden";_x000D_
    input.value = values[j].value;_x000D_
    input.name = values[j].path[0];_x000D_
    for (var k = 1; k < values[j].path.length; k++) {_x000D_
      input.name += "[" + values[j].path[k] + "]";_x000D_
    }_x000D_
    form.appendChild(input);_x000D_
  }_x000D_
  return form;_x000D_
}
_x000D_
_x000D_
_x000D_

Usage example:

_x000D_
_x000D_
document.body.onclick = function() {_x000D_
  var obj = {_x000D_
    "a": [1, 2, [3, 4]],_x000D_
    "b": "a",_x000D_
    "c": {_x000D_
      "x": [1],_x000D_
      "y": [2, 3],_x000D_
      "z": [{_x000D_
        "a": "Hello",_x000D_
        "b": "World"_x000D_
      }, {_x000D_
        "a": "Hallo",_x000D_
        "b": "Welt"_x000D_
      }]_x000D_
    }_x000D_
  };_x000D_
_x000D_
  var form = getForm("http://example.com", "_blank", obj, "post");_x000D_
_x000D_
  document.body.appendChild(form);_x000D_
  form.submit();_x000D_
  form.parentNode.removeChild(form);_x000D_
}
_x000D_
_x000D_
_x000D_

Golang read request body

I could use the GetBody from Request package.

Look this comment in source code from request.go in net/http:

GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."

GetBody func() (io.ReadCloser, error)

This way you can get the body request without make it empty.

Sample:

getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
    // Do something return err
}
http.DefaultClient.Do(request)

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

But, sometimes, even with user-select and touch-callout turned off, cursor: pointer; may cause this effect, so, just set cursor: default; and it'll work.

How to set a value to a file input in HTML?

Not an answer to your question (which others have answered), but if you want to have some edit functionality of an uploaded file field, what you probably want to do is:

  • show the current value of this field by just printing the filename or URL, a clickable link to download it, or if it's an image: just show it, possibly as thumbnail
  • the <input> tag to upload a new file
  • a checkbox that, when checked, deletes the currently uploaded file. note that there's no way to upload an 'empty' file, so you need something like this to clear out the field's value

create table with sequence.nextval in oracle

In Oracle 12c you can also declare an identity column

CREATE TABLE identity_test_tab (
  id          NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  description VARCHAR2(30)
);

examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.

Java Returning method which returns arraylist?

1. If that class from which you want to call this method, is in the same package, then create an instance of this class and call the method.

2. Use Composition

3. It would be better to have a Generic ArrayList like ArrayList<Integer> etc...

eg:

public class Test{

public ArrayList<Integer> myNumbers()    {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(11);
    numbers.add(3);
    return(numbers);
 }
}


public class T{


public static void main(String[] args){

   Test t = new Test();
   ArrayList<Integer> arr = t.myNumbers();        // You can catch the returned integer arraylist into an arraylist.
 }


}

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

How do I find out which process is locking a file using .NET?

This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.

C#:

using System.Management; 
using System.IO;   

static class Module1 
{ 
static internal ArrayList myProcessArray = new ArrayList(); 
private static Process myProcess; 

public static void Main() 
{ 

    string strFile = "c:\\windows\\system32\\msi.dll"; 
    ArrayList a = getFileProcesses(strFile); 
    foreach (Process p in a) { 
        Debug.Print(p.ProcessName); 
    } 
} 


private static ArrayList getFileProcesses(string strFile) 
{ 
    myProcessArray.Clear(); 
    Process[] processes = Process.GetProcesses; 
    int i = 0; 
    for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) { 
        myProcess = processes(i); 
        if (!myProcess.HasExited) { 
            try { 
                ProcessModuleCollection modules = myProcess.Modules; 
                int j = 0; 
                for (j = 0; j <= modules.Count - 1; j++) { 
                    if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) { 
                        myProcessArray.Add(myProcess); 
                        break; // TODO: might not be correct. Was : Exit For 
                    } 
                } 
            } 
            catch (Exception exception) { 
            } 
            //MsgBox(("Error : " & exception.Message)) 
        } 
    } 
    return myProcessArray; 
} 
} 

VB.Net:

Imports System.Management
Imports System.IO

Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process

Sub Main()

    Dim strFile As String = "c:\windows\system32\msi.dll"
    Dim a As ArrayList = getFileProcesses(strFile)
    For Each p As Process In a
        Debug.Print(p.ProcessName)
    Next
End Sub


Private Function getFileProcesses(ByVal strFile As String) As ArrayList
    myProcessArray.Clear()
    Dim processes As Process() = Process.GetProcesses
    Dim i As Integer
    For i = 0 To processes.GetUpperBound(0) - 1
        myProcess = processes(i)
        If Not myProcess.HasExited Then
            Try
                Dim modules As ProcessModuleCollection = myProcess.Modules
                Dim j As Integer
                For j = 0 To modules.Count - 1
                    If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
                        myProcessArray.Add(myProcess)
                        Exit For
                    End If
                Next j
            Catch exception As Exception
                'MsgBox(("Error : " & exception.Message))
            End Try
        End If
    Next i
    Return myProcessArray
End Function
End Module

How can I run multiple npm scripts in parallel?

In a package.json in the parent folder:

"dev": "(cd api && start npm run start) & (cd ../client && start npm run start)"

this work in windows

Create a table without a header in Markdown

Universal Solution

Many of the suggestions unfortunately do not work for all Markdown viewers/editors, for instance, the popular Markdown Viewer Chrome extension, but they do work with iA Writer.

What does seem to work across both of these popular programs (and might work for your particular application) is to use HTML comment blocks ('<!-- -->'):

| <!-- -->    | <!-- -->    |
|-------------|-------------|
| Foo         | Bar         |

Like some of the earlier suggestions stated, this does add an empty header row in your Markdown viewer/editor. In iA Writer, it's aesthetically small enough that it doesn't get in my way too much.

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

In order to simulate the issue that you are facing, I created the following sample using SSIS 2008 R2 with SQL Server 2008 R2 backend. The example is based on what I gathered from your question. This example doesn't provide a solution but it might help you to identify where the problem could be in your case.

Created a simple CSV file with two columns namely order number and order date. As you had mentioned in your question, values of both the columns are qualified with double quotes (") and also the lines end with Line Feed (\n) with the date being the last column. The below screenshot was taken using Notepad++, which can display the special characters in a file. LF in the screenshot denotes Line Feed.

Orders file

Created a simple table named dbo.Destination in the SQL Server database to populate the CSV file data using SSIS package. Create script for the table is given below.

CREATE TABLE [dbo].[Destination](
    [OrderNumber] [varchar](50) NULL,
    [OrderDate] [date] NULL
) ON [PRIMARY]
GO

On the SSIS package, I created two connection managers. SQLServer was created using the OLE DB Connection to connect to the SQL Server database. FlatFile is a flat file connection manager.

Connections

Flat file connection manager was configured to read the CSV file and the settings are shown below. The red arrows indicate the changes made.

Provided a name to the flat file connection manager. Browsed to the location of the CSV file and selected the file path. Entered the double quote (") as the text qualifier. Changed the Header row delimiter from {CR}{LF} to {LF}. This header row delimiter change also reflects on the Columns section.

Flat File General

No changes were made in the Columns section.

Flat File Columns

Changed the column name from Column0 to OrderNumber.

Advanced column OrderNumber

Changed the column name from Column1 to OrderDate and also changed the data type to date [DT_DATE]

Advanced column OrderDate

Preview of the data within the flat file connection manager looks good.

Data Preview

On the Control Flow tab of the SSIS package, placed a Data Flow Task.

Control Flow

Within the Data Flow Task, placed a Flat File Source and an OLE DB Destination.

Data Flow Task

The Flat File Source was configured to read the CSV file data using the FlatFile connection manager. Below three screenshots show how the flat file source component was configured.

Flat File Source Connection Manager

Flat File Source Columns

Flat File Source Error Output

The OLE DB Destination component was configured to accept the data from Flat File Source and insert it into SQL Server database table named dbo.Destination. Below three screenshots show how the OLE DB Destination component was configured.

OLE DB Destination Connection Manager

OLE DB Destination Mappings

OLE DB Destination Error Output

Using the steps mentioned in the below 5 screenshots, I added a data viewer on the flow between the Flat File Source and OLE DB Destination.

Right click

Data Flow Path Editor New

Configure Data Viewer

Data Flow Path Editor Added

Data Viewer visible

Before running the package, I verified the initial data present in the table. It is currently empty because I created this using the script provided at the beginning of this post.

Empty Table

Executed the package and the package execution temporarily paused to display the data flowing from Flat File Source to OLE DB Destination in the data viewer. I clicked on the run button to proceed with the execution.

Data Viewer Pause

The package executed successfully.

Successful execution

Flat file source data was inserted successfully into the table dbo.Destination.

Data in table

Here is the layout of the table dbo.Destination. As you can see, the field OrderDate is of data type date and the package still continued to insert the data correctly.

Destination layout

This post even though is not a solution. Hopefully helps you to find out where the problem could be in your scenario.

Should I use past or present tense in git commit messages?

It is up to you. Just use the commit message as you wish. But it is easier if you are not switching between times and languages.

And if you develop in a team - it should be discussed and set fixed.

how to get the one entry from hashmap without iterating

If you are using Java 8, it is as simple as findFirst():

Quick example:

Optional<Car> theCarFoundOpt = carMap.values().stream().findFirst();

if(theCarFoundOpt.isPresent()) {
    return theCarFoundOpt.get().startEngine();
}

Run a mySQL query as a cron job?

Try creating a shell script like the one below:

#!/bin/bash

mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"

You can then add this to the cron

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

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

C++.

It is the gold standard for AAA game programming. If you need to do something interesting, you will need to do C++ or delve into unmanaged C#(not always nice).

C++ is also arguably faster(usual caveats apply).

As a learning experience, C# is not worth it. C++ is unquestionably better, especially in the quasi-embedded world of consoles. To get the object-oriented experience, go towards Java.

how to list all sub directories in a directory

Easy as this:

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

Didn't Java once have a Pair class?

Many 3rd party libraries have their versions of Pair, but Java has never had such a class. The closest is the inner interface java.util.Map.Entry, which exposes an immutable key property and a possibly mutable value property.

How can I develop for iPhone using a Windows development machine?

Try macincloud.com It allows you to rent a mac and access it through RDP remote control. You can then use your PC to access a mac and then develop your apps.

What are the integrity and crossorigin attributes?

Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.

Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.

Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.

In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.

Source: https://yon.fun/what-is-link-integrity-and-crossorigin/

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

Copy mysql database from remote server to local computer

Better yet use a oneliner:

Dump remoteDB to localDB:

mysqldump -uroot -pMypsw -h remoteHost remoteDB | mysql -u root -pMypsw localDB

Dump localDB to remoteDB:

mysqldump -uroot -pmyPsw localDB | mysql -uroot -pMypsw -h remoteHost remoteDB

How to handle login pop up window using Selenium WebDriver?

This is a solution for Python based selenium, after going through the source code (here). I found this 3 steps as useful.

obj = driver.switch_to.alert
obj.send_keys(keysToSend="username\ue004password")
obj.accept()

Here \ue004 is the value for TAB which you can find in Keys class in the source code.

I guess the same approach can be used in JAVA as well but not sure.

Where is svn.exe in my machine?

I installed TortoiseSVN-1.12.2.28653-x64-svn-1.12.2 in Windows 10 with commandline tool enabled. Still it didn't have the svn.exe file inside the bin folder.

So I downloaded Apache Subversion commandline tools from https://www.visualsvn.com/files/Apache-Subversion-1.13.0.zip. After unzipping, I have put the following two locations into my PATH variable:

C:\Program Files\TortoiseSVN\bin
E:\Apache-Subversion-1.13.0\bin

Everything works fine for me after this configuration.I wanted to use SVN in VsCode IDE.

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

For s: When used with printf functions, specifies a single-byte or multi-byte character string; when used with wprintf functions, specifies a wide-character string. Characters are displayed up to the first null character or until the precision value is reached.

For S: When used with printf functions, specifies a wide-character string; when used with wprintf functions, specifies a single-byte or multi-byte character string. Characters are displayed up to the first null character or until the precision value is reached.

In Unix-like platform, s and S have the same meaning as windows platform.

Reference: https://msdn.microsoft.com/en-us/library/hf4y5e3w.aspx

How to get the current time in Python

Method1: Getting Current Date and Time from system datetime

The datetime module supplies classes for manipulating dates and times.

Code

from datetime import datetime,date

print("Date: "+str(date.today().year)+"-"+str(date.today().month)+"-"+str(date.today().day))
print("Year: "+str(date.today().year))
print("Month: "+str(date.today().month))
print("Day: "+str(date.today().day)+"\n")

print("Time: "+str(datetime.today().hour)+":"+str(datetime.today().minute)+":"+str(datetime.today().second))
print("Hour: "+str(datetime.today().hour))
print("Minute: "+str(datetime.today().minute))
print("Second: "+str(datetime.today().second))
print("MilliSecond: "+str(datetime.today().microsecond))

Output will be like

Date: 2020-4-18
Year: 2020
Month: 4
Day: 18

Time: 19:30:5
Hour: 19
Minute: 30
Second: 5
MilliSecond: 836071

Method2: Getting Current Date and Time if Network is available

urllib package helps us to handle the url's that means webpages. Here we collects data from the webpage http://just-the-time.appspot.com/ and parses dateime from the webpage using the package dateparser.

Code

from urllib.request import urlopen
import dateparser

time_url = urlopen(u'http://just-the-time.appspot.com/')
datetime = time_url.read().decode("utf-8", errors="ignore").split(' ')[:-1]
date = datetime[0]
time = datetime[1]

print("Date: "+str(date))
print("Year: "+str(date.split('-')[0]))
print("Month: "+str(date.split('-')[1]))
print("Day: "+str(date.split('-')[2])+'\n')

print("Time: "+str(time))
print("Hour: "+str(time.split(':')[0]))
print("Minute: "+str(time.split(':')[1]))
print("Second: "+str(time.split(':')[2]))

Output will be like

Date: 2020-04-18
Year: 2020
Month: 04
Day: 18

Time: 14:17:10
Hour: 14
Minute: 17
Second: 10

Method3: Getting Current Date and Time from Local Time of the Machine

Python's time module provides a function for getting local time from the number of seconds elapsed since the epoch called localtime(). ctime() function takes seconds passed since epoch as an argument and returns a string representing local time.

Code

from time import time, ctime
datetime = ctime(time()).split(' ')

print("Date: "+str(datetime[4])+"-"+str(datetime[1])+"-"+str(datetime[2]))
print("Year: "+str(datetime[4]))
print("Month: "+str(datetime[1]))
print("Day: "+str(datetime[2]))
print("Week Day: "+str(datetime[0])+'\n')

print("Time: "+str(datetime[3]))
print("Hour: "+str(datetime[3]).split(':')[0])
print("Minute: "+str(datetime[3]).split(':')[1])
print("Second: "+str(datetime[3]).split(':')[2])

Output will be like

Date: 2020-Apr-18
Year: 2020
Month: Apr
Day: 18
Week Day: Sat

Time: 19:30:20
Hour: 19
Minute: 30
Second: 20

No plot window in matplotlib

If you are user of Anaconda and Spyder then best solution for you is that :

Tools --> Preferences --> Ipython console --> Graphic Section

Then in the Support for graphics (Matplotlib) section:

select two avaliable options

and in the Graphics Backend:

select Automatic

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

How to show loading spinner in jQuery?

As well as setting global defaults for ajax events, you can set behaviour for specific elements. Perhaps just changing their class would be enough?

$('#myForm').ajaxSend( function() {
    $(this).addClass('loading');
});
$('#myForm').ajaxComplete( function(){
    $(this).removeClass('loading');
});

Example CSS, to hide #myForm with a spinner:

.loading {
    display: block;
    background: url(spinner.gif) no-repeat center middle;
    width: 124px;
    height: 124px;
    margin: 0 auto;
}
/* Hide all the children of the 'loading' element */
.loading * {
    display: none;  
}

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

Try to create lombok.config file under project base directory and provide lombok.log.fieldName value.

Example: lombok.log.fieldName = LOG

Change Name of Import in Java, or import two classes with the same name

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;

private Formatter textFormatter;
private com.json.Formatter jsonFormatter;

SQL ServerĀ® 2016, 2017 and 2019 Express full download

When you can't apply Juki's answer then after selecting the desired version of media you can use Fiddler to determine where the files are located.

SQL Server 2019 Express Edition (English):

SQL Server 2017 Express Edition (English):

SQL Server 2016 with SP2 Express Edition (English):

SQL Server 2016 with SP1 Express Edition (English):

And here is how to use Fiddler.

Test whether string is a valid integer

You can strip non-digits and do a comparison. Here's a demo script:

for num in "44" "-44" "44-" "4-4" "a4" "4a" ".4" "4.4" "-4.4" "09"
do
    match=${num//[^[:digit:]]}    # strip non-digits
    match=${match#0*}             # strip leading zeros
    echo -en "$num\t$match\t"
    case $num in
        $match|-$match)    echo "Integer";;
                     *)    echo "Not integer";;
    esac
done

This is what the test output looks like:

44      44      Integer
-44     44      Integer
44-     44      Not integer
4-4     44      Not integer
a4      4       Not integer
4a      4       Not integer
.4      4       Not integer
4.4     44      Not integer
-4.4    44      Not integer
09      9       Not integer

CXF: No message body writer found for class - automatically mapping non-simple resources

It isn't quite out of the box but CXF does support JSON bindings to rest services. See cxf jax-rs json docs here. You'll still need to do some minimal configuration to have the provider available and you need to be familiar with jettison if you want to have more control over how the JSON is formed.

EDIT: Per comment request, here is some code. I don't have a lot of experience with this but the following code worked as an example in a quick test system.

//TestApi parts
@GET
@Path ( "test" )
@Produces ( "application/json" )
public Demo getDemo () {
    Demo d = new Demo ();
    d.id = 1;
    d.name = "test";
    return d;
}

//client config for a TestApi interface
List providers = new ArrayList ();
JSONProvider jsonProvider = new JSONProvider ();
Map<String, String> map = new HashMap<String, String> ();
map.put ( "http://www.myserviceapi.com", "myapi" );
jsonProvider.setNamespaceMap ( map );
providers.add ( jsonProvider );
TestApi proxy = JAXRSClientFactory.create ( url, TestApi.class, 
    providers, true );

Demo d = proxy.getDemo ();
if ( d != null ) {
    System.out.println ( d.id + ":" + d.name );
}

//the Demo class
@XmlRootElement ( name = "demo", namespace = "http://www.myserviceapi.com" )
@XmlType ( name = "demo", namespace = "http://www.myserviceapi.com", 
    propOrder = { "name", "id" } )
@XmlAccessorType ( XmlAccessType.FIELD )
public class Demo {

    public String name;
    public int id;
}

Notes:

  1. The providers list is where you code configure the JSON provider on the client. In particular, you see the namespace mapping. This needs to match what is on your server side configuration. I don't know much about Jettison options so I'm not much help on manipulating all of the various knobs for controlling the marshalling process.
  2. Jettison in CXF works by marshalling XML from a JAXB provider into JSON. So you have to ensure that the payload objects are all marked up (or otherwise configured) to marshall as application/xml before you can have them marshall as JSON. If you know of a way around this (other than writing your own message body writer), I'd love to hear about it.
  3. I use spring on the server so my configuration there is all xml stuff. Essentially, you need to go through the same process to add the JSONProvider to the service with the same namespace configuration. Don't have code for that handy but I imagine it will mirror the client side fairly well.

This is a bit dirty as an example but will hopefully get you going.

Edit2: An example of a message body writer that is based on xstream to avoid jaxb.

@Produces ( "application/json" )
@Consumes ( "application/json" )
@Provider
public class XstreamJsonProvider implements MessageBodyReader<Object>,
    MessageBodyWriter<Object> {

@Override
public boolean isWriteable ( Class<?> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType ) {
    return MediaType.APPLICATION_JSON_TYPE.equals ( mediaType ) 
        && type.equals ( Demo.class );
}

@Override
public long getSize ( Object t, Class<?> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType ) {
    // I'm being lazy - should compute the actual size
    return -1;
}

@Override
public void writeTo ( Object t, Class<?> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType, 
    MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ) 
    throws IOException, WebApplicationException {
    // deal with thread safe use of xstream, etc.
    XStream xstream = new XStream ( new JettisonMappedXmlDriver () );
    xstream.setMode ( XStream.NO_REFERENCES );
    // add safer encoding, error handling, etc.
    xstream.toXML ( t, entityStream );
}

@Override
public boolean isReadable ( Class<?> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType ) {
    return MediaType.APPLICATION_JSON_TYPE.equals ( mediaType ) 
        && type.equals ( Demo.class );
}

@Override
public Object readFrom ( Class<Object> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType, 
    MultivaluedMap<String, String> httpHeaders, InputStream entityStream ) 
    throws IOException, WebApplicationException {
    // add error handling, etc.
    XStream xstream = new XStream ( new JettisonMappedXmlDriver () );
    return xstream.fromXML ( entityStream );
}
}

//now your client just needs this
List providers = new ArrayList ();
XstreamJsonProvider jsonProvider = new XstreamJsonProvider ();
providers.add ( jsonProvider );
TestApi proxy = JAXRSClientFactory.create ( url, TestApi.class, 
    providers, true );

Demo d = proxy.getDemo ();
if ( d != null ) {
    System.out.println ( d.id + ":" + d.name );
}

The sample code is missing the parts for robust media type support, error handling, thread safety, etc. But, it ought to get you around the jaxb issue with minimal code.

EDIT 3 - sample server side configuration As I said before, my server side is spring configured. Here is a sample configuration that works to wire in the provider:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
    http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">

<import resource="classpath:META-INF/cxf/cxf.xml" />

<jaxrs:server id="TestApi">
    <jaxrs:serviceBeans>
        <ref bean="testApi" />
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <bean id="xstreamJsonProvider" class="webtests.rest.XstreamJsonProvider" />
    </jaxrs:providers>
</jaxrs:server>

<bean id="testApi" class="webtests.rest.TestApi">
</bean>

</beans>

I have also noted that in the latest rev of cxf that I'm using there is a difference in the media types, so the example above on the xstream message body reader/writer needs a quick modification where isWritable/isReadable change to:

return MediaType.APPLICATION_JSON_TYPE.getType ().equals ( mediaType.getType () )
    && MediaType.APPLICATION_JSON_TYPE.getSubtype ().equals ( mediaType.getSubtype () )
    && type.equals ( Demo.class );

EDIT 4 - non-spring configuration Using your servlet container of choice, configure

org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet

with at least 2 init params of:

jaxrs.serviceClasses
jaxrs.providers

where the serviceClasses is a space separated list of the service implementations you want bound, such as the TestApi mentioned above and the providers is a space separated list of message body providers, such as the XstreamJsonProvider mentioned above. In tomcat you might add the following to web.xml:

<servlet>
    <servlet-name>cxfservlet</servlet-name>
    <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
    <init-param>
        <param-name>jaxrs.serviceClasses</param-name>
        <param-value>webtests.rest.TestApi</param-value>
    </init-param>
    <init-param>
        <param-name>jaxrs.providers</param-name>
        <param-value>webtests.rest.XstreamJsonProvider</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

That is pretty much the quickest way to run it without spring. If you are not using a servlet container, you would need to configure the JAXRSServerFactoryBean.setProviders with an instance of XstreamJsonProvider and set the service implementation via the JAXRSServerFactoryBean.setResourceProvider method. Check the CXFNonSpringJaxrsServlet.init method to see how they do it when setup in a servlet container.

That ought to get you going no matter your scenario.

Python Error: "ValueError: need more than 1 value to unpack"

You can't run this particular piece of code in the interactive interpreter. You'll need to save it into a file first so that you can pass the argument to it like this

$ python hello.py user338690

How do I save and restore multiple variables in python?

There is a built-in library called pickle. Using pickle you can dump objects to a file and load them later.

import pickle

f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()

f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()

SQL Error: ORA-00942 table or view does not exist

Case sensitive Tables (table names created with double-quotes) can throw this same error as well. See this answer for more information.

Simply wrap the table in double quotes:

INSERT INTO "customer" (c_id,name,surname) VALUES ('1','Micheal','Jackson')

Adding a css class to select using @Html.DropDownList()

As the signature from the error message implies, the second argument must be an IEnumerable, more specifically, an IEnumerable of SelectListItem. It is the list of choices. You can use the SelectList type, which is a IEnumerable of SelectListItem. For a list with no choices:

@Html.DropDownList("PriorityID", new List<SelectListItem>(), new {@class="textbox"} )

For a list with a few choices:

@Html.DropDownList(
    "PriorityID", 
    new List<SelectListItem> 
    { 
        new SelectListItem { Text = "High", Value = 1 }, 
        new SelectListItem { Text = "Low",  Value = 0 },
    }, 
    new {@class="textbox"})

Maybe this tutorial can be of help: How to create a DropDownList with ASP.NET MVC

array.select() in javascript

Underscore.js is a good library for these sorts of operations - it uses the builtin routines such as Array.filter if available, or uses its own if not.

http://documentcloud.github.com/underscore/

The docs will give an idea of use - the javascript lambda syntax is nowhere near as succinct as ruby or others (I always forget to add an explicit return statement for example) and scope is another easy way to get caught out, but you can do most things quite easily with the exception of constructs such as lazy list comprehensions.

From the docs for .select() (.filter() is an alias for the same)

Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). Delegates to the native filter method, if it exists.

  var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  => [2, 4, 6]

Is there a way to break a list into columns?

2021 - keep it simple, use CSS Grid

Lots of these answers are outdated, it's 2020 and we shouldn't be enabling people who are still using IE9. It's way more simple to just use CSS grid.

The code is very simple, and you can easily adjust how many columns there are using the grid-template-columns. See this and then play around with this fiddle to fit your needs.

_x000D_
_x000D_
.grid-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}
_x000D_
<ul class="grid-list">
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
</ul>
_x000D_
_x000D_
_x000D_

How can I set focus on an element in an HTML form using JavaScript?

For plain Javascript, try the following:

window.onload = function() {
  document.getElementById("TextBoxName").focus();
};

Angular no provider for NameService

You should be injecting NameService inside providers array of your AppModule's NgModule metadata.

@NgModule({
   providers: [MyService]
})

and be sure import in your component by same name (case sensitive),becouse SystemJs is case sensitive (by design). If you use different path name in your project files like this:

main.module.ts

import { MyService } from './MyService';

your-component.ts

import { MyService } from './Myservice';

then System js will make double imports

Displaying the Indian currency symbol on a website

best way copy the ? symbol and paste it.

What are public, private and protected in object oriented programming?

They aren't really concepts but rather specific keywords that tend to occur (with slightly different semantics) in popular languages like C++ and Java.

Essentially, they are meant to allow a class to restrict access to members (fields or functions). The idea is that the less one type is allowed to access in another type, the less dependency can be created. This allows the accessed object to be changed more easily without affecting objects that refer to it.

Broadly speaking, public means everyone is allowed to access, private means that only members of the same class are allowed to access, and protected means that members of subclasses are also allowed. However, each language adds its own things to this. For example, C++ allows you to inherit non-publicly. In Java, there is also a default (package) access level, and there are rules about internal classes, etc.

How do you do natural logs (e.g. "ln()") with numpy in Python?

from numpy.lib.scimath import logn
from math import e

#using: x - var
logn(e, x)

How can I define an interface for an array of objects with Typescript?

Here is one solution adapted to your example:

interface IenumServiceGetOrderByAttributes { 
  id: number; 
  label: string; 
  key: any 
}

interface IenumServiceGetOrderBy extends Array<IenumServiceGetOrderByAttributes> {

}

let result: IenumServiceGetOrderBy;

With this solution you can use all properties and methods of the Array (like: length, push(), pop(), splice() ...)

How to write log to file

I'm writing logs to the files, which are generate on daily basis (per day one log file is getting generated). This approach is working fine for me :

var (
    serverLogger *log.Logger
)

func init() {
    // set location of log file
    date := time.Now().Format("2006-01-02")
    var logpath = os.Getenv(constant.XDirectoryPath) + constant.LogFilePath + date + constant.LogFileExtension
    os.MkdirAll(os.Getenv(constant.XDirectoryPath)+constant.LogFilePath, os.ModePerm)
    flag.Parse()
    var file, err1 = os.OpenFile(logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)

    if err1 != nil {
        panic(err1)
    }
    mw := io.MultiWriter(os.Stdout, file)
    serverLogger = log.New(mw, constant.Empty, log.LstdFlags)
    serverLogger.Println("LogFile : " + logpath)
}

// LogServer logs to server's log file
func LogServer(logLevel enum.LogLevel, message string) {
    _, file, no, ok := runtime.Caller(1)
    logLineData := "logger_server.go"
    if ok {
        file = shortenFilePath(file)
        logLineData = fmt.Sprintf(file + constant.ColonWithSpace + strconv.Itoa(no) + constant.HyphenWithSpace)
    }
    serverLogger.Println(logLineData + logLevel.String() + constant.HyphenWithSpace + message)
}

// ShortenFilePath Shortens file path to a/b/c/d.go tp d.go
func shortenFilePath(file string) string {
    short := file
    for i := len(file) - 1; i > 0; i-- {
        if file[i] == constant.ForwardSlash {
            short = file[i+1:]
            break
        }
    }
    file = short
    return file
}

"shortenFilePath()" method used to get the name of the file from full path of file. and "LogServer()" method is used to create a formatted log statement (contains : filename, line number, log level, error statement etc...)

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

None of the solutions worked for me as of today. My situation was that I got my Android studio updated. The most popular thing to replace the tools folder with the latest one wouldn't work for me. Infact is not required in some cases.

npm update -g cordova did the trick for me.

Then I removed the platform and added it again.

ionic platform remove android

ionic platform add android

This works for me in Ionic. I am surecordova platform remove/add android will do the same stuff. Not tested though.

Working again !

Grep for beginning and end of line?

The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.

grep '^[-d]rwx.*[0-9]$' "$@"

See: Regular Expressions and grep for POSIX-standard details.

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

T-SQL query to show table definition?

This will return columns, datatypes, and indexes defined on the table:

--List all tables in DB
select * from sysobjects where xtype = 'U'

--Table Definition
sp_help TableName

This will return triggers defined on the table:

--Triggers in SQL Table
select * from sys.triggers where parent_id = object_id(N'SQLTableName') 

How to access a dictionary key value present inside a list?

You haven't provided enough context to provide an accurate answer (i.e. how do you want to handle identical keys in multiple dicts?)

One answer is to iterate the list, and attempt to get 'd'

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myvalues = [i['d'] for i in mylist if 'd' in i]

Another answer is to access the dict directly (by list index), though you have to know that the key is present

mylist[1]['d']

Moment.js: Date between dates

You can use one of the moment plugin -> moment-range to deal with date range:

var startDate = new Date(2013, 1, 12)
  , endDate   = new Date(2013, 1, 15)
  , date  = new Date(2013, 2, 15)
  , range = moment().range(startDate, endDate);

range.contains(date); // false

Concatenate strings from several rows using Pandas groupby

For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()

How to close a JavaFX application on window close?

Using Java 8 this worked for me:

@Override
public void start(Stage stage) {
    Scene scene = new Scene(new Region());
    stage.setScene(scene);

    /* ... OTHER STUFF ... */

    stage.setOnCloseRequest(e -> {
        Platform.exit();
        System.exit(0);
    });
}

How to secure database passwords in PHP?

Put the database password in a file, make it read-only to the user serving the files.

Unless you have some means of only allowing the php server process to access the database, this is pretty much all you can do.

Replace a character at a specific index in a string?

First thing I should have noticed is that charAt is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You are repeating the y,m,d.

Instead of

gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());  

You should use it like

gmdate('Y-m-d h:m:s \G\M\T', time());

How do I request a file but not save it with Wget?

Curl does that by default without any parameters or flags, I would use it for your purposes:

curl $url > /dev/null 2>&1

Curl is more about streams and wget is more about copying sites based on this comparison.

Implode an array with JavaScript?

Like This:

[1,2,3,4].join('; ')

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

You need to specify the width and height in px:

width: 10px; height: 10px;

In addition, you can use overflow: auto; to prevent the horizontal scrollbar from showing.

Therefore, you may want to try the following:

<div style="width:100px; height:100px; overflow: auto;" >
  text text text text text text text text text
  text text text text text text text text text
  text text text text text text text text text
  text text text text text text text text text
  text text text text text text text text text
  text text text text text text text text text
  text text text text text text text text text
  text text text text text text text text text
</div>