Programs & Examples On #Svn client

SVN client is a sofware implementing the client role specified in the client–server model of the Subversion revision control system.

Bootstrap-select - how to fire event on change

Easiest implementation.

<script>
    $( ".selectpicker" ).change(function() {
        alert( "Handler for .change() called." );
    });
</script>

How to make div's percentage width relative to parent div and not viewport

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

IntelliJ: Never use wildcard imports

  1. File\Settings... (Ctrl+Alt+S)
  2. Project Settings > Editor > Code Style > Java > Imports tab
  3. Set Class count to use import with '*' to 999
  4. Set Names count to use static import with '*' to 999

After this, your configuration should look like: enter image description here

(On IntelliJ IDEA 13.x, 14.x, 15.x, 2016.x, 2017.x)

Difference between java.exe and javaw.exe

java.exe is the console app while javaw.exe is windows app (console-less). You can't have Console with javaw.exe.

change text of button and disable button in iOS

Hey Namratha, If you're asking about changing the text and enabled/disabled state of a UIButton, it can be done pretty easily as follows;

[myButton setTitle:@"Normal State Title" forState:UIControlStateNormal]; // To set the title
[myButton setEnabled:NO]; // To toggle enabled / disabled

If you have created the buttons in the Interface Builder and want to access them in code, you can take advantage of the fact that they are passed in as an argument to the IBAction calls:

- (IBAction) triggerActionWithSender: (id) sender;

This can be bound to the button and you’ll get the button in the sender argument when the action is triggered. If that’s not enough (because you need to access the buttons somewhere else than in the actions), declare an outlet for the button:

@property(retain) IBOutlet UIButton *someButton;

Then it’s possible to bind the button in IB to the controller, the NIB loading code will set the property value when loading the interface.

The static keyword and its various uses in C++

Static Object: We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

Let us try the following example to understand the concept of static data members:

#include <iostream>

using namespace std;

class Box
{
   public:
      static int objectCount;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void)
{
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects.
   cout << "Total objects: " << Box::objectCount << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Constructor called.
Constructor called.
Total objects: 2

Static Function Members: By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

A static member function can only access static data member, other static member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.

Let us try the following example to understand the concept of static function members:

#include <iostream>

using namespace std;

class Box
{
   public:
      static int objectCount;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
      static int getCount()
      {
         return objectCount;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void)
{

   // Print total number of objects before creating object.
   cout << "Inital Stage Count: " << Box::getCount() << endl;

   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects after creating object.
   cout << "Final Stage Count: " << Box::getCount() << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2

"for" vs "each" in Ruby

I just want to make a specific point about the for in loop in Ruby. It might seem like a construct similar to other languages, but in fact it is an expression like every other looping construct in Ruby. In fact, the for in works with Enumerable objects just as the each iterator.

The collection passed to for in can be any object that has an each iterator method. Arrays and hashes define the each method, and many other Ruby objects do, too. The for/in loop calls the each method of the specified object. As that iterator yields values, the for loop assigns each value (or each set of values) to the specified variable (or variables) and then executes the code in body.

This is a silly example, but illustrates the point that the for in loop works with ANY object that has an each method, just like how the each iterator does:

class Apple
  TYPES = %w(red green yellow)
  def each
    yield TYPES.pop until TYPES.empty?
  end
end

a = Apple.new
for i in a do
  puts i
end
yellow
green
red
=> nil

And now the each iterator:

a = Apple.new
a.each do |i|
  puts i
end
yellow
green
red
=> nil

As you can see, both are responding to the each method which yields values back to the block. As everyone here stated, it is definitely preferable to use the each iterator over the for in loop. I just wanted to drive home the point that there is nothing magical about the for in loop. It is an expression that invokes the each method of a collection and then passes it to its block of code. Hence, it is a very rare case you would need to use for in. Use the each iterator almost always (with the added benefit of block scope).

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Webrtc is a part of peer to peer connection. We all know that before creating peer to peer connection, it requires handshaking process to establish peer to peer connection. And websockets play the role of handshaking process.

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

How to serialize an object to XML without getting xmlns="..."?

If you want to get rid of the extra xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xmlns:xsd="http://www.w3.org/2001/XMLSchema", but still keep your own namespace xmlns="http://schemas.YourCompany.com/YourSchema/", you use the same code as above except for this simple change:

//  Add lib namespace with empty prefix  
ns.Add("", "http://schemas.YourCompany.com/YourSchema/");   

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

Set style for TextView programmatically

We can use TextViewCompact.setTextAppearance(textView, R.style.xyz).

Android doc for reference.

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

Just add this to your view:

<?php header("Access-Control-Allow-Origin: *"); ?>

Ways to eliminate switch in code

'switch' is just a language construct and all language constructs can be thought of as tools to get a job done. As with real tools, some tools are better suited to one task than another (you wouldn't use a sledge hammer to put up a picture hook). The important part is how 'getting the job done' is defined. Does it need to be maintainable, does it need to be fast, does it need to scale, does it need to be extendable and so on.

At each point in the programming process there are usually a range of constructs and patterns that can be used: a switch, an if-else-if sequence, virtual functions, jump tables, maps with function pointers and so on. With experience a programmer will instinctively know the right tool to use for a given situation.

It must be assumed that anyone maintaining or reviewing code is at least as skilled as the original author so that any construct can be safely used.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

How to use EditText onTextChanged event when I press the number?

You have selected correct approach. You have to extend the class with TextWatcher and override afterTextChanged(),beforeTextChanged(), onTextChanged().

You have to write your desired logic in afterTextChanged() method to achieve functionality needed by you.

Error: Cannot find module 'gulp-sass'

I had the same problem, and I resolve doing this npm update. But I receive the message about permission, so I run:

sudo chwon -R myuser /home/myUserFolder/.config

This set permissions for my user run npm comands like administrator. Then I run this again:

npm update 

and this:

npm install gulp-sass

Then my problem with this was solved.

Str_replace for multiple items

If you're only replacing single characters, you should use strtr()

Gridview get Checkbox.Checked value

Blockquote

    foreach (GridViewRow row in tempGrid.Rows)
    {
        dt.Rows.Add();
        for (int i = 0; i < row.Controls.Count; i++)
        {
            Control control = row.Controls[i];
            if (control.Controls.Count==1)
            {
                CheckBox chk = row.Cells[i].Controls[0] as CheckBox;
                if (chk != null && chk.Checked)
                {
                    dt.Rows[dt.Rows.Count - 1][i] = "True";
                }
                else
                dt.Rows[dt.Rows.Count - 1][i] = "False";
            }
            else
                dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text.Replace("&nbsp;", "");
        }
    }

Uncaught Typeerror: cannot read property 'innerHTML' of null

var idPost=document.getElementById("status").innerHTML;

The 'status' element does not exist in your webpage.

So document.getElementById("status") return null. While you can not use innerHTML property of NULL.

You should add a condition like this:

if(document.getElementById("status") != null){
    var idPost=document.getElementById("status").innerHTML;
}

Hope this answer can help you. :)

Rotate label text in seaborn factorplot

Any seaborn plots suported by facetgrid won't work with (e.g. catplot)

g.set_xticklabels(rotation=30) 

however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.

g.set_xticklabels(g.get_xticklabels(), rotation=30)

Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.

Disable / Check for Mock Location (prevent gps spoofing)

This scrip is working for all version of android and i find it after many search

LocationManager locMan;
    String[] mockProviders = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER};

    try {
        locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        for (String p : mockProviders) {
            if (p.contentEquals(LocationManager.GPS_PROVIDER))
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
            else
                locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
                        android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW);

            locMan.setTestProviderEnabled(p, true);
            locMan.setTestProviderStatus(p, android.location.LocationProvider.AVAILABLE, Bundle.EMPTY,
                    java.lang.System.currentTimeMillis());
        }
    } catch (Exception ignored) {
        // here you should show dialog which is mean the mock location is not enable
    }

CSS disable hover effect

  .buttonDisabled{
     background-color: unset !important;
    color: unset !important;
}

How to get the cell value by column name not by index in GridView in asp.net

GridView does not act as column names, as that's it's datasource property to know those things.

If you still need to know the index given a column name, then you can create a helper method to do this as the gridview Header normally contains this information.

int GetColumnIndexByName(GridViewRow row, string columnName)
{
    int columnIndex = 0;
    foreach (DataControlFieldCell cell in row.Cells)
    {
        if (cell.ContainingField is BoundField)
            if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
                break;
        columnIndex++; // keep adding 1 while we don't have the correct name
    }
    return columnIndex;
}

remember that the code above will use a BoundField... then use it like:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int index = GetColumnIndexByName(e.Row, "myDataField");
        string columnValue = e.Row.Cells[index].Text;
    }
}

I would strongly suggest that you use the TemplateField to have your own controls, then it's easier to grab those controls like:

<asp:GridView ID="gv" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

and then use

string columnValue = ((Label)e.Row.FindControl("lblName")).Text;

"could not find stored procedure"

You may need to check who the actual owner of the stored procedure is. If it is a specific different user then that could be why you can't access it.

What is the best way to tell if a character is a letter or number in Java without using regexes?

Use the below code

Character.isLetterOrDigit(string.charAt(index))

fetch in git doesn't get all branches

The problem can be seen when checking the remote.origin.fetch setting
(The lines starting with $ are bash prompts with the commands I typed. The other lines are the resulting output)

$ git config --get remote.origin.fetch
+refs/heads/master:refs/remotes/origin/master

As you can see, in my case, the remote was set to fetch the master branch specifically and only. I fixed it as per below, including the second command to check the results.

$ git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
$ git config --get remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*

The wildcard * of course means everything under that path.

Unfortunately I saw this comment after I had already dug through and found the answer by trial and error.

Removing duplicates from a String in Java

public class RemoveDuplicatesFromStingsMethod1UsingLoops {

    public static void main(String[] args) {

        String input = new String("aaabbbcccddd");
        String output = "";
        for (int i = 0; i < input.length(); i++) {
            if (!output.contains(String.valueOf(input.charAt(i)))) {
                output += String.valueOf(input.charAt(i));
            }
        }
        System.out.println(output);
    }
}

output: abcd

How can I use Bash syntax in Makefile targets?

If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.

How to define a connection string to a SQL Server 2008 database?

You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:

Integrated Security = True;

If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:

User ID = "username"; Password = "password";

Changing project port number in Visual Studio 2013

  • Open Solution file (.sln) in Editable mode (Notepad or notepad++ or any other tool)
  • Find tag name VMDPort and update it to your desired port.

see below snap.

enter image description here

Delete rows containing specific strings in R

This should do the trick:

df[- grep("REVERSE", df$Name),]

Or a safer version would be:

df[!grepl("REVERSE", df$Name),]

What is the default value for enum variable?

I think it's quite dangerous to rely on the order of the values in a enum and to assume that the first is always the default. This would be good practice if you are concerned about protecting the default value.

enum E
{
    Foo = 0, Bar, Baz, Quux
}

Otherwise, all it takes is a careless refactor of the order and you've got a completely different default.

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

How to run VBScript from command line without Cscript/Wscript

You may follow the following steps:

  • Open your CMD(Command Prompt)
  • Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:
  • Type 'CD VBS' and hit Enter. Example: D:>CD VBS
  • Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs

Shortest way to print current year in a website

The JS solution works great but I would advise on a server side solution. Some of the sites I checked had this issue of the entire page going blank and only the year being seen once in a while.

The reason for this was the document.write actually wrote over the entire document.

I asked my friend to implement a server side solution and it worked for him. The simple code in php

<?php echo date('Y'); ?>

Enjoy!

How do we check if a pointer is NULL pointer?

First, to be 100% clear, there is no difference between C and C++ here. And second, the Stack Overflow question you cite doesn't talk about null pointers; it introduces invalid pointers; pointers which, at least as far as the standard is concerned, cause undefined behavior just by trying to compare them. There is no way to test in general whether a pointer is valid.

In the end, there are three widespread ways to check for a null pointer:

if ( p != NULL ) ...

if ( p != 0 ) ...

if ( p ) ...

All work, regardless of the representation of a null pointer on the machine. And all, in some way or another, are misleading; which one you choose is a question of choosing the least bad. Formally, the first two are indentical for the compiler; the constant NULL or 0 is converted to a null pointer of the type of p, and the results of the conversion are compared to p. Regardless of the representation of a null pointer.

The third is slightly different: p is implicitly converted to bool. But the implicit conversion is defined as the results of p != 0, so you end up with the same thing. (Which means that there's really no valid argument for using the third style—it obfuscates with an implicit conversion, without any offsetting benefit.)

Which one of the first two you prefer is largely a matter of style, perhaps partially dictated by your programming style elsewhere: depending on the idiom involved, one of the lies will be more bothersome than the other. If it were only a question of comparison, I think most people would favor NULL, but in something like f( NULL ), the overload which will be chosen is f( int ), and not an overload with a pointer. Similarly, if f is a function template, f( NULL ) will instantiate the template on int. (Of course, some compilers, like g++, will generate a warning if NULL is used in a non-pointer context; if you use g++, you really should use NULL.)

In C++11, of course, the preferred idiom is:

if ( p != nullptr ) ...

, which avoids most of the problems with the other solutions. (But it is not C-compatible:-).)

Creating dummy variables in pandas for python

It's hard to infer what you're looking for from the question, but my best guess is as follows.

If we assume you have a DataFrame where some column is 'Category' and contains integers (or otherwise unique identifiers) for categories, then we can do the following.

Call the DataFrame dfrm, and assume that for each row, dfrm['Category'] is some value in the set of integers from 1 to N. Then,

for elem in dfrm['Category'].unique():
    dfrm[str(elem)] = dfrm['Category'] == elem

Now there will be a new indicator column for each category that is True/False depending on whether the data in that row are in that category.

If you want to control the category names, you could make a dictionary, such as

cat_names = {1:'Some_Treatment', 2:'Full_Treatment', 3:'Control'}
for elem in dfrm['Category'].unique():
    dfrm[cat_names[elem]] = dfrm['Category'] == elem

to result in having columns with specified names, rather than just string conversion of the category values. In fact, for some types, str() may not produce anything useful for you.

'any' vs 'Object'

Adding to Alex's answer and simplifying it:

Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Unable to call the built in mb_internal_encoding method?

For OpenSUse (zypper package manager):

zypper install php5-mbstring

and:

zyper install php7-mbstring

In the other hand, you can search them through YaST Software manager.

Note that, you must restart apache http server:

systemctl restart apache2.service

How to decode jwt token in javascript without using a library?

Based on answers here and here:

const dashRE = /-/g;
const lodashRE = /_/g;

module.exports = function jwtDecode(tokenStr) {
  const base64Url = tokenStr.split('.')[1];
  if (base64Url === undefined) return null;
  const base64 = base64Url.replace(dashRE, '+').replace(lodashRE, '/');
  const jsonStr = Buffer.from(base64, 'base64').toString();
  return JSON.parse(jsonStr);
};

Laravel Soft Delete posts

You actually do the normal delete. But on the model you specify that its a softdelete model.

So on your model add the code:

class Contents extends Eloquent {

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

}

Then on your code do the normal delete like:

$id = Contents::find( $id );
$id ->delete();

Also make sure you have the deleted_at column on your table.

Or just see the docs: http://laravel.com/docs/eloquent#soft-deleting

Call js-function using JQuery timer

setInterval is the function you want. That repeats every x miliseconds.

window.setInterval(function() {
    alert('test');
}, 10000);

Visual Studio Code includePath

A more current take on the situation. During 2018, the C++ extension added another option to the configuration compilerPath of the c_cpp_properties.json file;

compilerPath (optional) The absolute path to the compiler you use to build your project. The extension will query the compiler to determine the system include paths and default defines to use for IntelliSense.

If used, the includePath would not be needed since the IntelliSense will use the compiler to figure out the system include paths.


Originally,

How and where can I add include paths in the configurations below?

The list is a string array, hence adding an include path would look something like;

"configurations": [
    {
        "name": "Mac",
        "includePath": ["/usr/local/include",
            "/path/to/additional/includes",
            "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include"
        ]
    }
]

Source; cpptools blog 31 March 2016.

The linked source has a gif showing the format for the Win32 configuration, but the same applies to the others.

The above sample includes the SDK (OSX 10.11) path if Xcode is installed.

Note I find it can take a while to update once the include path has been changed.

The cpptools extension can be found here.

Further documentation (from Microsoft) on the C++ language support in VSCode can be found here.


For the sake of preservation (from the discussion), the following are basic snippets for the contents of the tasks.json file to compile and execute either a C++ file, or a C file. They allow for spaces in the file name (requires escaping the additional quotes in the json using \"). The shell is used as the runner, thus allowing the compilation (clang...) and the execution (&& ./a.out) of the program. It also assumes that the tasks.json "lives" in the local workspace (under the directory .vscode). Further task.json details, such as supported variables etc. can be found here.

For C++;

{ 
    "version": "0.1.0", 
    "isShellCommand": true, 
    "taskName": "GenericBuild", 
    "showOutput": "always", 
    "command": "sh", 
    "suppressTaskName": false, 
    "args": ["-c", "clang++ -std=c++14 -Wall -Wextra -pedantic -pthread \"${file}\" && ./a.out"]
}

For C;

{ 
    "version": "0.1.0", 
    "isShellCommand": true, 
    "taskName": "GenericBuild", 
    "showOutput": "always", 
    "command": "sh", 
    "suppressTaskName": false, 
    "args": ["-c", "clang -std=c11 -Wall -Wextra -pedantic -pthread \"${file}\" && ./a.out"] // command arguments... 
}

How to set selectedIndex of select element using display text?

You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California

How to create a directory if it doesn't exist using Node.js?

I'd like to add a Typescript Promise refactor of josh3736's answer.

It does the same thing and has the same edge cases, it just happens to use Promises, typescript typedefs and works with "use strict".

// https://en.wikipedia.org/wiki/File_system_permissions#Numeric_notation
const allRWEPermissions = parseInt("0777", 8);

function ensureFilePathExists(path: string, mask: number = allRWEPermissions): Promise<void> {
    return new Promise<void>(
        function(resolve: (value?: void | PromiseLike<void>) => void,
            reject: (reason?: any) => void): void{
            mkdir(path, mask, function(err: NodeJS.ErrnoException): void {
                if (err) {
                    if (err.code === "EEXIST") {
                        resolve(null); // ignore the error if the folder already exists
                    } else {
                        reject(err); // something else went wrong
                    }
                } else {
                    resolve(null); // successfully created folder
                }
            });
    });
}

Change the background color of a pop-up dialog

Use setInverseBackgroundForced(true) on the alert dialog builder to invert the background.

Android Text over image

The below code this will help you

public class TextProperty {
    private int heigt;                              //???????
    private String []context = new String[1024];    //???????

    /*
     *@parameter wordNum
     *
     */
    public TextProperty(int wordNum ,InputStreamReader in) throws Exception {
        int i=0;
        BufferedReader br = new BufferedReader(in);
        String s;
        while((s=br.readLine())!=null){
            if(s.length()>wordNum){
                int k=0;
                while(k+wordNum<=s.length()){
                    context[i++] = s.substring(k, k+wordNum);
                    k=k+wordNum;
                }
                context[i++] = s.substring(k,s.length());
            }
            else{
                context[i++]=s;
            }
        }
        this.heigt = i;
        in.close();
        br.close();
    }


    public int getHeigt() {
        return heigt;
    }

    public String[] getContext() {

        return context;
    }
}
public class MainActivity extends AppCompatActivity {

    private Button btn;
    private ImageView iv;
    private final int WORDNUM = 35;  //??????  ???????
    private final int WIDTH = 450;   //???????

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = (ImageView) findViewById(R.id.imageView);
        btn = (Button) findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int x=5,y=10;
                try {
                    TextProperty tp = new TextProperty(WORDNUM, new InputStreamReader(getResources().getAssets().open("1.txt")));
                    Bitmap bitmap = Bitmap.createBitmap(WIDTH, 20*tp.getHeigt(), Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bitmap);
                    Paint paint = new Paint();
                    paint.setColor(Color.WHITE);
                    paint.setTextAlign(Paint.Align.LEFT);
                    paint.setTextSize(20f);

                    String [] ss = tp.getContext();
                    for(int i=0;i<tp.getHeigt();i++){
                        canvas.drawText(ss[i], x, y, paint);
                        y=y+20;
                    }

                    canvas.save(Canvas.ALL_SAVE_FLAG);
                    canvas.restore();
                    String path = Environment.getExternalStorageDirectory() + "/image.png";
                    System.out.println(path);
                    FileOutputStream os = new FileOutputStream(new File(path));
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                    //Display the image on ImageView.
                    iv.setImageBitmap(bitmap);
                    iv.setBackgroundColor(Color.BLUE);
                    os.flush();
                    os.close();
                }
                catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}```

Gson library in Android Studio

Gradle:

dependencies {
   implementation 'com.google.code.gson:gson:2.8.5'
}

Maven:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version> 
</dependency>

Gson jar downloads are available from Maven Central.

Reflection: How to Invoke Method with parameters

I tried to work with all the suggested answers above but nothing seems to work for me. So i am trying to explain what worked for me here.

I believe if you are calling some method like the Main below or even with a single parameter as in your question, you just have to change the type of parameter from string to object for this to work. I have a class like below

//Assembly.dll
namespace TestAssembly{
    public class Main{

        public void Hello()
        { 
            var name = Console.ReadLine();
            Console.WriteLine("Hello() called");
            Console.WriteLine("Hello" + name + " at " + DateTime.Now);
        }

        public void Run(string parameters)
        { 
            Console.WriteLine("Run() called");
            Console.Write("You typed:"  + parameters);
        }

        public string TestNoParameters()
        {
            Console.WriteLine("TestNoParameters() called");
            return ("TestNoParameters() called");
        }

        public void Execute(object[] parameters)
        { 
            Console.WriteLine("Execute() called");
           Console.WriteLine("Number of parameters received: "  + parameters.Length);

           for(int i=0;i<parameters.Length;i++){
               Console.WriteLine(parameters[i]);
           }
        }

    }
}

Then you have to pass the parameterArray inside an object array like below while invoking it. The following method is what you need to work

private void ExecuteWithReflection(string methodName,object parameterObject = null)
{
    Assembly assembly = Assembly.LoadFile("Assembly.dll");
    Type typeInstance = assembly.GetType("TestAssembly.Main");

    if (typeInstance != null)
    {
        MethodInfo methodInfo = typeInstance.GetMethod(methodName);
        ParameterInfo[] parameterInfo = methodInfo.GetParameters();
        object classInstance = Activator.CreateInstance(typeInstance, null);

        if (parameterInfo.Length == 0)
        {
            // there is no parameter we can call with 'null'
            var result = methodInfo.Invoke(classInstance, null);
        }
        else
        {
            var result = methodInfo.Invoke(classInstance,new object[] { parameterObject } );
        }
    }
}

This method makes it easy to invoke the method, it can be called as following

ExecuteWithReflection("Hello");
ExecuteWithReflection("Run","Vinod");
ExecuteWithReflection("TestNoParameters");
ExecuteWithReflection("Execute",new object[]{"Vinod","Srivastav"});

Right align text in android TextView

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

  <TextView
    android:id="@+id/tct_postpone_hour"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_gravity="center"
    android:gravity="center_vertical|center_horizontal"
    android:text="1"
    android:textSize="24dp" />
</RelativeLayout>

makes number one align in center both horizontal and vertical.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

If you are in same network then add the destination server to the MS Server management studio using connect option and then try exporting from source to destination. The most easiest way :)

How to change column datatype from character to numeric in PostgreSQL 8.4

You can try using USING:

The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

So this might work (depending on your data):

alter table presales alter column code type numeric(10,0) using code::numeric;
-- Or if you prefer standard casting...
alter table presales alter column code type numeric(10,0) using cast(code as numeric);

This will fail if you have anything in code that cannot be cast to numeric; if the USING fails, you'll have to clean up the non-numeric data by hand before changing the column type.

Finding element's position relative to the document

For those that want to get the x and y coordinates of various positions of an element, relative to the document.

const getCoords = (element, position) => {
  const { top, left, width, height } = element.getBoundingClientRect();
  let point;
  switch (position) {
    case "top left":
      point = {
        x: left + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "top center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "top right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "center left":
      point = {
        x: left + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "center right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "bottom left":
      point = {
        x: left + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
    case "bottom center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
    case "bottom right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
  }
  return point;
};

Usage

  • getCoords(document.querySelector('selector'), 'center')

  • getCoords(document.querySelector('selector'), 'bottom right')

  • getCoords(document.querySelector('selector'), 'top center')

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

As long as the server allows the ampresand character to be POSTed (not all do as it can be unsafe), all you should have to do is URL Encode the character. In the case of an ampresand, you should replace the character with %26.

.NET provides a nice way of encoding the entire string for you though:

string strNew = "&uploadfile=true&file=" + HttpUtility.UrlEncode(iCalStr);

How to insert a timestamp in Oracle?

Inserting date in sql

insert
into tablename (timestamp_value)
values ('dd-mm-yyyy hh-mm-ss AM');

If suppose we wanted to insert system date

insert
into tablename (timestamp_value)
values (sysdate);

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

Your second example does not work if you send the argument by reference. Did you mean

void copyVecFast(vec<int> original) // no reference
{

  vector<int> new_;
  new_.swap(original); 
}

That would work, but an easier way is

vector<int> new_(original);

How to scan multiple paths using the @ComponentScan annotation?

Another way of doing this is using the basePackages field; which is a field inside ComponentScan annotation.

@ComponentScan(basePackages={"com.firstpackage","com.secondpackage"})

If you look into the ComponentScan annotation .class from the jar file you will see a basePackages field that takes in an array of Strings

public @interface ComponentScan {
String[] basePackages() default {};
}

Or you can mention the classes explicitly. Which takes in array of classes

Class<?>[]  basePackageClasses

Install pip in docker

An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine. They offer pip out of the box (and have a smaller footprint which leads to faster builds etc).

Decreasing for loops in Python impossible?

for n in range(6,0,-1):
    print n
# prints [6, 5, 4, 3, 2, 1]

Guzzle 6: no more json() method for responses

$response is instance of PSR-7 ResponseInterface. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces

getBody() returns StreamInterface:

/**
 * Gets the body of the message.
 *
 * @return StreamInterface Returns the body as a stream.
 */
public function getBody();

StreamInterface implements __toString() which does

Reads all data from the stream into a string, from the beginning to end.

Therefore, to read body as string, you have to cast it to string:

$stringBody = (string) $response->getBody()


Gotchas

  1. json_decode($response->getBody() is not the best solution as it magically casts stream into string for you. json_decode() requires string as 1st argument.
  2. Don't use $response->getBody()->getContents() unless you know what you're doing. If you read documentation for getContents(), it says: Returns the remaining contents in a string. Therefore, calling getContents() reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.

Laravel 5.2 - pluck() method returns array

I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();

it gives back an array of ids [50,2,3] and this is the whole query I used:

   $article_tags = DB::table('tags')
    ->join('taggables', function ($join) use ($id) {
        $join->on('tags.id', '=', 'taggables.tag_id');
        $join->where([
            ['taggable_id', '=', $id],
            ['taggable_type','=','article']
        ]);
    })->select('tags.id')->get()->pluck('id')->toArray();

How do I split a string into an array of characters?

Old question but I should warn:

Do NOT use .split('')

You'll get weird results with non-BMP (non-Basic-Multilingual-Plane) character sets.

Reason is that methods like .split() and .charCodeAt() only respect the characters with a code point below 65536; bec. higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters.

''.length     // —> 6
''.split('')  // —> ["?", "?", "?", "?", "?", "?"]

''.length      // —> 2
''.split('')   // —> ["?", "?"]

Use ES2015 (ES6) features where possible:

Using the spread operator:

let arr = [...str];

Or Array.from

let arr = Array.from(str);

Or split with the new u RegExp flag:

let arr = str.split(/(?!$)/u);

Examples:

[...'']        // —> ["", "", ""]
[...'']     // —> ["", "", ""]

For ES5, options are limited:

I came up with this function that internally uses MDN example to get the correct code point of each character.

function stringToArray() {
  var i = 0,
    arr = [],
    codePoint;
  while (!isNaN(codePoint = knownCharCodeAt(str, i))) {
    arr.push(String.fromCodePoint(codePoint));
    i++;
  }
  return arr;
}

This requires knownCharCodeAt() function and for some browsers; a String.fromCodePoint() polyfill.

if (!String.fromCodePoint) {
// ES6 Unicode Shims 0.1 , © 2012 Steven Levithan , MIT License
    String.fromCodePoint = function fromCodePoint () {
        var chars = [], point, offset, units, i;
        for (i = 0; i < arguments.length; ++i) {
            point = arguments[i];
            offset = point - 0x10000;
            units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point];
            chars.push(String.fromCharCode.apply(null, units));
        }
        return chars.join("");
    }
}

Examples:

stringToArray('')     // —> ["", "", ""]
stringToArray('')  // —> ["", "", ""]

Note: str[index] (ES5) and str.charAt(index) will also return weird results with non-BMP charsets. e.g. ''.charAt(0) returns "?".

UPDATE: Read this nice article about JS and unicode.

Get last field using awk substr

It should be a comment to the basename answer but I haven't enough point.

If you do not use double quotes, basename will not work with path where there is space character:

$ basename /home/foo/bar foo/bar.png
bar

ok with quotes " "

$ basename "/home/foo/bar foo/bar.png"
bar.png

file example

$ cat a
/home/parent/child 1/child 2/child 3/filename1
/home/parent/child 1/child2/filename2
/home/parent/child1/filename3

$ while read b ; do basename "$b" ; done < a
filename1
filename2
filename3

div background color, to change onhover

The "a:hover" literally tells the browser to change the properties for the <a>-tag, when the mouse is hovered over it. What you perhaps meant was "the div:hover" instead, which would trigger when the div was chosen.

Just to make sure, if you want to change only one particular div, give it an id ("<div id='something'>") and use the CSS "#something:hover {...}" instead. If you want to edit a group of divs, make them into a class ("<div class='else'>") and use the CSS ".else {...}" in this case (note the period before the class' name!)

SQL Insert into table only if record doesn't exist

Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id and date.

ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);

Then when inserting a record add the condition when a conflict is encountered:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value

This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.

How can I open a URL in Android's web browser from my application?

From Anko library method

fun Context.browse(url: String, newTask: Boolean = false): Boolean {
    try {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = Uri.parse(url)
        if (newTask) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        startActivity(intent)
        return true
    } catch (e: ActivityNotFoundException) {
        e.printStackTrace()
        return false
    }
}

Convert string to Python class object?

Warning: eval() can be used to execute arbitrary Python code. You should never use eval() with untrusted strings. (See Security of Python's eval() on untrusted strings?)

This seems simplest.

>>> class Foo(object):
...     pass
... 
>>> eval("Foo")
<class '__main__.Foo'>

Is there any difference between DECIMAL and NUMERIC in SQL Server?

This is what then SQL2003 standard (§6.1 Data Types) says about the two:

 <exact numeric type> ::=
    NUMERIC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DECIMAL [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DEC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | SMALLINT
  | INTEGER
  | INT
  | BIGINT

 ...

21) NUMERIC specifies the data type
    exact numeric, with the decimal
    precision and scale specified by the
    <precision> and <scale>.

22) DECIMAL specifies the data type
    exact numeric, with the decimal scale
    specified by the <scale> and the
    implementation-defined decimal
    precision equal to or greater than the
    value of the specified <precision>.

How to force a script reload and re-execute?

How about adding a new script tag to <head> with the script to (re)load? Something like below:

<script>
   function load_js()
   {
      var head= document.getElementsByTagName('head')[0];
      var script= document.createElement('script');
      script.src= 'source_file.js';
      head.appendChild(script);
   }
   load_js();
</script>

The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.

How do I select which GPU to run a job on?

Set the following two environment variables:

NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0

where gpu_id is the ID of your selected GPU, as seen in the host system's nvidia-smi (a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).

You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id parameter in nvidia-smi run in a terminal in the guest system).

More info

This method based on NVIDIA_VISIBLE_DEVICES exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).

Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0 or env in Kubernetes or Openshift.

If you want GPU load-balancing, make gpu_id random at each guest system start.

If setting this with python, make sure you are using strings for all environment variables, including numerical ones.

You can verify that a different card is selected for each value of gpu_id by inspecting nvidia-smi's Bus-Id parameter (in a terminal run in the guest system).

The accepted solution based on CUDA_VISIBLE_DEVICES alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).

This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).

This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.

List directory in Go

Even simpler, use path/filepath:

package main    

import (
    "fmt"
    "log"
    "path/filepath"
)

func main() {
    files, err := filepath.Glob("*")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(files) // contains a list of all files in the current directory
}

Converts scss to css

You can use sass /sassFile.scss /cssFile.css

Attention: Before using sass command you must install ruby and then install sass.

For installing sass, after ruby installation type gem install sass in your Terminal

Hint: sass compile SCSS files

Disable browser cache for entire ASP.NET website

You can try below code in Global.asax file.

protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();
    }

How to execute XPath one-liners from shell?

You can also try my Xidel. It is not in a package in the repository, but you can just download it from the webpage (it has no dependencies).

It has simple syntax for this task:

xidel filename.xml -e '//element/@attribute' 

And it is one of the rare of these tools that supports XPath 2.

Android ViewPager with bottom dots

My handmade solution:

In the layout:

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dots"
        />

And in the Activity

private final static int NUM_PAGES = 5;
private ViewPager mViewPager;
private List<ImageView> dots;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    addDots();
}

public void addDots() {
    dots = new ArrayList<>();
    LinearLayout dotsLayout = (LinearLayout)findViewById(R.id.dots);

    for(int i = 0; i < NUM_PAGES; i++) {
        ImageView dot = new ImageView(this);
        dot.setImageDrawable(getResources().getDrawable(R.drawable.pager_dot_not_selected));

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        dotsLayout.addView(dot, params);

        dots.add(dot);
    }

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            selectDot(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
}

public void selectDot(int idx) {
    Resources res = getResources();
    for(int i = 0; i < NUM_PAGES; i++) {
        int drawableId = (i==idx)?(R.drawable.pager_dot_selected):(R.drawable.pager_dot_not_selected);
        Drawable drawable = res.getDrawable(drawableId);
        dots.get(i).setImageDrawable(drawable);
    }
}

What does CultureInfo.InvariantCulture mean?

JetBrains offer a reasonable explanation,

"Ad-hoc conversion of data structures to text is largely dependent on the current culture, and may lead to unintended results when the code is executed on a machine whose locale differs from that of the original developer. To prevent ambiguities, ReSharper warns you of any instances in code where such a problem may occur."

but if I am working on a site I know will be in English only, I just ignore the suggestion.

Getting values from query string in an url using AngularJS $location

Not sure if it has changed since the accepted answer was accepted, but it is possible.

$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:

{"test_user_bLzgB": true}

You could access this value directly with $location.search().test_user_bLzgB

Example (with larger query string): http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

Note: Due to hashes (as it will go to http://fiddle.jshell.net/#/url, which would create a new fiddle), this fiddle will not work in browsers that do not support js history (will not work in IE <10)

Edit:
As pointed out in the comments by @Naresh and @DavidTchepak, the $locationProvider also needs to be configured properly: https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, 
       sb.inact, sb.inadur, sb.inadist, 
       sb.smlct, sb.smldur, sb.smldist, 
       sb.larct, sb.lardur, sb.lardist, 
       sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct, 
       inact, inadur, inadist, 
       smlct, smldur, smldist, 
       larct, lardur, lardist, 
       emptyct, emptydur 
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...

how to download file using AngularJS and calling MVC API?

Here you have the angularjs http request to the API that any client will have to do. Just adapt the WS url and params (if you have) to your case. It's a mixture between Naoe's answer and this one:

$http({
    url: '/path/to/your/API',
    method: 'POST',
    params: {},
    headers: {
        'Content-type': 'application/pdf',
    },
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    // TODO when WS success
    var file = new Blob([data], {
        type: 'application/csv'
    });
    //trick to download store a file having its URL
    var fileURL = URL.createObjectURL(file);
    var a = document.createElement('a');
    a.href = fileURL;
    a.target = '_blank';
    a.download = 'yourfilename.pdf';
    document.body.appendChild(a); //create the link "a"
    a.click(); //click the link "a"
    document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
    //TODO when WS error
});

Explanation of the code:

  1. Angularjs request a file.pdf at the URL: /path/to/your/API.
  2. Success is received on the response
  3. We execute a trick with JavaScript on the front-end:
    • Create an html link ta: <a>.
    • Click the hyperlink <a> tag, using the JS click() function
  4. Remove the html <a> tag, after its click.

How comment a JSP expression?

Pure JSP comments look like this:

<%-- Comment --%>

So if you want to retain the "=".you could do something like:

<%--= map.size() --%>

The key thing is that <%= defines the beginning of an expression, in which you can't leave the body empty, but you could do something like this instead if the pure JSP comment doesn't appeal to you:

<% /*= map.size()*/ %>

Code Conventions for the JavaServer Pages Technology Version 1.x Language has details about the different commenting options available to you (but has a complete lack of link targets, so I can't link you directly to the relevant section - boo!)

Python 3 print without parenthesis

You can't, because the only way you could do it without parentheses is having it be a keyword, like in Python 2. You can't manually define a keyword, so no.

Should I make HTML Anchors with 'name' or 'id'?

I have to say if you are going to be linking to that area in the page... such as page.html#foo and Foo Title isn't a link you should be using:

<h1 id="foo">Foo Title</h1>

If you instead put an <a> reference around it your headline will be influenced by an <a> specific CSS within your site. It's just extra markup, and you shouldn't need it. I'd highly recommend placing an id on the headline, not only is it better formed, but it will allow you to either address that object in Javascript or CSS.

IE prompts to open or save json result from server

Have you tried to send your ajax request using POST method ? You could also try to set content type to 'text/x-json' while returning result from the server.

Remove 'b' character do in front of a string literal in Python 3

Here u Go

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)

How to change Windows 10 interface language on Single Language version

1) Upgrade using windows update or using "media creation tool" http://windows.microsoft.com/en-us/windows-10/media-creation-tool-install

  • if you are using "media creation tool" select "Upgrade this PC now"

When Windows 10 installed check that it is activated.

2) Now as you have activated Windows 10 using "media creation tool" http://windows.microsoft.com/en-us/windows-10/media-creation-tool-install select second option "Create installation media for another PC" here you can select Windows version and its language. Make sure that Windows version is also "Single Language"

3) Boot from you device, USB in my case and install clean Windows in English or any other language you selected.

reference http://bit.ly/1RKmPBs

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

Laravel 5 Clear Views Cache

Right now there is no view:clear command. For laravel 4 this can probably help you: https://gist.github.com/cjonstrup/8228165

Disabling caching can be done by skipping blade. View caching is done because blade compiling each time is a waste of time.

How to switch between python 2.7 to python 3 from command line?

There is an easier way than all of the above; You can use the PY_PYTHON environment variable. From inside the cmd.exe shell;

For the latest version of Python 2

set PY_PYTHON=2

For the latest version of Python 3

set PY_PYTHON=3

If you want it to be permanent, set it in the control panel. Or use setx instead of set in the cmd.exe shell.

Control the size of points in an R scatterplot?

As rcs stated, cex will do the job in base graphics package. I reckon that you're not willing to do your graph in ggplot2 but if you do, there's a size aesthetic attribute, that you can easily control (ggplot2 has user-friendly function arguments: instead of typing cex (character expansion), in ggplot2 you can type e.g. size = 2 and you'll get 2mm point).

Here's the example:

### base graphics ###
plot(mpg ~ hp, data = mtcars, pch = 16, cex = .9)

### ggplot2 ###
# with qplot()
qplot(mpg, hp, data = mtcars, size = I(2))
# or with ggplot() + geom_point()
ggplot(mtcars, aes(mpg, hp), size = 2) + geom_point()
# or another solution:
ggplot(mtcars, aes(mpg, hp)) + geom_point(size = 2)

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Suppress the @JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

This solved my similar problem. I used it to revert the changes, then I added everything and commited changes in the terminal with

svn add folder_path/*
svn commit -m "message"

How to use a different version of python during NPM install?

for quick one time use this works, npm install --python="c:\python27"

inserting characters at the start and end of a string

For completeness along with the other answers:

yourstring = "L%sLL" % yourstring

Or, more forward compatible with Python 3.x:

yourstring = "L{0}LL".format(yourstring)

How to pass multiple checkboxes using jQuery ajax post

Here's a more flexible way.

let's say this is your form.

<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>

And this is your jquery ajax below...

                // Don't get confused at this portion right here
                // cuz "var data" will get all the values that the form
                // has submitted in the $_POST. It doesn't matter if you 
                // try to pass a text or password or select form element.
                // Remember that the "form" is not a name attribute
                // of the form, but the "form element" itself that submitted
                // the current post method
                var data = $("form").serialize(); 

                $.ajax({
                    url: "link/of/your/ajax.php", // link of your "whatever" php
                    type: "POST",
                    async: true,
                    cache: false,
                    data: data, // all data will be passed here
                    success: function(data){ 
                        alert(data) // The data that is echoed from the ajax.php
                    }
                });

And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.

<?php 
    print_r($_POST); // this will be echoed back to you upon success.
    echo "This one too, will be echoed back to you";

Hope that is clear enough.

How to apply style classes to td classes?

A more definite way to target a td is table tr td { }

Get average color of image via Javascript

I recently came across a jQuery plugin which does what I originally wanted https://github.com/briangonzalez/jquery.adaptive-backgrounds.js in regards to getting a dominiate color from an image.

Imitating a blink tag with CSS3 animations

if you want some glow effect use this

@keyframes blink {
  50% {
    opacity: 0.0;
  }
}
@-webkit-keyframes blink {
  50% {
    opacity: 0.0;
  }
}

atom-text-editor::shadow  .bracket-matcher .region {
    border:none;
    background-color: rgba(195,195,255,0.1);
    border-bottom: 1px solid rgb(155,155,255);
    box-shadow: 0px 0px 9px 4px rgba(155,155,255,0.1);
    border-radius: 3px;
    animation: blink 2s steps(115, start) infinite;
    -webkit-animation: blink 2s steps(115, start) infinite;
}

Javascript getElementsByName.value not working

You have mentioned Wrong id

alert(document.getElementById("name").value);

if you want to use name attribute then

alert(document.getElementsByName("username")[0].value);

Updates:

input type="text" id="name" name="username"  

id is different from name

html script src="" triggering redirection with button

Your foldername is scripts ?

Change

<script src="../Script/login.js">

to

<script src='scripts/login.js' type='text/javascript'></script>

How do I clone a specific Git branch?

git checkout -b <branch-name> <origin/branch_name>

for example in my case:

 git branch -a
* master
  origin/HEAD
  origin/enum-account-number
  origin/master
  origin/rel_table_play
  origin/sugarfield_customer_number_show_c

So to create a new branch based on my enum-account-number branch I do:

git checkout -b enum-account-number origin/enum-account-number

After you hit return the following happens:

Branch enum-account-number set up to track remote branch refs/remotes/origin/enum-account-number.
Switched to a new branch "enum-account-number"

How to give ASP.NET access to a private key in a certificate in the certificate store?

  1. Create / Purchase certificate. Make sure it has a private key.
  2. Import the certificate into the "Local Computer" account. Best to use Certificates MMC. Make sure to check "Allow private key to be exported"
  3. Based upon which, IIS 7.5 Application Pool's identity use one of the following.

    • IIS 7.5 Website is running under ApplicationPoolIdentity. Open MMC => Add Certificates (Local computer) snap-in => Certificates (Local Computer) => Personal => Certificates => Right click the certificate of interest => All tasks => Manage private key => Add IIS AppPool\AppPoolName and grant it Full control. Replace "AppPoolName" with the name of your application pool (sometimes IIS_IUSRS)
    • IIS 7.5 Website is running under NETWORK SERVICE. Using Certificates MMC, added "NETWORK SERVICE" to Full Trust on certificate in "Local Computer\Personal".
    • IIS 7.5 Website is running under "MyIISUser" local computer user account. Using Certificates MMC, added "MyIISUser" (a new local computer user account) to Full Trust on certificate in "Local Computer\Personal".

Update based upon @Phil Hale comment:

Beware, if you're on a domain, your domain will be selected by default in the 'from location box'. Make sure to change that to "Local Computer". Change the location to "Local Computer" to view the app pool identities.

Pandas: Convert Timestamp to datetime.date

As of pandas 0.20.3, use .to_pydatetime() to convert any pandas.DateTimeIndex instances to Python datetime.datetime.

Strip off URL parameter with PHP

This should do it:

public function removeQueryParam(string $url, string $param): string
{
    $parsedUrl = parse_url($url);

    if (isset($parsedUrl[$param])) {
        $baseUrl = strtok($url, '?');
        parse_str(parse_url($url)['query'], $query);
        unset($query[$param]);
        return sprintf('%s?%s',
            $baseUrl,
            http_build_query($query)
        );
    }

    return $url;
}

Remove insignificant trailing zeros from a number?

Here's a possible solution:

var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001

eval(x) --> 1.234
eval(y) --> 1.234001

How do you get total amount of RAM the computer has?

.NIT has a limit to the amount of memory it can access of the total. Theres a percentage, and then 2 GB in xp was the hard ceiling.

You could have 4 GB in it, and it would kill the app when it hit 2GB.

Also in 64 bit mode, there is a percentage of memory you can use out of the system, so I'm not sure if you can ask for the whole thing or if this is specifically guarded against.

git push to specific branch

I would like to add an updated answer - now I have been using git for a while, I find that I am often using the following commands to do any pushing (using the original question as the example):

  • git push origin amd_qlp_tester - push to the branch located in the remote called origin on remote-branch called amd_qlp_tester.
  • git push -u origin amd_qlp_tester - same as last one, but sets the upstream linking the local branch to the remote branch so that next time you can just use git push/pull if not already linked (only need to do it once).
  • git push - Once you have set the upstream you can just use this shorter version.

Note -u option is the short version of --set-upstream - they are the same.

Python datetime to string without microsecond component

As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.

isoformat(timespec='seconds', sep=' ')

Usage:

>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'

Setting width of spreadsheet cell using PHPExcel

It's a subtle difference, but this works fine for me:

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);

Notice, the difference between getColumnDimensionByColumn and getColumnDimension

Also, I'm not even setting AutoSize and it works fine.

Understanding Linux /proc/id/maps

Please check: http://man7.org/linux/man-pages/man5/proc.5.html

address           perms offset  dev   inode       pathname
00400000-00452000 r-xp 00000000 08:02 173521      /usr/bin/dbus-daemon

The address field is the address space in the process that the mapping occupies.

The perms field is a set of permissions:

 r = read
 w = write
 x = execute
 s = shared
 p = private (copy on write)

The offset field is the offset into the file/whatever;

dev is the device (major:minor);

inode is the inode on that device.0 indicates that no inode is associated with the memoryregion, as would be the case with BSS (uninitialized data).

The pathname field will usually be the file that is backing the mapping. For ELF files, you can easily coordinate with the offset field by looking at the Offset field in the ELF program headers (readelf -l).

Under Linux 2.0, there is no field giving pathname.

How can I read the client's machine/computer name from the browser?

<html>
<body onload = "load()">
<script>
  function load(){ 

     try {
       var ax = new ActiveXObject("WScript.Network");
       alert('User: ' + ax.UserName );
       alert('Computer: ' + ax.ComputerName);
     }
     catch (e) {
       document.write('Permission to access computer name is denied' + '<br />');
     } 
  }
</script>
</body>
</html>

What can MATLAB do that R cannot do?

We can't because it's expected/required by our customers.

oracle varchar to number

You have to use the TO_NUMBER function:

select * from exception where exception_value = to_number('105')

Limiting the output of PHP's echo to 200 characters

echo strlen($row['style-info']) > 200) ? substr($row['style-info'], 0, 200)."..." : $row['style-info'];

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

The same problem I came across, but I solved by following these steps of code.

Step 1) npm install -g @angular/cli
Step 2) ng new my-angular-project
Step 3) cd my-angular-project
Step 4) ng serve --open

How to disable RecyclerView scrolling?

Override onTouchEvent() and onInterceptTouchEvent() and return false if you don't need OnItemTouchListener at all. This does not disable OnClickListeners of ViewHolders.

public class ScrollDisabledRecyclerView extends RecyclerView {
    public ScrollDisabledRecyclerView(Context context) {
        super(context);
    }

    public ScrollDisabledRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ScrollDisabledRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        return false;
    }
}

Enabling error display in PHP via htaccess only

I feel like adding more details to the existing answer:

# PHP error handling for development servers
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /full/path/to/file/php_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0

Give 777 or 755 permission to the log file and then add the code

<Files php_errors.log>
     Order allow,deny
     Deny from all
     Satisfy All
</Files>

at the end of .htaccess. This will protect your log file.

These options are suited for a development server. For a production server you should not display any error to the end user. So change the display flags to off.

For more information, follow this link: Advanced PHP Error Handling via htaccess

How to specify table's height such that a vertical scroll bar appears?

You need to wrap the table inside another element and set the height of that element. Example with inline css:

<div style="height: 500px; overflow: auto;">
 <table>
 </table>
</div>

How to dynamically add and remove form fields in Angular 2

That is the HTML code. Anyone can use this:

<div class="card-header">Contact Information</div>
          <div class="card-body" formArrayName="funds">
            <div class="row">
              <div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
                <div [formGroupName]="i" class="row">
                  <div class="form-group col-6">
                    <label>Type of Contact</label>
                    <select class="form-control" formControlName="fundName" type="text">
                      <option value="01">Balance Fund</option>
                      <option value="02">Equity Fund</option>
                    </select> 
                  </div>
                  <div class="form-group col-12">
                    <label>Allocation</label>
                    <input class="form-control" formControlName="allocation" type="number">
                    <span class="text-danger" *ngIf="getContactsFormGroup(i).controls['allocation'].touched && 
                    getContactsFormGroup(i).controls['allocation'].hasError('required')">
                        Allocation % is required! </span>
                  </div>
                  <div class="form-group col-12 text-right">
                    <button class="btn btn-danger" type="button" (click)="removeContact(i)"> Remove </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <button class="btn btn-primary m-1" type="button" (click)="addContact()"> Add Contact </button>

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

How to top, left justify text in a <td> cell that spans multiple rows

 <td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>

That should do it.

get specific row from spark dataframe

Following is a Java-Spark way to do it , 1) add a sequentially increment columns. 2) Select Row number using Id. 3) Drop the Column

import static org.apache.spark.sql.functions.*;
..

ds = ds.withColumn("rownum", functions.monotonically_increasing_id());
ds = ds.filter(col("rownum").equalTo(99));
ds = ds.drop("rownum");

N.B. monotonically_increasing_id starts from 0;

DLL References in Visual C++

The additional include directories are relative to the project dir. This is normally the dir where your project file, *.vcproj, is located. I guess that in your case you have to add just "include" to your include and library directories.

If you want to be sure what your project dir is, you can check the value of the $(ProjectDir) macro. To do that go to "C/C++ -> Additional Include Directories", press the "..." button and in the pop-up dialog press "Macros>>".

SQL How to remove duplicates within select query?

You mention that there are date duplicates, but it appears they're quite unique down to the precision of seconds.

Can you clarify what precision of date you start considering dates duplicate - day, hour, minute?

In any case, you'll probably want to floor your datetime field. You didn't indicate which field is preferred when removing duplicates, so this query will prefer the last name in alphabetical order.

 SELECT MAX(owner_name), 
        --floored to the second
        dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01') AS StartDate
 From   MyTable
 GROUP BY dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01')

How to parse JSON response from Alamofire API in Swift?

I found the answer on GitHub for Swift2

https://github.com/Alamofire/Alamofire/issues/641

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
    .responseJSON { request, response, result in
        switch result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

        case .Failure(let data, let error):
            print("Request failed with error: \(error)")

            if let data = data {
                print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
            }
        }
    }

Formatting Phone Numbers in PHP

Another option - easily updated to receive a format from configuration.

$numbers = explode("\n", '(111) 222-3333
((111) 222-3333
1112223333
111 222-3333
111-222-3333
(111)2223333
+11234567890
    1-8002353551
    123-456-7890   -Hello!
+1 - 1234567890
');
foreach( $numbers AS $number ){
  echo comMember_format::phoneNumber($number) . '<br>';
}

// ************************************************************************
// Format Phone Number
public function phoneNumber( $number ){
  $txt = preg_replace('/[\s\-|\.|\(|\)]/','',$number);
  $format = '[$1?$1 :][$2?($2):x][$3: ]$4[$5: ]$6[$7? $7:]';
  if( preg_match('/^(.*)(\d{3})([^\d]*)(\d{3})([^\d]*)(\d{4})([^\d]{0,1}.*)$/', $txt, $matches) ){
    $result = $format;
    foreach( $matches AS $k => $v ){
      $str = preg_match('/\[\$'.$k.'\?(.*?)\:(.*?)\]|\[\$'.$k.'\:(.*?)\]|(\$'.$k.'){1}/', $format, $filterMatch);
      if( $filterMatch ){
        $result = str_replace( $filterMatch[0], (!isset($filterMatch[3]) ? (strlen($v) ? str_replace( '$'.$k, $v, $filterMatch[1] ) : $filterMatch[2]) : (strlen($v) ? $v : (isset($filterMatch[4]) ? '' : (isset($filterMatch[3]) ? $filterMatch[3] : '')))), $result );
      }
    }
    return $result;
  }
  return $number;
}

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

I face the same issue. I am using docker version:17.09.0-ce.

I follow below steps:

  1. Create Dockerfile and added commands for creating docker image
  2. Go to directory where we have created Dockfile
  3. execute below command $ sudo docker build -t ubuntu-test:latest .

It resolved issue and image created successsfully.

Note: build command depend on docker version as well as which build option we are using. :)

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

Removing the textarea border in HTML

In CSS:

  textarea { 
    border-style: none; 
    border-color: Transparent; 
    overflow: auto;        
  }

Python Script Uploading files via FTP

ftplib now supports context managers so I guess it can be made even easier

from ftplib import FTP
from pathlib import Path

file_path = Path('kitten.jpg')

with FTP('server.address.com', 'USER', 'PWD') as ftp, open(file_path, 'rb') as file:
        ftp.storbinary(f'STOR {file_path.name}', file)

No need to close the file or the session

Convert a List<T> into an ObservableCollection<T>

ObervableCollection have constructor in which you can pass your list. Quoting MSDN:

 public ObservableCollection(
      List<T> list
 )

retrieve data from db and display it in table in php .. see this code whats wrong with it?

Here is the solution total html with php and database connections

   <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>database connections</title>
    </head>
    <body>
      <?php
      $username = "database-username";
      $password = "database-password";
      $host = "localhost";

      $connector = mysql_connect($host,$username,$password)
          or die("Unable to connect");
        echo "Connections are made successfully::";
      $selected = mysql_select_db("test_db", $connector)
        or die("Unable to connect");

      //execute the SQL query and return records
      $result = mysql_query("SELECT * FROM table_one ");
      ?>
      <table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
      <thead>
        <tr>
          <th>Employee_id</th>
          <th>Employee_Name</th>
          <th>Employee_dob</th>
          <th>Employee_Adress</th>
          <th>Employee_dept</th>
          <td>Employee_salary</td>
        </tr>
      </thead>
      <tbody>
        <?php
          while( $row = mysql_fetch_assoc( $result ) ){
            echo
            "<tr>
              <td>{$row\['employee_id'\]}</td>
              <td>{$row\['employee_name'\]}</td>
              <td>{$row\['employee_dob'\]}</td>
              <td>{$row\['employee_addr'\]}</td>
              <td>{$row\['employee_dept'\]}</td>
              <td>{$row\['employee_sal'\]}</td> 
            </tr>\n";
          }
        ?>
      </tbody>
    </table>
     <?php mysql_close($connector); ?>
    </body>
    </html>

Min and max value of input in angular4 application

If you are looking to validate length use minLength and maxLength instead.

jQuery "blinking highlight" effect on div?

If you are not already using the Jquery UI library and you want to mimic the effect what you can do is very simple

$('#blinkElement').fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100);

you can also play around with the numbers to get a faster or slower one to fit your design better.

This can also be a global jquery function so you can use the same effect across the site. Also note that if you put this code in a for loop you can have 1 milion pulses so therefore you are not restricted to the default 6 or how much the default is.

EDIT: Adding this as a global jQuery function

$.fn.Blink = function (interval = 100, iterate = 1) {
    for (i = 1; i <= iterate; i++)
        $(this).fadeOut(interval).fadeIn(interval);
}

Blink any element easily from your site using the following

$('#myElement').Blink(); // Will Blink once

$('#myElement').Blink(500); // Will Blink once, but slowly

$('#myElement').Blink(100, 50); // Will Blink 50 times once

Using custom std::set comparator

Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.

template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
    struct ftor {
        bool operator()( T const &l, T const &r )
            { return comp( l, r ); }
    };
public:
    typedef std::set< T, ftor > t;
};

// usage

bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!

Wow, I think that was worth the trouble!

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

*NgIf can create problem here , so either use display none css or easier way is to Use [hidden]="!condition"

Manually install Gradle and use it in Android Studio

in first step you should go to http://www.gradle.org/downloads and then choose your Gradle version and follow download link in GitHub and then download Gradle from GitHub. after your download is completed, you should extract the downloaded file in a directory (every directory that you want). finally open extracted folder and just run gradlew.bat and wait several minutes for completing download. and after completing download files, Gradle install itself automaticly. Gradle will work correctly for next times. i resolve this problem with this way and i tested it and every things are ok, so every one can test this way, it should working well. Good Luck.

Python - add PYTHONPATH during command line module run

You may try this to execute a function inside your script

python -c "import sys; sys.path.append('/your/script/path'); import yourscript; yourscript.yourfunction()"

How do I add target="_blank" to a link within a specified div?

Using jQuery:

 $('#link_other a').each(function(){
  $(this).attr('target', '_BLANK');
 });

SQL Server: Invalid Column Name

There can be many things:
First attempt, make a select of this field in its source table;
Check the instance of the sql script window, you may be in a different instance;
Check if your join is correct;
Verify query ambiguity, maybe you are making a wrong table reference
Of these checks, run the T-sql script again

[Image of the script SQL][1]
  [1]: https://i.stack.imgur.com/r59ZY.png`enter code here

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Dockerfile if else condition with external arguments

You can use the conditional system that best fits your needs.

Dockerfile

ARG ENV

FROM foo as base

ARG ENV

# run common
RUN ...

# For long running tasks that would slow down deployments
RUN if [[ "$ENV" == "dev" ]] ; then \
        yum install -y lots of big dev packages ; \
    fi

# Build dev image
FROM base as image-dev

RUN ...
COPY ...

# Build prod image
FROM base as image-prod

RUN ...
COPY ...

FROM image-$ENV AS final

Note that we define ENV twice - you need to define ENV globally, and in each image where it is used.

Use docker:

docker build -t my_docker . --build-arg ENV="dev"

Use docker-compose:

version: '3'

services:

  dev:
    container_name: dev
    ports:
      - 3000:8080
    volumes:
      - ./:/var/task
    tty: true
    build:
      context: .
      dockerfile: Dockerfile
      args:
        ENV: dev
docker-compose build --no-cache dev && docker-compose up dev

What's the best practice using a settings file in Python?

You can have a regular Python module, say config.py, like this:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

and use it like this:

import config
print(config.truck['color'])  

Differences in boolean operators: & vs && and | vs ||

In Java, the single operators &, |, ^, ! depend on the operands. If both operands are ints, then a bitwise operation is performed. If both are booleans, a "logical" operation is performed.

If both operands mismatch, a compile time error is thrown.

The double operators &&, || behave similarly to their single counterparts, but both operands must be conditional expressions, for example:

if (( a < 0 ) && ( b < 0 )) { ... } or similarly, if (( a < 0 ) || ( b < 0 )) { ... }

source: java programming lang 4th ed

Can I open a dropdownlist using jQuery

You can easily simulate a click on an element, but a click on a <select> won’t open up the dropdown.

Using multiple selects can be problematic. Perhaps you should consider radio buttons inside a container element which you can expand and contract as needed.

How to Load an Assembly to AppDomain with all references recursively?

I have had to do this several times and have researched many different solutions.

The solution I find in most elegant and easy to accomplish can be implemented as such.

1. Create a project that you can create a simple interface

the interface will contain signatures of any members you wish to call.

public interface IExampleProxy
{
    string HelloWorld( string name );
}

Its important to keep this project clean and lite. It is a project that both AppDomain's can reference and will allow us to not reference the Assembly we wish to load in seprate domain from our client assembly.

2. Now create project that has the code you want to load in seperate AppDomain.

This project as with the client proj will reference the proxy proj and you will implement the interface.

public interface Example : MarshalByRefObject, IExampleProxy
{
    public string HelloWorld( string name )
    {
        return $"Hello '{ name }'";
    }
}

3. Next, in the client project, load code in another AppDomain.

So, now we create a new AppDomain. Can specify the base location for assembly references. Probing will check for dependent assemblies in GAC and in current directory and the AppDomain base loc.

// set up domain and create
AppDomainSetup domaininfo = new AppDomainSetup
{
    ApplicationBase = System.Environment.CurrentDirectory
};

Evidence adevidence = AppDomain.CurrentDomain.Evidence;

AppDomain exampleDomain = AppDomain.CreateDomain("Example", adevidence, domaininfo);

// assembly ant data names
var assemblyName = "<AssemblyName>, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null|<keyIfSigned>";
var exampleTypeName = "Example";

// Optional - get a reflection only assembly type reference
var @type = Assembly.ReflectionOnlyLoad( assemblyName ).GetType( exampleTypeName ); 

// create a instance of the `Example` and assign to proxy type variable
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( assemblyName, exampleTypeName );

// Optional - if you got a type ref
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( @type.Assembly.Name, @type.Name );    

// call any members you wish
var stringFromOtherAd = proxy.HelloWorld( "Tommy" );

// unload the `AppDomain`
AppDomain.Unload( exampleDomain );

if you need to, there are a ton of different ways to load an assembly. You can use a different way with this solution. If you have the assembly qualified name then I like to use the CreateInstanceAndUnwrap since it loads the assembly bytes and then instantiates your type for you and returns an object that you can simple cast to your proxy type or if you not that into strongly-typed code you could use the dynamic language runtime and assign the returned object to a dynamic typed variable then just call members on that directly.

There you have it.

This allows to load an assembly that your client proj doesnt have reference to in a seperate AppDomain and call members on it from client.

To test, I like to use the Modules window in Visual Studio. It will show you your client assembly domain and what all modules are loaded in that domain as well your new app domain and what assemblies or modules are loaded in that domain.

The key is to either make sure you code either derives MarshalByRefObject or is serializable.

`MarshalByRefObject will allow you to configure the lifetime of the domain its in. Example, say you want the domain to destroy if the proxy hasnt been called in 20 minutes.

I hope this helps.

Using NotNull Annotation in method argument

If you are using Spring, you can force validation by annotating the class with @Validated:

import org.springframework.validation.annotation.Validated;

More info available here: Javax validation @NotNull annotation usage

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

How to create a date object from string in javascript

First extract the string like this

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

Then,

var d = new Date( dateString[3], dateString[2]-1, dateString[1] );

How to respond to clicks on a checkbox in an AngularJS directive?

This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).

The markup

<table class="table">
  <thead>
    <tr>
      <th>
        <input type="checkbox" 
          ng-click="selectAll($event)"
          ng-checked="isSelectedAll()">
      </th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
      <td>
        <input type="checkbox" name="selected"
          ng-checked="isSelected(e.id)"
          ng-click="updateSelection($event, e.id)">
      </td>
      <td>{{e.title}}</td>
    </tr>
  </tbody>
</table>

And in the controller

var updateSelected = function(action, id) {
  if (action === 'add' && $scope.selected.indexOf(id) === -1) {
    $scope.selected.push(id);
  }
  if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
    $scope.selected.splice($scope.selected.indexOf(id), 1);
  }
};

$scope.updateSelection = function($event, id) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  updateSelected(action, id);
};

$scope.selectAll = function($event) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  for ( var i = 0; i < $scope.entities.length; i++) {
    var entity = $scope.entities[i];
    updateSelected(action, entity.id);
  }
};

$scope.getSelectedClass = function(entity) {
  return $scope.isSelected(entity.id) ? 'selected' : '';
};

$scope.isSelected = function(id) {
  return $scope.selected.indexOf(id) >= 0;
};

//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
  return $scope.selected.length === $scope.entities.length;
};

EDIT: getSelectedClass() expects the entire entity but it was being called with the id of the entity only, which is now corrected

Handle JSON Decode Error when nothing returned

If you don't mind importing the json module, then the best way to handle it is through json.JSONDecodeError (or json.decoder.JSONDecodeError as they are the same) as using default errors like ValueError could catch also other exceptions not necessarily connected to the json decode one.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want

//EDIT (Oct 2020):

As @Jacob Lee noted in the comment, there could be the basic common TypeError raised when the JSON object is not a str, bytes, or bytearray. Your question is about JSONDecodeError, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want
except TypeError as e:
    # do whatever you want in this case

How to change the default GCC compiler in Ubuntu?

Here's a complete example of jHackTheRipper's answer for the TL;DR crowd. :-) In this case, I wanted to run g++-4.5 on an Ubuntu system that defaults to 4.6. As root:

apt-get install g++-4.5
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 100
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.5 50
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 100
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.5 50
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.6 100
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.5 50
update-alternatives --set g++ /usr/bin/g++-4.5
update-alternatives --set gcc /usr/bin/gcc-4.5
update-alternatives --set cpp-bin /usr/bin/cpp-4.5

Here, 4.6 is still the default (aka "auto mode"), but I explicitly switch to 4.5 temporarily (manual mode). To go back to 4.6:

update-alternatives --auto g++
update-alternatives --auto gcc
update-alternatives --auto cpp-bin

(Note the use of cpp-bin instead of just cpp. Ubuntu already has a cpp alternative with a master link of /lib/cpp. Renaming that link would remove the /lib/cpp link, which could break scripts.)

CSS selector for a checked radio button's label

If your input is a child element of the label and you have more than one labels, you can combine @Mike's trick with Flexbox + order.

enter image description here

_x000D_
_x000D_
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }



/* style the switch */

:root {
  --radio-size: 14px;
}

.switchLabel input.switch  {
  width: var(--radio-size);
  height: var(--radio-size);
  border-radius: 50%;
  border: 1px solid #999999;
  box-sizing: border-box;
  outline: none;
  -webkit-appearance: inherit;
  -moz-appearance: inherit;
  appearance: inherit;
  
  box-shadow: calc(var(--radio-size) / 2) 0 0 0 gray, calc(var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 calc(5px + var(--radio-size) / 2) 0 5px;
}

.switchLabel input.switch:checked {
  box-shadow: calc(-1 * var(--radio-size) / 2) 0 0 0 gray, calc(-1 * var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 5px 0 calc(5px + var(--radio-size) / 2);
}
_x000D_
<label class="switchLabel">
  <input type="checkbox" class="switch" />
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
_x000D_
_x000D_
_x000D_ asd

html
<label class="switchLabel">
  <input type="checkbox" class="switch"/>
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
css
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }

See it on JSFiddle.

note: Sibling selector only works within the same parent. To work around this, you can make the input hidden at top-level using @Nathan Blair hack.

How do I return multiple values from a function in C?

Create a struct and set two values inside and return the struct variable.

struct result {
    int a;
    char *string;
}

You have to allocate space for the char * in your program.

What is a PDB file?

PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.

This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb files. So effectively pdb files are really a boon to developers while debugging a program.

Generally it is not recommended to exclude the generation of *.pdb files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.

If you still want to disable generation of *.pdb files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none from "Debug Info" drop-down box -> press OK as shown in the snapshot below.

None Debug Info setting for a C# Project

Note: This setting will have to be done separately for "Debug" and "Release" build configurations.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

How to set encoding in .getJSON jQuery

I think that you'll probably have to use $.ajax() if you want to change the encoding, see the contentType param below (the success and error callbacks assume you have <div id="success"></div> and <div id="error"></div> in the html):

$.ajax({
    type: "POST",
    url: "SomePage.aspx/GetSomeObjects",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (xhr, textStatus, errorThrown) {
        $("#error").html(xhr.responseText);
    }
});

I actually just had to do this about an hour ago, what a coincidence!

Remove the last three characters from a string

myString = myString.Remove(myString.Length - 3, 3);

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

I had this problem and its because I wasnt using the latest version of C# (C# 7.3 as of writing this) and I had to change the below internal access modifier to public.

internal class Program
 {
    public static void Main(string[] args)
    {
        //My Code
    }
  }

or ammend the .csproj to use the latest version of C# (this way meant I could still keep the above class as internal):

<PropertyGroup>
    <LangVersion>latest</LangVersion>
    <NoWin32Manifest>true</NoWin32Manifest>
</PropertyGroup>

Create instance of generic type in Java?

As you said, you can't really do it because of type erasure. You can sort of do it using reflection, but it requires a lot of code and lot of error handling.

Search for "does-not-contain" on a DataFrame in pandas

I hope the answers are already posted

I am adding the framework to find multiple words and negate those from dataFrame.

Here 'word1','word2','word3','word4' = list of patterns to search

df = DataFrame

column_a = A column name from from DataFrame df

Search_for_These_values = ['word1','word2','word3','word4'] 

pattern = '|'.join(Search_for_These_values)

result = df.loc[~(df['column_a'].str.contains(pattern, case=False)]

How do I parse JSON with Ruby on Rails?

Here's what I would do:

json = "{\"errorCode\":0,\"errorMessage\":\"\",\"results\":{\"http://www.foo.com\":{\"hash\":\"e5TEd\",\"shortKeywordUrl\":\"\",\"shortUrl\":\"http://b.i.t.ly/1a0p8G\",\"userHash\":\"1a0p8G\"}},\"statusCode\":\"OK\"}"

hash = JSON.parse(json)
results = hash[:results]

If you know the source url then you can use:

source_url = "http://www.foo.com".to_sym

results.fetch(source_url)[:shortUrl]
=> "http://b.i.t.ly/1a0p8G"

If you don't know the key for the source url you can do the following:

results.fetch(results.keys[0])[:shortUrl]
=> "http://b.i.t.ly/1a0p8G"

If you're not wanting to lookup keys using symbols, you can convert the keys in the hash to strings:

results = json[:results].stringify_keys

results.fetch(results.keys[0])["shortUrl"]
=> "http://b.i.t.ly/1a0p8G"

If you're concerned the JSON structure might change you could build a simple JSON Schema and validate the JSON before attempting to access keys. This would provide a guard.

NOTE: Had to mangle the bit.ly url because of posting rules.

What does the C++ standard state the size of int, long type to be?

unsigned char bits = sizeof(X) << 3;

where X is a char,int,long etc.. will give you size of X in bits.

How to find Current open Cursors in Oracle

Here's how to find open cursors that have been parsed. You need to be logged in as a user with access to v$open_cursor and v$session.

COLUMN USER_NAME FORMAT A15

SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
GROUP BY user_name, sql_text, machine
HAVING COUNT(1) > 2
ORDER BY count(1) DESC
;

If gives you part of the SQL text so it can be useful for identifying leaky applications. If a cursor has not been parsed, then it does not appear here. Note that Oralce will sometimes keep things open longer than you do.

Convert JsonNode into POJO

This should do the trick:

mapper.readValue(fileReader, MyClass.class);

I say should because I'm using that with a String, not a BufferedReader but it should still work.

Here's my code:

String inputString = // I grab my string here
MySessionClass sessionObject;
try {
    ObjectMapper objectMapper = new ObjectMapper();
    sessionObject = objectMapper.readValue(inputString, MySessionClass.class);

Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)

You can also define a custom deserializer when you instantiate the ObjectMapper: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

Edit: I just remembered something else. If your object coming in has more properties than the POJO has and you just want to ignore the extras you'll want to set this:

    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Or you'll get an error that it can't find the property to set into.

Failed to build gem native extension — Rails install

sudo apt-get install ruby-dev

worked for me

.NET Events - What are object sender & EventArgs e?

The sender is the control that the action is for (say OnClick, it's the button).

The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.

What Chris is saying is you can do this:

protected void someButton_Click (object sender, EventArgs ea)
{
    Button someButton = sender as Button;
    if(someButton != null)
    {
        someButton.Text = "I was clicked!";
    }
}

Spring Boot how to hide passwords in properties file

You can use Jasypt to encrypt properties, so you could have your property like this:

db.password=ENC(XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=)

Jasypt allows you to encrypt your properties using different algorithms, once you get the encrypted property you put inside the ENC(...). For instance, you can encrypt this way through Jasypt using the terminal:

encrypted-pwd$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="contactspassword" password=supersecretz algorithm=PBEWithMD5AndDES

----ENVIRONMENT-----------------

Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 24.45-b08



----ARGUMENTS-------------------

algorithm: PBEWithMD5AndDES
input: contactspassword
password: supersecretz



----OUTPUT----------------------

XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=

To easily configure it with Spring Boot you can use its starter jasypt-spring-boot-starter with group ID com.github.ulisesbocchio

Keep in mind, that you will need to start your application using the same password you used to encrypt the properties. So, you can start your app this way:

mvn -Djasypt.encryptor.password=supersecretz spring-boot:run

Or using the environment variable (thanks to spring boot relaxed binding):

export JASYPT_ENCRYPTOR_PASSWORD=supersecretz
mvn spring-boot:run

You can check below link for more details:

https://www.ricston.com/blog/encrypting-properties-in-spring-boot-with-jasypt-spring-boot/

To use your encrypted properties in your app just use it as usual, use either method you like (Spring Boot wires the magic, anyway the property must be of course in the classpath):

Using @Value annotation

@Value("${db.password}")
private String password;

Or using Environment

@Autowired
private Environment environment;

public void doSomething(Environment env) {
    System.out.println(env.getProperty("db.password"));
}

Update: for production environment, to avoid exposing the password in the command line, since you can query the processes with ps, previous commands with history, etc etc. You could:

  • Create a script like this: touch setEnv.sh
  • Edit setEnv.sh to export the JASYPT_ENCRYPTOR_PASSWORD variable

    #!/bin/bash

    export JASYPT_ENCRYPTOR_PASSWORD=supersecretz

  • Execute the file with . setEnv.sh
  • Run the app in background with mvn spring-boot:run &
  • Delete the file setEnv.sh
  • Unset the previous environment variable with: unset JASYPT_ENCRYPTOR_PASSWORD

Undefined Reference to

g++ test.cpp LinearNode.cpp LinkedList.cpp -o test

Can I have H2 autocreate a schema in an in-memory database?

If you are using spring with application.yml the following will work for you

spring: datasource: url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar

PHP-FPM doesn't write to error log

Check the Owner directory of "PHP-FPM"

You can do:

ls -lah /var/log/php-fpm/
chown -R webusr:webusr /var/log/php-fpm/
chmod -R 777 /var/log/php-fpm/

What is the C++ function to raise a number to a power?

I don't have enough reputation to comment, but if you like working with QT, they have their own version.

    #include <QtCore/qmath.h>
    qPow(x, y); // returns x raised to the y power.

Or if you aren't using QT, cmath has basically the same thing.

    #include <cmath>
    double x = 5, y = 7; //As an example, 5 ^ 7 = 78125
    pow(x, y); //Should return this: 78125

How do I set the default Java installation/runtime (Windows)?

This is a bit of a pain on Windows. Here's what I do.

Install latest Sun JDK, e.g. 6u11, in path like c:\install\jdk\sun\6u11, then let the installer install public JRE in the default place (c:\program files\blah). This will setup your default JRE for the majority of things.

Install older JDKs as necessary, like 5u18 in c:\install\jdk\sun\5u18, but don't install the public JREs.

When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set JAVA_HOME=c:\jdk\sun\JDK_DESIRED and then set PATH=%JAVA_HOME%\bin;%PATH%. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the JAVA_HOME variable.

The path is important because most public JRE installs put a linked executable at c:\WINDOWS\System32\java.exe, which usually overrides most other settings.

RESTful URL design for search

For the searching, use querystrings. This is perfectly RESTful:

/cars?color=blue&type=sedan&doors=4

An advantage to regular querystrings is that they are standard and widely understood and that they can be generated from form-get.

$rootScope.$broadcast vs. $scope.$emit

Use RxJS in a Service

What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately

Build a service with RxJS Extensions for Angular.

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

app.factory("DataService", function(rx) {
  var subject = new rx.Subject(); 
  var data = "Initial";

  return {
      set: function set(d){
        data = d;
        subject.onNext(d);
      },
      get: function get() {
        return data;
      },
      subscribe: function (o) {
         return subject.subscribe(o);
      }
  };
});

Then simply subscribe to the changes.

app.controller('displayCtrl', function(DataService) {
  var $ctrl = this;

  $ctrl.data = DataService.get();
  var subscription = DataService.subscribe(function onNext(d) {
      $ctrl.data = d;
  });

  this.$onDestroy = function() {
      subscription.dispose();
  };
});

Clients can subscribe to changes with DataService.subscribe and producers can push changes with DataService.set.

The DEMO on PLNKR.

Multiplying Two Columns in SQL Server

Syntax:

SELECT <Expression>[Arithmetic_Operator]<expression>...
 FROM [Table_Name] 
 WHERE [expression];
  1. Expression : Expression made up of a single constant, variable, scalar function, or column name and can also be the pieces of a SQL query that compare values against other values or perform arithmetic calculations.
  2. Arithmetic_Operator : Plus(+), minus(-), multiply(*), and divide(/).
  3. Table_Name : Name of the table.

element not interactable exception in selenium web automation

I had the same problem and then figured out the cause. I was trying to type in a span tag instead of an input tag. My XPath was written with a span tag, which was a wrong thing to do. I reviewed the Html for the element and found the problem. All I then did was to find the input tag which happens to be a child element. You can only type in an input field if your XPath is created with an input tagname

Missing Maven dependencies in Eclipse project

for me issue was due to multi module project .

  1. delete project from disk
  2. checkout project from your repo and import as maven project in eclipse
  3. clean install

How to set fake GPS location on IOS real device

xCode is picky about the GPX file it accepts.

But, in xCode you can create a GPX file with the format it will accept:

enter image description here

enter image description here

enter image description here

And then just change the content of the file to the location you need.

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Dependent DLL is not getting copied to the build output folder in Visual Studio

Just a sidenote to Overlord Zurg's answer.

I've added the dummy reference this way, and it worked in Debug mode:

public class DummyClass
{
    private static void Dummy()
    {
        var dummy = typeof(AbcDll.AnyClass);
    }
}

But in Release mode, the dependent dll still did not get copied.
This worked however:

public class DummyClass
{
    private static void Dummy()
    {
        Action<Type> noop = _ => {};
        var dummy = typeof(AbcDll.AnyClass);
        noop(dummy);
    }
}

This infomation actually costed me hours to figure out, so I thought I share it.

Pointer to incomplete class type is not allowed

One thing to check for...

If your class is defined as a typedef:

typedef struct myclass { };

Then you try to refer to it as struct myclass anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:

typedef struct mystruct {}...

struct mystruct *myvar = value;

Instead use...

mystruct *myvar = value;

Common mistake.

How to make graphics with transparent background in R using ggplot2?

Just to improve YCR's answer:

1) I added black lines on x and y axis. Otherwise they are made transparent too.

2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.

Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.

MyTheme_transparent <- theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
    legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
    axis.line = element_line(colour = "black") # adding a black line for x and y axis
)

MVC 4 Razor File Upload

you just have to change the name of your input filed because same name is required in parameter and input field name just replace this line Your code working fine

 <input type="file" name="file" />

Relative instead of Absolute paths in Excel VBA

Just to clarify what yalestar said, this will give you the relative path:

Workbooks.Open FileName:= ThisWorkbook.Path & "\TRICATEndurance Summary.html"

concat scope variables into string in angular directive expression

<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

On https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest I found this snippet that uses internal js module:

async function sha256(message) {
    // encode as UTF-8
    const msgBuffer = new TextEncoder().encode(message);                    

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string                  
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
}

Note that crypto.subtle in only available on https or localhost - for example for your local development with python3 -m http.server you need to add this line to your /etc/hosts: 0.0.0.0 localhost

Reboot - and you can open localhost:8000 with working crypto.subtle.

ASP.NET email validator regex

Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator

How do I use a pipe to redirect the output of one command to the input of another?

This should work:

for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i

If running in a batch file, you need to use %%i instead of just %i (in both places).

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

LINQ's Distinct() on a particular property

Please give a try with below code.

var Item = GetAll().GroupBy(x => x .Id).ToList();

Call JavaScript function on DropDownList SelectedIndexChanged Event:

First Method: (Tested)

Code in .aspx.cs:

 protected void Page_Load(object sender, EventArgs e)
    {
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
        if (!Page.IsPostBack)
        {
            ddl.Attributes.Add("onchange", "CalcTotalAmt();");
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
       //Your Code
    }

JavaScript function: return true from your JS function

   function CalcTotalAmt() 
 {
//Your Code
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

Second Method: (Tested)

Code in .aspx.cs:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
                ddl_SelectedIndexChanged(sender, e);
            if (!Page.IsPostBack)
            {
                ddl.Attributes.Add("onchange", "CalcTotalAmt();");
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Your Code
        }

JavaScript function: return true from your JS function

function CalcTotalAmt() {
         //Your Code
     __doPostBack("ctl00$MainContent$ddl","ddlchange");
 }

.aspx code:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

"commence before first target. Stop." error

It's a simple Mistake while adding a new file you just have to make sure that \ is added to the file before and the new file remain as it is eg.

Check Out what to do if i want to add a new file named customer.cc

Add a common Legend for combined ggplots

If the legend is the same for both plots, there is a simple solution using grid.arrange(assuming you want your legend to align with both plots either vertically or horizontally). Simply keep the legend for the bottom-most or right-most plot while omitting the legend for the other. Adding a legend to just one plot, however, alters the size of one plot relative to the other. To avoid this use the heights command to manually adjust and keep them the same size. You can even use grid.arrange to make common axis titles. Note that this will require library(grid) in addition to library(gridExtra). For vertical plots:

y_title <- expression(paste(italic("E. coli"), " (CFU/100mL)"))

grid.arrange(arrangeGrob(p1, theme(legend.position="none"), ncol=1), 
   arrangeGrob(p2, theme(legend.position="bottom"), ncol=1), 
   heights=c(1,1.2), left=textGrob(y_title, rot=90, gp=gpar(fontsize=20)))

Here is the result for a similar graph for a project I was working on: enter image description here

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Java: Unresolved compilation problem

try to clean the eclipse project

Send inline image in email

In addition to the comments above, I have the following additional comments:

  • Do not mix Attachments and AlternativeView, use one or the other. If you mix them, the inline attachments will be rendered as unknown downloads.
  • While Outlook and Google allow standard HTML-style "cid:att-001" this does NOT work on iPhone (late 2016 patch level), rather use pure alpha numeric "cid:att-001" -> "cid:att001"

As an aside: Outlook (even Office 2015) rendering (still the clear majority for business users) requires the use of TABLE TR TD style HTML, as it does not fully support the HTML box model.