Programs & Examples On #Protected

`protected` is an access specifier in object-oriented languages. When the members of a class are `protected`, there is restricted access to these members for other classes.

What are access specifiers? Should I inherit with private, protected or public?

what are Access Specifiers?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:

  • Private Inheritance
  • Public Inheritance
  • Protected inheritance

Here are the member access rules with respect to each of these:

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:public Base
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Allowed
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:protected Base  
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
        b = 20;  //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.


Important points to note:

- Access Specification is per-Class not per-Object

Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.

- A Derived class can only access members of its own Base class

Consider the following code example:

class Myclass
{ 
    protected: 
       int x; 
}; 

class derived : public Myclass
{
    public: 
        void f( Myclass& obj ) 
        { 
            obj.x = 5; 
        } 
};

int main()
{
    return 0;
}

It gives an compilation error:

prog.cpp:4: error: ‘int Myclass::x’ is protected

Because the derived class can only access members of its own Base Class. Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members.


What is a friend? How does friend affect access specification rules?

You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friended class/function. The class or function can access all the members of that particular class.

So do friends break Encapsulation?

No they don't, On the contrary they enhance Encapsulation!

friendship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.

What is the difference between public, private, and protected?

When we follow object oriented php in our project , we should follow some rules to use access modifiers in php. Today we are going to learn clearly what is access modifier and how can we use it.PHP access modifiers are used to set access rights with PHP classes and their members that are the functions and variables defined within the class scope. In php there are three scopes for class members.

  1. PUBLIC
  2. PRIVATE
  3. PROTECTED

Now, let us have a look at the following image to understand access modifier access level enter image description here

Now, let us have a look at the following list to know about the possible PHP keywords used as access modifiers.

public :- class or its members defined with this access modifier will be publicly accessible from anywhere, even from outside the scope of the class.

private :- class members with this keyword will be accessed within the class itself. we can’t access private data from subclass. It protects members from outside class access.

protected :- same as private, except by allowing subclasses to access protected superclass members.

Now see the table to understand access modifier Read full article php access modifire

What is the difference between public, protected, package-private and private in Java?

  • public - accessible from anywhere in the application.

  • default - accessible from package.

  • protected - accessible from package and sub-classes in other package. as well

  • private - accessible from its class only.

What is the difference between private and protected members of C++ classes?

A protected nonstatic base class member can be accessed by members and friends of any classes derived from that base class by using one of the following:

  • A pointer to a directly or indirectly derived class
  • A reference to a directly or indirectly derived class
  • An object of a directly or indirectly derived class

In Java, how do I parse XML as a String instead of a file?

I'm using this method

public Document parseXmlFromString(String xmlString){
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new    ByteArrayInputStream(xmlString.getBytes());
    org.w3c.dom.Document document = builder.parse(inputStream);
    return document;
}

What is a segmentation fault?

To be honest, as other posters have mentioned, Wikipedia has a very good article on this so have a look there. This type of error is very common and often called other things such as Access Violation or General Protection Fault.

They are no different in C, C++ or any other language that allows pointers. These kinds of errors are usually caused by pointers that are

  1. Used before being properly initialised
  2. Used after the memory they point to has been realloced or deleted.
  3. Used in an indexed array where the index is outside of the array bounds. This is generally only when you're doing pointer math on traditional arrays or c-strings, not STL / Boost based collections (in C++.)

Dropping Unique constraint from MySQL table

If you want to remove unique constraints from mysql database table, use alter table with drop index.

Example:

create table unique_constraints(unid int,activity_name varchar(100),CONSTRAINT activty_uqniue UNIQUE(activity_name),primary key (unid));

alter table unique_constraints drop index activty_uqniue;

Where activty_uqniue is UNIQUE constraint for activity_name column.

How can you flush a write using a file descriptor?

You have two choices:

  1. Use fileno() to obtain the file descriptor associated with the stdio stream pointer

  2. Don't use <stdio.h> at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write() call won't even return until the lower-level IO has completed (in theory).

For device-level IO I'd say it's pretty unusual to use stdio. I'd strongly recommend using the lower-level open(), read() and write() functions instead (based on your later reply):

int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);

How to draw vectors (physical 2D/3D vectors) in MATLAB?

a = [2 3 5];
b = [1 1 0];
c = a+b;

starts = zeros(3,3);
ends = [a;b;c];

quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3))
axis equal

How to display a jpg file in Python?

Don't forget to include

import Image

In order to show it use this :

Image.open('pathToFile').show()

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

How to convert an Image to base64 string in java?

I think you might want:

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

How to detect when an Android app goes to the background and come back to the foreground

Consider using onUserLeaveHint. This will only be called when your app goes into the background. onPause will have corner cases to handle, since it can be called for other reasons; for example if the user opens another activity in your app such as your settings page, your main activity's onPause method will be called even though they are still in your app; tracking what is going in will lead to bugs when you can instead simply use the onUserLeaveHint callback which does what you are asking.

When on UserLeaveHint is called, you can set a boolean inBackground flag to true. When onResume is called, only assume you came back into the foreground if the inBackground flag is set. This is because onResume will also be called on your main activity if the user was just in your settings menu and never left the app.

Remember that if the user hits the home button while in your settings screen, onUserLeaveHint will be called in your settings activity, and when they return onResume will be called in your settings activity. If you only have this detection code in your main activity you will miss this use case. To have this code in all your activities without duplicating code, have an abstract activity class which extends Activity, and put your common code in it. Then each activity you have can extend this abstract activity.

For example:

public abstract AbstractActivity extends Activity {
    private static boolean inBackground = false;

    @Override
    public void onResume() {
        if (inBackground) {
            // You just came from the background
            inBackground = false;
        }
        else {
            // You just returned from another activity within your own app
        }
    }

    @Override
    public void onUserLeaveHint() {
        inBackground = true;
    }
}

public abstract MainActivity extends AbstractActivity {
    ...
}

public abstract SettingsActivity extends AbstractActivity {
    ...
}

Hibernate: hbm2ddl.auto=update in production?

I agree with Vladimir. The administrators in my company would definitely not appreciate it if I even suggested such a course.

Further, creating an SQL script in stead of blindly trusting Hibernate gives you the opportunity to remove fields which are no longer in use. Hibernate does not do that.

And I find comparing the production schema with the new schema gives you even better insight to wat you changed in the data model. You know, of course, because you made it, but now you see all the changes in one go. Even the ones which make you go like "What the heck?!".

There are tools which can make a schema delta for you, so it isn't even hard work. And then you know exactly what's going to happen.

HTML tag inside JavaScript

JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document.write to display things on browser. Also if your document.write exceeds one line, make sure to put concatenation + at the end of each line.

Example

<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello" +
"member</h1>");
}
</script>

How to run multiple SQL commands in a single SQL connection?

Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.

// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();

// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();

Error You must specify a region when running command aws ecs list-container-instances

I think you need to use for example:

aws ecs list-container-instances --cluster default --region us-east-1

This depends of your region of course.

What is the meaning of "Failed building wheel for X" in pip install?

(pip maintainer here!)

If the package is not a wheel, pip tries to build a wheel for it (via setup.py bdist_wheel). If that fails for any reason, you get the "Failed building wheel for pycparser" message and pip falls back to installing directly (via setup.py install).

Once we have a wheel, pip can install the wheel by unpacking it correctly. pip tries to install packages via wheels as often as it can. This is because of various advantages of using wheels (like faster installs, cache-able, not executing code again etc).


Your error message here is due to the wheel package being missing, which contains the logic required to build the wheels in setup.py bdist_wheel. (pip install wheel can fix that.)


The above is the legacy behavior that is currently the default; we'll switch to PEP 517 by default, sometime in the future, moving us to a standards-based process for this. We also have isolated builds for that so, you'd have wheel installed in those environments by default. :)

Cannot find java. Please use the --jdkhome switch

In my case, I had installed *ahem* OpenJDK, but the bin folder was full of symlinks to the bundled JRE and the actual JDK was nowhere to be found.

When I see a directory structure with bin and jre subdirectories I expect this to be the JDK installation, because JRE installations on Windows looked different. But in this case it was the JRE installation as found out by apt search. After installing openjdk-8-jre the simlinks were replaced and the directory structure otherwise stayed the same.

How to read file using NPOI

It might be helpful to rely on the Workbook factory to instantiate the workbook object since the factory method will do the detection of xls or xlsx for you. Reference: http://apache-poi.1045710.n5.nabble.com/How-to-check-for-valid-excel-files-using-POI-without-checking-the-file-extension-td2341055.html

IWorkbook workbook = WorkbookFactory.Create(inputStream);

If you're not sure of the Sheet's name but you are sure of the index (0 based), you can grab the sheet like this:

ISheet sheet = workbook.GetSheetAt(sheetIndex);

You can then iterate through the rows using code supplied by the accepted answer from mj82

Getting CheckBoxList Item values

//Simple example code:

foreach (var item in YourCheckedListBox.CheckedItems)
{List<string>.Add(item);}

Builder Pattern in Effective Java

To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder

How do you manually execute SQL commands in Ruby On Rails using NuoDB

Reposting the answer from our forum to help others with a similar issue:

@connection = ActiveRecord::Base.connection
result = @connection.exec_query('select tablename from system.tables')
result.each do |row|
puts row
end

How do I build a graphical user interface in C++?

Essentially, an operating system's windowing system exposes some API calls that you can perform to do jobs like create a window, or put a button on the window. Basically, you get a suite of header files and you can call functions in those imported libraries, just like you'd do with stdlib and printf.

Each operating system comes with its own GUI toolkit, suite of header files, and API calls, and their own way of doing things. There are also cross platform toolkits like GTK, Qt, and wxWidgets that help you build programs that work anywhere. They achieve this by having the same API calls on each platform, but a different implementation for those API functions that call down to the native OS API calls.

One thing they'll all have in common, which will be different from a CLI program, is something called an event loop. The basic idea there is somewhat complicated, and difficult to compress, but in essence it means that not a hell of a lot is going in in your main class/main function, except:

  • check the event queue if there's any new events
  • if there is, dispatch those events to appropriate handlers
  • when you're done, yield control back to the operating system (usually with some kind of special "sleep" or "select" or "yield" function call)
  • then the yield function will return when the operating system is done, and you have another go around the loop.

There are plenty of resources about event based programming. If you have any experience with JavaScript, it's the same basic idea, except that you, the scripter have no access or control over the event loop itself, or what events there are, your only job is to write and register handlers.

You should keep in mind that GUI programming is incredibly complicated and difficult, in general. If you have the option, it's actually much easier to just integrate an embedded webserver into your program and have an HTML/web based interface. The one exception that I've encountered is Apple's Cocoa+Xcode +interface builder + tutorials that make it easily the most approachable environment for people new to GUI programming that I've seen.

How do I override nested NPM dependency versions?

For those from 2018 and beyond, using npm version 5 or later: edit your package-lock.json: remove the library from "requires" section and add it under "dependencies".

For example, you want deglob package to use glob package version 3.2.11 instead of its current one. You open package-lock.json and see:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "glob": "7.1.2",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  }
},

Remove "glob": "7.1.2", from "requires", add "dependencies" with proper version:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  },
  "dependencies": {
    "glob": {
      "version": "3.2.11"
    }
  }
},

Now remove your node_modules folder, run npm install and it will add missing parts to the "dependencies" section.

How to get current time in milliseconds in PHP?

Use microtime(true) in PHP 5, or the following modification in PHP 4:

array_sum(explode(' ', microtime()));

A portable way to write that code would be:

function getMicrotime()
{
    if (version_compare(PHP_VERSION, '5.0.0', '<'))
    {
        return array_sum(explode(' ', microtime()));
    }

    return microtime(true);
}

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

How to get Spinner value?

View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();

Polymorphism vs Overriding vs Overloading

Both overriding and overloading are used to achieve polymorphism.

You could have a method in a class that is overridden in one or more subclasses. The method does different things depending on which class was used to instantiate an object.

    abstract class Beverage {
       boolean isAcceptableTemperature();
    }

    class Coffee extends Beverage {
       boolean isAcceptableTemperature() { 
           return temperature > 70;
       }
    }

    class Wine extends Beverage {
       boolean isAcceptableTemperature() { 
           return temperature < 10;
       }
    }

You could also have a method that is overloaded with two or more sets of arguments. The method does different things based on the type(s) of argument(s) passed.

    class Server {
        public void pour (Coffee liquid) {
            new Cup().fillToTopWith(liquid);
        }

        public void pour (Wine liquid) {
            new WineGlass().fillHalfwayWith(liquid);
        }

        public void pour (Lemonade liquid, boolean ice) {
            Glass glass = new Glass();
            if (ice) {
                glass.fillToTopWith(new Ice());
            }
            glass.fillToTopWith(liquid);
        }
    }

How to get logged-in user's name in Access vba?

In a Form, Create a text box, with in text box properties select data tab

Default value =CurrentUser()

Current source "select table field name"

It will display current user log on name in text box / label as well as saves the user name in the table field

Position: absolute and parent height?

If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.

Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

Alternatively, just use float: left/float:right and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden on the parent (or any other clearfix technique) to cause its height to expand to that of its children.

article {
    position: relative;
    overflow: hidden;
}

.one {
    position: relative;
    float: left;
    margin-top: 10px;
    margin-left: 10px;
    background: red;
    width: 30px;
    height: 30px;
}

.two {
    position: relative;
    float: right;
    margin-top: 10px;
    margin-right: 10px;
    background: blue;
    width: 30px;
    height: 30px;
}

How to insert current datetime in postgresql insert query

timestamp (or date or time columns) do NOT have "a format".

Any formatting you see is applied by the SQL client you are using.


To insert the current time use current_timestamp as documented in the manual:

INSERT into "Group" (name,createddate) 
VALUES ('Test', current_timestamp);

To display that value in a different format change the configuration of your SQL client or format the value when SELECTing the data:

select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"

For psql (the default command line client) you can configure the display format through the configuration parameter DateStyle: https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

How can I get the status code from an http error in Axios?

This is a known bug, try to use "axios": "0.13.1"

https://github.com/mzabriskie/axios/issues/378

I had the same problem so I ended up using "axios": "0.12.0". It works fine for me.

Sort a Map<Key, Value> by values

If there's not any value bigger than the size of the map, you could use arrays, this should be the fastest approach:

public List<String> getList(Map<String, Integer> myMap) {
    String[] copyArray = new String[myMap.size()];
    for (Entry<String, Integer> entry : myMap.entrySet()) {
        copyArray[entry.getValue()] = entry.getKey();
    }
    return Arrays.asList(copyArray);
}

SELECT last id, without INSERT

I have different solution:

SELECT AUTO_INCREMENT - 1 as CurrentId FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'tablename'

datetime datatype in java

Depends on the RDBMS or even the JDBC driver.

Most of the times you can use java.sql.Timestamp most of the times along with a prepared statement:

pstmt.setTimestamp( index, new Timestamp( yourJavaUtilDateInstance.getTime() );

jQuery to retrieve and set selected option value of html select element

Try this

$('#your_select_element_id').val('your_value').attr().add('selected');

'this' implicitly has type 'any' because it does not have a type annotation

The error is indeed fixed by inserting this with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:

foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS

It should've been this:

foo.on('error', function(this: Foo, err: any) {

or this:

foo.on('error', function(this: typeof foo, err: any) {

A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this and arrow-functions.

Paging with Oracle

Something like this should work: From Frans Bouma's Blog

SELECT * FROM
(
    SELECT a.*, rownum r__
    FROM
    (
        SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%'
        ORDER BY OrderDate DESC, ShippingDate DESC
    ) a
    WHERE rownum < ((pageNumber * pageSize) + 1 )
)
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)

How to run sql script using SQL Server Management Studio?

Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim

EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName

pdftk compression option

Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook setting for gs. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.

pdftk compress:

no change in size
bookmarks TOC are gone

gs screen:

takes a ridiculously long time and 100% CPU
errors:
    sfopen: gs_parse_file_name failed.                                 ? 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone

gs printer:

takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone

gs ebook:

errors:
    sfopen: gs_parse_file_name failed.
      ./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone

qpdf --linearize:

very fast, a few seconds
no size change
bookmarks TOC are gone

pdf2ps:

took very long time
output_pdf2ps.ps 74.8MB-->331.6MB

ps2pdf:

pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone

How to convert C# nullable int to int

The other answers so far are all correct; I just wanted to add one more that's slightly cleaner:

v2 = v1 ?? default(int);

Any Nullable<T> is implicitly convertible to its T, PROVIDED that the entire expression being evaluated can never result in a null assignment to a ValueType. So, the null-coalescing operator ?? is just syntax sugar for the ternary operator:

v2 = v1 == null ? default(int) : v1;

...which is in turn syntax sugar for an if/else:

if(v1==null)
   v2 = default(int);
else
   v2 = v1;

Also, as of .NET 4.0, Nullable<T> has a "GetValueOrDefault()" method, which is a null-safe getter that basically performs the null-coalescing shown above, so this works too:

v2 = v1.GetValueOrDefault();

What is the difference between docker-compose ports vs expose

I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:

Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.

This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.

How to solve a timeout error in Laravel 5

try

ini_set('max_execution_time', $time);
$articles = Article::all();

where $time is in seconds, set it to 0 for no time. make sure to make it 60 back after your function finish

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.


Just for completeness:

x += y is not always doing an in-place operation, there are (at least) three exceptions:

  • If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int.

  • If __iadd__ returns NotImplemented, Python falls back to x = x + y.

  • The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.

As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.

You can read more on this in the Python documentation of "Emulating Numeric Types".

These [__i*__] methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y. In certain situations, augmented assignment can result in unexpected errors (see Why does a_tuple[i] += ["item"] raise an exception when the addition works?), but this behavior is in fact part of the data model.

Yarn: How to upgrade yarn version using terminal?

I updated yarn on my Ubuntu by running the following command from my terminal

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

source:https://yarnpkg.com/lang/en/docs/cli/self-update

How to get the separate digits of an int number?

Java 8 solution to get digits as int[] from an integer that you have as a String:

int[] digits = intAsString.chars().map(i -> i - '0').toArray();

Group list by values

>>> xs = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> xs.sort(key=lambda x: x[1])
>>> reduce(lambda l, x: (l.append([x]) if l[-1][0][1] != x[1] else l[-1].append(x)) or l, xs[1:], [[xs[0]]]) if xs else []
[[['A', 0], ['C', 0]], [['B', 1]], [['D', 2], ['E', 2]]]

Basically, if the list is sorted, it is possible to reduce by looking at the last group constructed by the previous steps - you can tell if you need to start a new group, or modify an existing group. The ... or l bit is a trick that enables us to use lambda in Python. (append returns None. It is always better to return something more useful than None, but, alas, such is Python.)

CodeIgniter - return only one row?

class receipt_model extends CI_Model {

   public function index(){

      $this->db->select('*');

      $this->db->from('donor_details');

      $this->db->order_by('donor_id','desc');

      $query=$this->db->get();

      $row=$query->row();

      return $row;
 }

}

How to expand 'select' option width after the user wants to select an option

I improved the cychan's solution, to be like that:

<html>
<head>

<style>
    .wrapper{
        display: inline;
        float: left; 
        width: 180px; 
        overflow: hidden; 
    }
    .selectArrow{
        display: inline;
        float: left;
        width: 17px;
        height: 20px;
        border:1px solid #7f9db9;
        border-left: none;
        background: url('selectArrow.png') no-repeat 1px 1px;
    }
    .selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;}
    .selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;}
</style>
<script language="javascript" src="jquery-1.3.2.min.js"></script>

<script language="javascript">
    $(document).ready(function(){
        $('#w1').wrap("<div class='wrapper'></div>");
        $('.wrapper').after("<div class='selectArrow'/>");
        $('.wrapper').find('select').mousedown(function(){
            $(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).parent().next().addClass('selectArrow-mouseover');
        }, function(){
            $(this).parent().next().removeClass('selectArrow-mouseover');
        });

        $('.selectArrow').click(function(){
            $(this).prev().find('select').focus();
        });

        $('.selectArrow').mousedown(function(){
            $(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).addClass('selectArrow-mouseover');
        }, function(){
            $(this).removeClass('selectArrow-mouseover');
        });
    });

</script>
</head>
<body>
    <select id="w1">
       <option value="0">AnyAnyAnyAnyAnyAnyAny</option>
       <option value="1">AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny</option>
    </select>

</body>
</html>

The PNGs used in css classes are uploaded here...

And you still need JQuery.....

.NET unique object identifier

RuntimeHelpers.GetHashCode() may help (MSDN).

How to create EditText with cross(x) button at end of it?

Just put close cross like drawableEnd in your EditText:

<EditText
     ...
    android:drawableEnd="@drawable/ic_close"
    android:drawablePadding="8dp"
     ... />

and use extension to handle click (or use OnTouchListener directly on your EditText):

fun EditText.onDrawableEndClick(action: () -> Unit) {
    setOnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            v as EditText
            val end = if (v.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
                v.left else v.right
            if (event.rawX >= (end - v.compoundPaddingEnd)) {
                action.invoke()
                return@setOnTouchListener true
            }
        }
        return@setOnTouchListener false
    }
}

extension usage:

editText.onDrawableEndClick {
    // TODO clear action
    etSearch.setText("")
}

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

  • <% %> : Executes the ruby code
  • <%= %> : Prints into Erb file. Or browser
  • <% -%> : Avoids line break after expression.
  • <%# %> : ERB comment

CHECK constraint in MySQL is not working

Update to MySQL 8.0.16 to use checks:

As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines. CREATE TABLE permits the following CHECK constraint syntax, for both table constraints and column constraints

MySQL Checks Documentation

How to make an image center (vertically & horizontally) inside a bigger div

This worked for me. Add this to image css:

img
{
   display: block;
   margin: auto;
}

Creating a file only if it doesn't exist in Node.js

You can do something like this:

function writeFile(i){
    var i = i || 0;
    var fileName = 'a_' + i + '.jpg';
    fs.exists(fileName, function (exists) {
        if(exists){
            writeFile(++i);
        } else {
            fs.writeFile(fileName);
        }
    });
}

Search for an item in a Lua list

Sort of solution using metatable...

local function preparetable(t)
 setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end

local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)

if workingtable[456] then
...
end

Difference between size and length methods?

size() is a method specified in java.util.Collection, which is then inherited by every data structure in the standard library. length is a field on any array (arrays are objects, you just don't see the class normally), and length() is a method on java.lang.String, which is just a thin wrapper on a char[] anyway.

Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.

The process cannot access the file because it is being used by another process (File is created but contains nothing)

File.AppendAllText does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText will fail, throwing the exception you see.

I suggest you used str.Write or str.WriteLine instead, as you already do elsewhere in your code.

Your file is created but contains nothing because the exception is thrown before str.Flush() and str.Close() are called.

HSL to RGB color conversion

PHP - shortest but precise

Here I rewrite my JS answer (math details are there) to PHP - you can run it here

function hsl2rgb($h,$s,$l) 
{
  $a = $s * min($l, 1-$l);
  $k = function($n,$h) { return ($n+$h/30)%12;};
  $f = function($n) use ($h,$s,$l,$a,$k) { 
      return $l - $a * max( min($k($n,$h)-3, 9-$k($n,$h), 1),-1);
  };
  return [ $f(0), $f(8), $f(4) ];
}   

converting multiple columns from character to numeric format in r

I think I figured it out. Here's what I did (perhaps not the most elegant solution - suggestions on how to imp[rove this are very much welcome)

#names of columns in data frame
cols <- names(DF)
# character variables
cols.char <- c("fx_code","date")
#numeric variables
cols.num <- cols[!cols %in% cols.char]

DF.char <- DF[cols.char]
DF.num <- as.data.frame(lapply(DF[cols.num],as.numeric))
DF2 <- cbind(DF.char, DF.num)

How to terminate process from Python using pid?

I wanted to do the same thing as, but I wanted to do it in the one file.

So the logic would be:

  • if a script with my name is running, kill it, then exit
  • if a script with my name is not running, do stuff

I modified the answer by Bakuriu and came up with this:

from os import getpid
from sys import argv, exit
import psutil  ## pip install psutil

myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
    if process.pid != mypid:
        for path in process.cmdline():
            if myname in path:
                print "process found"
                process.terminate()
                exit()

## your program starts here...

Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.

How to submit a form using Enter key in react.js?

I've built up on @user1032613's answer and on this answer and created a "on press enter click element with querystring" hook. enjoy!

const { useEffect } = require("react");

const useEnterKeyListener = ({ querySelectorToExecuteClick }) => {
    useEffect(() => {
        //https://stackoverflow.com/a/59147255/828184
        const listener = (event) => {
            if (event.code === "Enter" || event.code === "NumpadEnter") {
                handlePressEnter();
            }
        };

        document.addEventListener("keydown", listener);

        return () => {
            document.removeEventListener("keydown", listener);
        };
    }, []);

    const handlePressEnter = () => {
        //https://stackoverflow.com/a/54316368/828184
        const mouseClickEvents = ["mousedown", "click", "mouseup"];
        function simulateMouseClick(element) {
            mouseClickEvents.forEach((mouseEventType) =>
                element.dispatchEvent(
                    new MouseEvent(mouseEventType, {
                        view: window,
                        bubbles: true,
                        cancelable: true,
                        buttons: 1,
                    })
                )
            );
        }

        var element = document.querySelector(querySelectorToExecuteClick);
        simulateMouseClick(element);
    };
};

export default useEnterKeyListener;

This is how you use it:

useEnterKeyListener({
    querySelectorToExecuteClick: "#submitButton",
});

https://codesandbox.io/s/useenterkeylistener-fxyvl?file=/src/App.js:399-407

Bootstrap 3 Horizontal Divider (not in a dropdown)

Currently it only works for the .dropdown-menu:

.dropdown-menu .divider {
  height: 1px;
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

If you want it for other use, in your own css, following the bootstrap.css create another one:

.divider {
  height: 1px;
  width:100%;
  display:block; /* for use on default inline elements like span */
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

Quick answer : Add proxy configuration with parameter for both install/update

gem install --http-proxy http://host:port/ package_name

gem update --http-proxy http://host:port/ package_name

How to "add existing frameworks" in Xcode 4?

The frameworks directory is as follow in my computer: /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/Frameworks

not the directory

/Developer/SDKs/MacOSXversion.sdk/System/Library/Frameworks

Slide up/down effect with ng-show and ng-animate

update for Angular 1.2+ (v1.2.6 at the time of this post):

.stuff-to-show {
  position: relative;
  height: 100px;
  -webkit-transition: top linear 1.5s;
  transition: top linear 1.5s;
  top: 0;
}
.stuff-to-show.ng-hide {
  top: -100px;
}
.stuff-to-show.ng-hide-add,
.stuff-to-show.ng-hide-remove {
  display: block!important;
}

(plunker)

Converting dd/mm/yyyy formatted string to Datetime

You need to use DateTime.ParseExact with format "dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.


Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.


Another method for parsing is using DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013", 
                            "d/M/yyyy", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //valid date
}
else
{
    //invalid date
}

The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.

Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"

For further reading you should see: Custom Date and Time Format Strings

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }

document.getElementById(id).focus() is not working for firefox or chrome

Try location.href='#yourId'

Like this:

<button onclick="javascript:location.href='#yourId'">Show</button>

Using generic std::function objects with member functions in one class

Unfortunately, C++ does not allow you to directly get a callable object referring to an object and one of its member functions. &Foo::doSomething gives you a "pointer to member function" which refers to the member function but not the associated object.

There are two ways around this, one is to use std::bind to bind the "pointer to member function" to the this pointer. The other is to use a lambda that captures the this pointer and calls the member function.

std::function<void(void)> f = std::bind(&Foo::doSomething, this);
std::function<void(void)> g = [this](){doSomething();};

I would prefer the latter.

With g++ at least binding a member function to this will result in an object three-pointers in size, assigning this to an std::function will result in dynamic memory allocation.

On the other hand, a lambda that captures this is only one pointer in size, assigning it to an std::function will not result in dynamic memory allocation with g++.

While I have not verified this with other compilers, I suspect similar results will be found there.

How to overcome "'aclocal-1.15' is missing on your system" warning?

You can install the version you need easily:

First get source:

$ wget https://ftp.gnu.org/gnu/automake/automake-1.15.tar.gz

Unpack it:

$ tar -xzvf automake-1.15.tar.gz

Build and install:

$ cd automake-1.15
$ ./configure  --prefix=/opt/aclocal-1.15
$ make
$ sudo mkdir -p /opt
$ sudo make install

Use it:

$ export PATH=/opt/aclocal-1.15/bin:$PATH
$ aclocal --version

aclocal (GNU automake) 1.15

Now when aclocal is called, you get the right version.

jQuery $.cookie is not a function

Solve jQuery $.cookie is not a function this Problem jquery cdn update in solve this problem

 <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

Visual Studio opens the default browser instead of Internet Explorer

Another way is to do the following in Visual Studio:

  1. Select Debug
  2. Options and Settings
  3. Expand Environment
  4. Select Web Browser
  5. Click the 'Internet Explorer Options' button
  6. Select the 'Programs' tab
  7. Select 'Make Default' button for Internet Explorer

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

In my case, it was the password that contained some characters like ', after changing it the server started without problems.

How to parse XML using shellscript?

There's also xmlstarlet (which is available for Windows as well).

http://xmlstar.sourceforge.net/doc/xmlstarlet.txt

converting numbers in to words C#

public static string NumberToWords(int number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];
            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

Import SQL file into mysql

Ok so, I'm using Linux but I think this holds true for Windows too. You can do this either directly from the command prompt

> mysql -u <user name> -p<password> <database name> < sqlfilename.sql

Or from within the mysql prompt, you can use:

mysql>source sqlfilename.sql

But both these approaches have their own benefits in the results they display. In the first approach, the script exits as soon as it encounters an error. And the better part, is that it tells you the exact line number in the source file where the error occurred. However, it ONLY displays errors. If it didn't encounter any errors, the scripts displays NOTHING. Which can be a little unnerving. Because you're most often running a script with a whole pile of commands.

Now second approach (from within the mysql prompt) has the benefit that it displays a message for every different MySQL command in the script. If it encounters errors, it displays the mysql error message but continues on through the scripts. This can be good, because you can then go back and fix all the errors before you run the script again. The downside is that it does NOT display the line numbers in the script where the errors were encountered. This can be a bit of a pain. But the error messages are as descriptive so you could probably figure out where the problem is.

I, for one, prefer the directly-from-OS-command line approach.

What are Covering Indexes and Covered Queries in SQL Server?

If all the columns requested in the select list of query, are available in the index, then the query engine doesn't have to lookup the table again which can significantly increase the performance of the query. Since all the requested columns are available with in the index, the index is covering the query. So, the query is called a covering query and the index is a covering index.

A clustered index can always cover a query, if the columns in the select list are from the same table.

The following links can be helpful, if you are new to index concepts:

Can media queries resize based on a div element instead of the screen?

I was also thinking of media queries, but then I found this:

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

_x000D_
_x000D_
div {_x000D_
  width: 100%;_x000D_
  padding-bottom: 75%;_x000D_
  background:gold; /** <-- For the demo **/_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).

This technique can also be coupled with media queries and a bit of ad hoc knowledge about page layout for even more finer-grained control.

It's enough for my needs. Which might be enough for your needs too.

How to draw polygons on an HTML5 canvas?

In addition to @canvastag, use a while loop with shift I think is more concise:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var poly = [5, 5, 100, 50, 50, 100, 10, 90];

// copy array
var shape = poly.slice(0);

ctx.fillStyle = '#f00'
ctx.beginPath();
ctx.moveTo(shape.shift(), shape.shift());
while(shape.length) {
  ctx.lineTo(shape.shift(), shape.shift());
}
ctx.closePath();
ctx.fill();

pandas: How do I split text in a column into multiple rows?

This seems a far easier method than those suggested elsewhere in this thread.

split rows in pandas dataframe

phpMyAdmin - Error > Incorrect format parameter?

If you use docker-compose just set UPLOAD_LIMIT

phpmyadmin:
    image: phpmyadmin/phpmyadmin
    environment:
        UPLOAD_LIMIT: 1G

How to commit a change with both "message" and "description" from the command line?

In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.

git rebase -i origin/master

Then, your commits will appear:

pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments

Select the commit you want to reword and save.

pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments

Now, you have the opportunity to add header and body, where the first line will be the header.

Create perpetuum mobile

Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.

How to tar certain file types in all subdirectories?

tar -cf my_archive `find ./ | grep '.php\|.html'`

Use "find" and "grep" to get all path of .php and .html files in all directory and its sub-directories. Then pass those path information to tar to compress.

Please be careful with those symbol ` and '. Note also that this will hit the limit of how many characters your shell will allow on the command line, unlike some of the other answers.

Is there a way to access an iteration-counter in Java's for-each loop?

There is a "variant" to pax' answer... ;-)

int i = -1;
for(String s : stringArray) {
    doSomethingWith(s, ++i);
}

Struct Constructor in C++?

In C++ both struct & class are equal except struct'sdefault member access specifier is public & class has private.

The reason for having struct in C++ is C++ is a superset of C and must have backward compatible with legacy C types.

For example if the language user tries to include some C header file legacy-c.h in his C++ code & it contains struct Test {int x,y};. Members of struct Test should be accessible as like C.

how to update spyder on anaconda

Use this conda install spyder=4.0.0 This will not mess up your anaconda dependencies. https://github.com/spyder-ide/spyder/releases

What does the [Flags] Enum Attribute mean in C#?

Please see the following for an example which shows the declaration and potential usage:

namespace Flags
{
    class Program
    {
        [Flags]
        public enum MyFlags : short
        {
            Foo = 0x1,
            Bar = 0x2,
            Baz = 0x4
        }

        static void Main(string[] args)
        {
            MyFlags fooBar = MyFlags.Foo | MyFlags.Bar;

            if ((fooBar & MyFlags.Foo) == MyFlags.Foo)
            {
                Console.WriteLine("Item has Foo flag set");
            }
        }
    }
}

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

$a, $b, $c, $d can be dynamic values by the query

 ->where(function($query) use ($a, $b)
        {
            $query->where('a', $a)
                  ->orWhere('b',$b);
        })
 ->where(function($query) use ($c, $d)
        {
            $query->where('c', $c)
                  ->orWhere('d',$d);
        })

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

How do I stretch a background image to cover the entire HTML element?

It works for me

.page-bg {
  background: url("res://background");
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

Convert binary to ASCII and vice versa

Are you looking for the code to do it or understanding the algorithm?

Does this do what you need? Specifically a2b_uu and b2a_uu? There are LOTS of other options in there in case those aren't what you want.

(NOTE: Not a Python guy but this seemed like an obvious answer)

"inappropriate ioctl for device"

Eureka moment!

I have had this error before.

Did you invoke the perl debugger with something like :-

perl -d yourprog.pl > log.txt

If so whats going on is perl debug tries to query and perhaps reset the terminal width. When stdout is not a terminal this fails with the IOCTL message.

The alternative would be for your debug session to hang forever because you did not see the prompt for instructions.

Android/Java - Date Difference in days

This fragment accounts for daylight savings time and is O(1).

private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;

private static long getDateToLong(Date date) {
    return Date.UTC(date.getYear(), date.getMonth(), date.getDate(), 0, 0, 0);
}

public static int getSignedDiffInDays(Date beginDate, Date endDate) {
    long beginMS = getDateToLong(beginDate);
    long endMS = getDateToLong(endDate);
    long diff = (endMS - beginMS) / (MILLISECS_PER_DAY);
    return (int)diff;
}

public static int getUnsignedDiffInDays(Date beginDate, Date endDate) {
    return Math.abs(getSignedDiffInDays(beginDate, endDate));
}

How to display the string html contents into webbrowser control?

As commented by Thomas W. - I almost missed this comment but I had the same issues so it's worth rewriting as an answer I think.

The main issue being that after the first assignment of webBrowser1.DocumentText to some html, subsequent assignments had no effect.

The solution as linked by Thomas can be found in detail at http://weblogs.asp.net/gunnarpeipman/archive/2009/08/15/displaying-custom-html-in-webbrowser-control.aspx however I will summarize below in case this page becomes unavailable in the future.

In short, due to the way the webBrowser control works, you must navigate to a new page each time you wish to change the content. Therefore the author proposes a method to update the control as:

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("about:blank");
    if (webBrowser1.Document != null)
    {
        webBrowser1.Document.Write(string.Empty);
    }
    webBrowser1.DocumentText = html;
}

I have however found that in my current application I get a CastException from the line if(webBrowser1.Document != null). I'm not sure why this is, but I've found that if I wrap the whole if block in a try catch the desired effect still works. See:

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("about:blank");
    try
    {
        if (webBrowser1.Document != null)
        {
            webBrowser1.Document.Write(string.Empty);
        }
    }
    catch (CastException e)
    { } // do nothing with this
    webBrowser1.DocumentText = html;
}

So every time the function to DisplayHtml is executed I receive a CastException from the if statement, so the contents of the if statement are never reached. However if I comment out the if statement so as not to receive the CastException, then the browser control doesn't get updated. I suspect there is another side effect of the code behind the Document property which causes this effect despite the fact that it also throws an exception.

Anyway I hope this helps people.

What is the best way to remove accents (normalize) in a Python unicode string?

gensim.utils.deaccent(text) from Gensim - topic modelling for humans:

'Sef chomutovskych komunistu dostal postou bily prasek'

Another solution is unidecode.

Note that the suggested solution with unicodedata typically removes accents only in some character (e.g. it turns 'l' into '', rather than into 'l').

MySQL: What's the difference between float and double?

Float has 32 bit (4 bytes) with 8 places accuracy. Double has 64 bit (8 bytes) with 16 places accuracy.

If you need better accuracy, use Double instead of Float.

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

cast or convert a float to nvarchar?

You can also do something:

SELECT CAST(CAST(34512367.392 AS decimal(30,9)) AS NVARCHAR(100))

Output: 34512367.392000000

How to break lines in PowerShell?

You can also just use:

Write-Host "";

Or, to put it in terms of your specific question:

$str = ""
foreach($line in $file){
  if($line -Match $review){ #Special condition
    $str += Write-Host ""
    $str += ANSWER #looking for ANSWER
  }
  #code.....
}

Programmatically go back to the previous fragment in the backstack

By adding fragment_tran.addToBackStack(null) on last fragment, I am able to do come back on last fragment.

adding new fragment:

view.findViewById(R.id.changepass).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, new ChangePassword());
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

Is there a command to list all Unix group names?

On Linux, macOS and Unix to display the groups to which you belong, use:

id -Gn

which is equivalent to groups utility which has been obsoleted on Unix (as per Unix manual).

On macOS and Unix, the command id -p is suggested for normal interactive.

Explanation of the parameters:

-G, --groups - print all group IDs

-n, --name - print a name instead of a number, for -ugG

-p - Make the output human-readable.

Why does ASP.NET webforms need the Runat="Server" attribute?

I've always believed it was there more for the understanding that you can mix ASP.NET tags and HTML Tags, and HTML Tags have the option of either being runat="server" or not. It doesn't hurt anything to leave the tag in, and it causes a compiler error to take it out. The more things you imply about web language, the less easy it is for a budding programmer to come in and learn it. That's as good a reason as any to be verbose about tag attributes.

This conversation was had on Mike Schinkel's Blog between himself and Talbot Crowell of Microsoft National Services. The relevant information is below (first paragraph paraphrased due to grammatical errors in source):

[...] but the importance of <runat="server"> is more for consistency and extensibility.

If the developer has to mark some tags (viz. <asp: />) for the ASP.NET Engine to ignore, then there's also the potential issue of namespace collisions among tags and future enhancements. By requiring the <runat="server"> attribute, this is negated.

It continues:

If <runat=client> was required for all client-side tags, the parser would need to parse all tags and strip out the <runat=client> part.

He continues:

Currently, If my guess is correct, the parser simply ignores all text (tags or no tags) unless it is a tag with the runat=server attribute or a “<%” prefix or ssi “<!– #include(...) Also, since ASP.NET is designed to allow separation of the web designers (foo.aspx) from the web developers (foo.aspx.vb), the web designers can use their own web designer tools to place HTML and client-side JavaScript without having to know about ASP.NET specific tags or attributes.

Delete a single record from Entity Framework?

With Entity Framework 6, you can use Remove. Also it 's a good tactic to use using for being sure that your connection is closed.

using (var context = new EmployDbContext())
{
    Employ emp = context.Employ.Where(x => x.Id == id).Single<Employ>();
    context.Employ.Remove(emp);
    context.SaveChanges();
}

How to use OAuth2RestTemplate?

My simple solution. IMHO it's the cleanest.

First create a application.yml

spring.main.allow-bean-definition-overriding: true

security:
  oauth2:
    client:
      clientId: XXX
      clientSecret: XXX
      accessTokenUri: XXX
      tokenName: access_token
      grant-type: client_credentials

Create the main class: Main

@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll();
    }

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Bean
    public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
        return new OAuth2RestTemplate(details);
    }

}

Then Create the controller class: Controller

@RestController
class OfferController {

    @Autowired
    private OAuth2RestOperations restOperations;

    @RequestMapping(value = "/<your url>"
            , method = RequestMethod.GET
            , produces = "application/json")
    public String foo() {
        ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
        return responseEntity.getBody();
    }
}

Maven dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.1.5.RELEASE</version>
    </dependency>
</dependencies>

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

I got this since I had a comment in a file I was adding to my JS, really awkward reason to what was going on - though when clicking on the VM file that's pre-rendered and catches the error, you'll find out what exactly the error was, in my case it was simply uncommenting some code I was using.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

I think this represents a good answer.

APK Signature Scheme v2 verification

  1. Locate the APK Signing Block and verify that:
    1. Two size fields of APK Signing Block contain the same value.
    2. ZIP Central Directory is immediately followed by ZIP End of Central Directory record.
    3. ZIP End of Central Directory is not followed by more data.
  2. Locate the first APK Signature Scheme v2 Block inside the APK Signing Block. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.
  3. For each signer in the APK Signature Scheme v2 Block:
    1. Choose the strongest supported signature algorithm ID from signatures. The strength ordering is up to each implementation/platform version.
    2. Verify the corresponding signature from signatures against signed data using public key. (It is now safe to parse signed data.)
    3. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
    4. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
    5. Verify that the computed digest is identical to the corresponding digest from digests.
    6. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
  4. Verification succeeds if at least one signer was found and step 3 succeeded for each found signer.

Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.

JAR-signed APK verification (v1 scheme)

The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF and where all entries must be signed by the same set of signers. Its integrity is verified as follows:

  1. Each signer is represented by a META-INF/<signer>.SF and META-INF/<signer>.(RSA|DSA|EC) JAR entry.
  2. <signer>.(RSA|DSA|EC) is a PKCS #7 CMS ContentInfo with SignedData structure whose signature is verified over the <signer>.SF file.
  3. <signer>.SF file contains a whole-file digest of the META-INF/MANIFEST.MF and digests of each section of META-INF/MANIFEST.MF. The whole-file digest of the MANIFEST.MF is verified. If that fails, the digest of each MANIFEST.MF section is verified instead.
  4. META-INF/MANIFEST.MF contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.
  5. APK verification fails if the APK contains JAR entries which are not listed in the MANIFEST.MF and are not part of JAR signature. The protection chain is thus <signer>.(RSA|DSA|EC) ? <signer>.SF ? MANIFEST.MF ? contents of each integrity-protected JAR entry.

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

Convert a negative number to a positive one in JavaScript

If you want the number to always be positive no matter what you can do this.

function toPositive(n){
    if(n < 0){
        n = n * -1;
    }
    return n;
}
var a = toPositive(2);  // 2
var b = toPositive(-2); // 2

You could also try this, but i don't recommended it:

function makePositive(n){
    return Number((n*-n).toString().replace('-','')); 
}
var a = makePositive(2);  // 2
var b = makePositive(-2); // 2

The problem with this is that you could be changing the number to negative, then converting to string and removing the - from the string, then converting back to int. Which I would guess would take more processing then just using the other function.

I have tested this in php and the first function is faster, but sometimes JS does some crazy things, so I can't say for sure.

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

Swift 4 code: For tableview with no section headers you can add this code:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return CGFloat.leastNormalMagnitude
}

and you will get the header spacing to 0.

If you want a header of your specific height pass that value:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return header_height
}

and the view from viewForHeaderinSection delegate.

Android studio doesn't list my phone under "Choose Device"

Though the answer is accepted, but I'm going to answer it anyway.

From the points perspective, it might seem that it's a lot of work. But it's very simple. And Up un till now it has worked on all the devices I have tried with.

At first download the universal ADB driver. Then follow the process below:

  1. Install the Universal ADB driver.
  2. Then go to the control panel.
  3. Select Device and Printers.
  4. Then find your device and right click on it.
  5. Probably you will see a yellow exclamation mark. Which means the device doesn't have the correct driver installed.
  6. Next, select the properties of the device. Then-

    • Select hardware tab, and again select properties.
    • Then under general tab select Change Settings.
    • Then under the Driver tab, select update driver.
    • Then select Browse my computer for driver software.
    • Then select Let me pick from a list of device drivers on my computer.
    • Here you will see the list of devices. Select Android devices. Which will show you all the available drivers.
    • Under the model section, you can see a lot of drivers available.
    • You can select your preferred one.
    • Most of the cases the generic ANDROID ADB INTERFACE will do the trick.
    • When you try to install it, it might give you a warning but go ahead and install the driver.
    • And it's done.

Then re-run your app from the android studio. And it will show your device under Choose Device. Cheers!

Redis command to get all available keys?

It can happen that using redis-cli, you connect to your remote redis-server, and then the command:

KEYS *

is not showing anything, or better, it shows:
(empty list or set)

If you are absolutely sure that the Redis server you use is the one you have the data, then maybe your redis-cli is not connecting to the Redis correct database instance.

As it is mentioned in the Redis docs, new connections connect as default to the db 0.

In my case KEYS command was not retrieving results because my database was 1. In order to select the db you want, use SELECT.
The db is identified by an integer.

SELECT 1
KEYS *

I post this info because none of the previous answers was solving my issue.

Save bitmap to location

Some formats, like PNG which is lossless, will ignore the quality setting.

Align div with fixed position on the right side

You can simply do this:

.test {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  right: 0;
}

JQuery - $ is not defined

That error means that jQuery has not yet loaded on the page. Using $(document).ready(...) or any variant thereof will do no good, as $ is the jQuery function.

Using window.onload should work here. Note that only one function can be assigned to window.onload. To avoid losing the original onload logic, you can decorate the original function like so:

originalOnload = window.onload;
window.onload = function() {
  if (originalOnload) {
    originalOnload();
  }
  // YOUR JQUERY
};

This will execute the function that was originally assigned to window.onload, and then will execute // YOUR JQUERY.

See https://en.wikipedia.org/wiki/Decorator_pattern for more detail about the decorator pattern.

How to query as GROUP BY in django?

You need to do custom SQL as exemplified in this snippet:

Custom SQL via subquery

Or in a custom manager as shown in the online Django docs:

Adding extra Manager methods

round() doesn't seem to be rounding properly

I am doing:

int(round( x , 0))

In this case, we first round properly at the unit level, then we convert to integer to avoid printing a float.

so

>>> int(round(5.59,0))
6

I think this answer works better than formating the string, and it also makes more sens to me to use the round function.

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

You can remove "JavaAppletPlugin.plugin" found in Spotlight or Finder, then re-install downloaded Java 8.

This will simply solve your problem.

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

It's an invisible folder. Just hit Command + Shift + G (takes you to the Go to Folder menu item) and type /etc/.

Then it will take you to inside that folder.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

This is related to compact option of Babel compiler, which commands to "not include superfluous whitespace characters and line terminators. When set to 'auto' compact is set to true on input sizes of >100KB." By default its value is "auto", so that is probably the reason you are getting the warning message. See Babel documentation.

You can change this option from Webpack using a query parameter. For example:

loaders: [
    { test: /\.js$/, loader: 'babel', query: {compact: false} }
]

Get paragraph text inside an element

Do you use jQuery? A good option would be

text = $('p').text();

What are the different types of indexes, what are the benefits of each?

Different database systems have different names for the same type of index, so be careful with this. For example, what SQL Server and Sybase call "clustered index" is called in Oracle an "index-organised table".

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Invoke JSF managed bean action on page load

calling bean action from a will be a good idea,keep attribute autoRun="true" example below

<p:remoteCommand autoRun="true" name="myRemoteCommand" action="#{bean.action}" partialSubmit="true" update=":form" />

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

Special characters like @ and & in cURL POST data

Just found another solutions worked for me. You can use '\' sign before your one special.

passwd=\@31\&3*J

Typescript ReferenceError: exports is not defined

EDIT:

This answer might not work depending if you're not targeting es5 anymore, I'll try to make the answer more complete.

Original Answer

If CommonJS isn't installed (which defines exports), you have to remove this line from your tsconfig.json:

 "module": "commonjs",

As per the comments, this alone may not work with later versions of tsc. If that is the case, you can install a module loader like CommonJS, SystemJS or RequireJS and then specify that.

Note:

Look at your main.js file that tsc generated. You will find this at the very top:

Object.defineProperty(exports, "__esModule", { value: true });

It is the root of the error message, and after removing "module": "commonjs",, it will vanish.

Update Git submodule to latest commit on origin

The git submodule update command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. If you want to update your submodules to the latest commit available from their remote, you will need to do this directly in the submodules.

So in summary:

# Get the submodule initially
git submodule add ssh://bla submodule_dir
git submodule init

# Time passes, submodule upstream is updated
# and you now want to update

# Change to the submodule directory
cd submodule_dir

# Checkout desired branch
git checkout master

# Update
git pull

# Get back to your project root
cd ..

# Now the submodules are in the state you want, so
git commit -am "Pulled down update to submodule_dir"

Or, if you're a busy person:

git submodule foreach git pull origin master

How do I bind to list of checkbox values with AngularJS?

Here is yet another solution. The upside of my solution:

  • It does not need any additional watches (which may have an impact on performance)
  • It does not require any code in the controller keeping it clean
  • The code is still somewhat short
  • It is requires very little code to reuse in multiple places because it is just a directive

Here is the directive:

function ensureArray(o) {
    var lAngular = angular;
    if (lAngular.isArray(o) || o === null || lAngular.isUndefined(o)) {
        return o;
    }
    return [o];
}

function checkboxArraySetDirective() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            var name = attrs.checkboxArraySet;

            ngModel.$formatters.push(function(value) {
                return (ensureArray(value) || []).indexOf(name) >= 0;
            });

            ngModel.$parsers.push(function(value) {
                var modelValue = ensureArray(ngModel.$modelValue) || [],
                    oldPos = modelValue.indexOf(name),
                    wasSet = oldPos >= 0;
                if (value) {
                    if (!wasSet) {
                        modelValue = angular.copy(modelValue);
                        modelValue.push(name);
                    }
                } else if (wasSet) {
                    modelValue = angular.copy(modelValue);
                    modelValue.splice(oldPos, 1);
                }
                return modelValue;
            });
        }
    }
}

At the end then just use it like this:

<input ng-repeat="fruit in ['apple', 'banana', '...']" type="checkbox" ng-model="fruits" checkbox-array-set="{{fruit}}" />

And that is all there is. The only addition is the checkbox-array-set attribute.

How to make inline functions in C#

Not only Inside methods, it can be used inside classes also.

class Calculator
    {
        public static int Sum(int x,int y) => x + y;
        public static Func<int, int, int>  Add = (x, y) => x + y;
        public static Action<int,int> DisplaySum = (x, y) => Console.WriteLine(x + y);
    }

How to do case insensitive search in Vim

You can issue the command

:set ignorecase

and after that your searches will be case-insensitive.

check if file exists in php

for me also the file_exists() function is not working properly. So I got this alternative solution. Hope this one help someone

$path = 'http://localhost/admin/public/upload/video_thumbnail/thumbnail_1564385519_0.png';

    if (@GetImageSize($path)) {
        echo 'File exits';
    } else {
        echo "File doesn't exits";
    }

Python timedelta in years

How exact do you need it to be? td.days / 365.25 will get you pretty close, if you're worried about leap years.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

gradle.properties:

theGroup=some.group
theName=someName
theVersion=1.0
theSourceCompatibility=1.6

settings.gradle:

rootProject.name = theName

build.gradle:

apply plugin: "java"

group = theGroup
version = theVersion
sourceCompatibility = theSourceCompatibility

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

If conditions in a Makefile, inside a target

You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:

clean:
    @if [ "test" = "test" ]; then\
        echo "Hello world";\
    fi

Note that the closing ";" and "\" are necessary.

cancelling a handler.postdelayed process

Here is a class providing a cancel method for a delayed action

public class DelayedAction {

private Handler _handler;
private Runnable _runnable;

/**
 * Constructor
 * @param runnable The runnable
 * @param delay The delay (in milli sec) to wait before running the runnable
 */
public DelayedAction(Runnable runnable, long delay) {
    _handler = new Handler(Looper.getMainLooper());
    _runnable = runnable;
    _handler.postDelayed(_runnable, delay);
}

/**
 * Cancel a runnable
 */
public void cancel() {
    if ( _handler == null || _runnable == null ) {
        return;
    }
    _handler.removeCallbacks(_runnable);
}}

How do I shrink my SQL Server Database?

I came across this post even though I needed to SHRINKFILE on MSSQL 2012 version which is little trickier since 2000 or 2005 versions. After reading up on all risks and issues related to this issue I ended up testing. Long story short, the best results I got were from using the MS SQL Server Management Studio.

Right-Click the DB -> TASKS -> SHRINK -> FILES -> select the LOG file

See :hover state in Chrome Developer Tools

In case it helps, this seems to be easier in the latest Chrome (47.0.2526.106):

Inspect element and then click on the three white dots in the left gutter:
click on the three white dots

Then choose the desired element state from this dropdown:
this dropdown

Failed to load resource under Chrome

I recently ran into this problem and discovered that it was caused by the "Adblock" extension (my best guess is that it's because I had the words "banner" and "ad" in the filename).

As a quick test to see if that's your problem, start Chrome in incognito mode with extensions disabled (ctrl+shift+n) and see if your page works now. Note that by default all extensions will be already disabled in incognito mode unless you've specifically set them to run (via chrome://extensions).

Angular File Upload

I am using Angular 5.2.11, I like the solution provided by Gregor Doroschenko, however I noticed that the uploaded file is of zero bytes, I had to make a small change to get it to work for me.

postFile(fileToUpload: File): Observable<boolean> {
  const endpoint = 'your-destination-url';
  return this.httpClient
    .post(endpoint, fileToUpload, { headers: yourHeadersConfig })
    .map(() => { return true; })
    .catch((e) => this.handleError(e));
}

The following lines (formData) didn't work for me.

const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);

https://github.com/amitrke/ngrke/blob/master/src/app/services/fileupload.service.ts

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="mycheck" type="checkbox">
    </body>

    <script language="javascript">
        var=check;
        document.getElementById("mycheck");
        check.checked="false";
    </script>
</html>

What is a daemon thread in Java?

A few more points (Reference: Java Concurrency in Practice)

  • When a new thread is created it inherits the daemon status of its parent.
  • When all non-daemon threads finish, the JVM halts, and any remaining daemon threads are abandoned:

    • finally blocks are not executed,
    • stacks are not unwound - the JVM just exits.

    Due to this reason daemon threads should be used sparingly, and it is dangerous to use them for tasks that might perform any sort of I/O.

How do I order my SQLITE database in descending order, for an android app?

you can do it with this

Cursor cursor = database.query(
            TABLE_NAME,
            YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");

Use JavaScript to place cursor at end of text in text input element

Simple. When editing or changing values, first put the focus then set value.

$("#catg_name").focus();
$("#catg_name").val(catg_name);

How do I minimize the command prompt from my bat file

Using PowerShell you can minimize from the same file without opening a new instance.

powershell -window minimized -command ""

Also -window hidden and -window normal is available to hide completely or restore.


source: https://stackoverflow.com/a/45061676/1178975

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

gdb: how to print the current line or find the current line number?

Command where or frame can be used. where command will give more info with the function name

__proto__ VS. prototype in JavaScript

my understanding is: __proto__ and prototype are all served for the prototype chain technique . the difference is functions named with underscore(like __proto__) are not aim for developers invoked explicitly at all. in other words, they are just for some mechanisms like inherit etc. they are 'back-end'. but functions named without underscore are designed for invoked explicitly, they are 'front-end'.

How can I increase the size of a bootstrap button?

Default Bootstrap size classes

You can use btn-lg, btn-sm and btn-xs classes for manipulating with its size.

btn-block

Also, there is a class btn-block which will extend your button to the whole block. It is very convenient in combination with Bootstrap grid.
For example, this code will show a button with the width equal to half of screen for medium and large screens; and will show a full-width button for small screens:

<div class="container">
    <div class="col-xs-12 col-xs-offset-0 col-sm-offset-3 col-sm-6">
        <button class="btn btn-group">Click me!</button>
    </div>
</div>

Check this JSFiddle out. Try to resize frame.

If it is not enough, you can easily create your custom class.

Using wget to recursively fetch a directory with arbitrary files in it

The following option seems to be the perfect combination when dealing with recursive download:

wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2

Relevant snippets from man pages for convenience:

   -nd
   --no-directories
       Do not create a hierarchy of directories when retrieving recursively.  With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
       filenames will get extensions .n).


   -np
   --no-parent
       Do not ever ascend to the parent directory when retrieving recursively.  This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.

Webview load html from assets directory

Download source code from here (Open html file from assets android)

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:background="#FFFFFF"
 android:layout_height="match_parent">

<WebView
 android:layout_width="match_parent"
 android:id="@+id/webview"
 android:layout_height="match_parent"
 android:layout_margin="10dp"></WebView>
</RelativeLayout>

MainActivity.java

package com.deepshikha.htmlfromassets;
 import android.app.ProgressDialog;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

WebView webview;
 ProgressDialog progressDialog;

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

private void init(){
 webview = (WebView)findViewById(R.id.webview);
 webview.loadUrl("file:///android_asset/download.html");
 webview.requestFocus();

progressDialog = new ProgressDialog(MainActivity.this);
 progressDialog.setMessage("Loading");
 progressDialog.setCancelable(false);
 progressDialog.show();

webview.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {
 try {
 progressDialog.dismiss();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }
 }

How to list running screen sessions?

Multiple folks have already pointed that

$ screen -ls

would list the screen sessions.

Here is another trick that may be useful to you.

If you add the following command as a last line in your .bashrc file on server xxx, then it will automatically reconnect to your screen session on login.

screen -d -r

Hope you find it useful.

How can I convert a .py to .exe for Python?

I've been using Nuitka and PyInstaller with my package, PySimpleGUI.

Nuitka There were issues getting tkinter to compile with Nuikta. One of the project contributors developed a script that fixed the problem.

If you're not using tkinter it may "just work" for you. If you are using tkinter say so and I'll try to get the script and instructions published.

PyInstaller I'm running 3.6 and PyInstaller is working great! The command I use to create my exe file is:

pyinstaller -wF myfile.py

The -wF will create a single EXE file. Because all of my programs have a GUI and I do not want to command window to show, the -w option will hide the command window.

This is as close to getting what looks like a Winforms program to run that was written in Python.

[Update 20-Jul-2019]

There is PySimpleGUI GUI based solution that uses PyInstaller. It uses PySimpleGUI. It's called pysimplegui-exemaker and can be pip installed.

pip install PySimpleGUI-exemaker

To run it after installing:

python -m pysimplegui-exemaker.pysimplegui-exemaker

Background position, margin-top?

#div-name

{

  background-image: url('../images/background-art-main.jpg');
  background-position: top right 50px;
  background-repeat: no-repeat;
}

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

Get Number of Rows returned by ResultSet in Java

A simple getRowCount method can look like this :

private int getRowCount(ResultSet resultSet) {
    if (resultSet == null) {
        return 0;
    }

    try {
        resultSet.last();
        return resultSet.getRow();
    } catch (SQLException exp) {
        exp.printStackTrace();
    } finally {
        try {
            resultSet.beforeFirst();
        } catch (SQLException exp) {
            exp.printStackTrace();
        }
    }

    return 0;
}

Just to be aware that this method will need a scroll sensitive resultSet, so while creating the connection you have to specify the scroll option. Default is FORWARD and using this method will throw you exception.

How to end a session in ExpressJS

use,

delete req.session.yoursessionname;

What is stability in sorting algorithms and why is it important?

A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input unsorted array. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.

However, any given sorting algo which is not stable can be modified to be stable. There can be sorting algo specific ways to make it stable, but in general, any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison operation so that the comparison of two keys considers position as a factor for objects with equal keys.

References: http://www.math.uic.edu/~leon/cs-mcs401-s08/handouts/stability.pdf http://en.wikipedia.org/wiki/Sorting_algorithm#Stability

FIFO based Queue implementations?

Here is example code for usage of java's built-in FIFO queue:

public static void main(String[] args) {
    Queue<Integer> myQ = new LinkedList<Integer>();
    myQ.add(1);
    myQ.add(6);
    myQ.add(3);
    System.out.println(myQ);   // 1 6 3
    int first = myQ.poll();    // retrieve and remove the first element
    System.out.println(first); // 1
    System.out.println(myQ);   // 6 3
}

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

You only have tried comma-separated and semicolon-separated CSV. If you had tried tab-separated CSV (also called TSV) you would have found the answer:

UTF-16LE with BOM (byte order mark), tab-separated


But: In a comment you mention that TSV is not an option for you (I haven't been able to find this requirement in your question though). That's a pity. It often means that you allow manual editing of TSV files, which probably is not a good idea. Visual checking of TSV files is not a problem. Furthermore editors can be set to display a special character to mark tabs.

And yes, I tried this out on Windows and Mac.

Load a HTML page within another HTML page

The thing you are asking is not popup but lightbox. For this, the trick is to display a semitransparent layer behind (called overlay) and that required div above it.

Hope you are familiar basic javascript. Use the following code. With javascript, change display:block to/from display:none to show/hide popup.

<div style="background-color: rgba(150, 150, 150, 0.5); overflow: hidden; position: fixed; left: 0px; top: 0px; bottom: 0px; right: 0px; z-index: 1000; display:block;">
    <div style="background-color: rgb(255, 255, 255); width: 600px; position: static; margin: 20px auto; padding: 20px 30px 0px; top: 110px; overflow: hidden; z-index: 1001; box-shadow: 0px 3px 8px rgba(34, 25, 25, 0.4);">
        <iframe src="otherpage.html" width="400px"></iframe>
    </div>
</div>

Class 'ViewController' has no initializers in swift

The Swift Programming Language states:

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.

Therefore, you can write:

class myClass {

    var delegate: AppDelegate //non-optional variable

    init() {
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

Or:

class myClass {

    var delegate = UIApplication.sharedApplication().delegate as AppDelegate //non-optional variable

    init() {
        println("Hello")
    }

}

Or:

class myClass {

    var delegate : AppDelegate! //implicitly unwrapped optional variable set to nil when class is initialized

    init() {
        println("Hello")
    }

    func myMethod() {
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

But you can't write the following:

class myClass {

    var delegate : AppDelegate //non-optional variable

    init() {
        println("Hello")
    }

    func myMethod() {
        //too late to assign delegate as an non-optional variable
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

Mocha / Chai expect.to.throw not catching thrown errors

I have found a nice way around it:

// The test, BDD style
it ("unsupported site", () => {
    The.function(myFunc)
    .with.arguments({url:"https://www.ebay.com/"})
    .should.throw(/unsupported/);
});


// The function that does the magic: (lang:TypeScript)
export const The = {
    'function': (func:Function) => ({
        'with': ({
            'arguments': function (...args:any) {
                return () => func(...args);
            }
        })
    })
};

It's much more readable then my old version:

it ("unsupported site", () => {
    const args = {url:"https://www.ebay.com/"}; //Arrange
    function check_unsupported_site() { myFunc(args) } //Act
    check_unsupported_site.should.throw(/unsupported/) //Assert
});

How can I parse a YAML file in Python

The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml:

#!/usr/bin/env python

import yaml

with open("example.yaml", 'r') as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

And that's it. A plain yaml.load() function also exists, but yaml.safe_load() should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.

Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.

Multiple variables in a 'with' statement?

You can also separate creating a context manager (the __init__ method) and entering the context (the __enter__ method) to increase readability. So instead of writing this code:

with Company(name, id) as company, Person(name, age, gender) as person, Vehicle(brand) as vehicle:
    pass

you can write this code:

company = Company(name, id)
person = Person(name, age, gender)
vehicle = Vehicle(brand)

with company, person, vehicle:
    pass

Note that creating the context manager outside of the with statement makes an impression that the created object can also be further used outside of the statement. If this is not true for your context manager, the false impression may counterpart the readability attempt.

The documentation says:

Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.

This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used.

How to create virtual column using MySQL SELECT?

You could use a CASE statement, like

SELECT name
       ,address
       ,CASE WHEN a < b THEN '1' 
             ELSE '2' END AS one_or_two
FROM ...

Undo git stash pop that results in merge conflict

Luckily git stash pop does not change the stash in the case of a conflict!

So nothing, to worry about, just clean up your code and try it again.

Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop again and you get the same stash, that conflicted before.

Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.

PHP Warning: PHP Startup: ????????: Unable to initialize module

In my case, with Windows Server 2008, I had to change the PATH variable. The former version of PHP (VC9) was inside it.

I have changed it with the newer version of PHP (VC11).

After a restart of Apache, it was okay.

How to call any method asynchronously in c#

public partial class MainForm : Form
{
    Image img;
    private void button1_Click(object sender, EventArgs e)
    {
        LoadImageAsynchronously("http://media1.santabanta.com/full5/Indian%20%20Celebrities(F)/Jacqueline%20Fernandez/jacqueline-fernandez-18a.jpg");
    }

    private void LoadImageAsynchronously(string url)
    {
        /*
        This is a classic example of how make a synchronous code snippet work asynchronously.
        A class implements a method synchronously like the WebClient's DownloadData(…) function for example
            (1) First wrap the method call in an Anonymous delegate.
            (2) Use BeginInvoke(…) and send the wrapped anonymous delegate object as the last parameter along with a callback function name as the first parameter.
            (3) In the callback method retrieve the ar's AsyncState as a Type (typecast) of the anonymous delegate. Along with this object comes EndInvoke(…) as free Gift
            (4) Use EndInvoke(…) to retrieve the synchronous call’s return value in our case it will be the WebClient's DownloadData(…)’s return value.
        */
        try
        {
            Func<Image> load_image_Async = delegate()
            {
                WebClient wc = new WebClient();
                Bitmap bmpLocal = new Bitmap(new MemoryStream(wc.DownloadData(url)));
                wc.Dispose();
                return bmpLocal;
            };

            Action<IAsyncResult> load_Image_call_back = delegate(IAsyncResult ar)
            {
                Func<Image> ss = (Func<Image>)ar.AsyncState;
                Bitmap myBmp = (Bitmap)ss.EndInvoke(ar);

                if (img != null) img.Dispose();
                if (myBmp != null)
                    img = myBmp;
                Invalidate();
                //timer.Enabled = true;
            };
            //load_image_Async.BeginInvoke(callback_load_Image, load_image_Async);             
            load_image_Async.BeginInvoke(new AsyncCallback(load_Image_call_back), load_image_Async);             
        }
        catch (Exception ex)
        {

        }
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        if (img != null)
        {
            Graphics grfx = e.Graphics;
            grfx.DrawImage(img,new Point(0,0));
        }
    }

Objective-C ARC: strong vs retain and weak vs assign

The differences between strong and retain:

  • In iOS4, strong is equal to retain
  • It means that you own the object and keep it in the heap until don’t point to it anymore
  • If you write retain it will automatically work just like strong

The differences between weak and assign:

  • A “weak” reference is a reference that you don’t retain and you keep it as long as someone else points to it strongly
  • When the object is “deallocated”, the weak pointer is automatically set to nil
  • A "assign" property attribute tells the compiler how to synthesize the property’s setter implementation

BAT file to open CMD in current directory

you probably want to do this:

cd /d %~dp0
cmd.exe

this will set your current directory to the directory you have the batch file in

How can I conditionally require form inputs with AngularJS?

For Angular2

<input type='email' 
    [(ngModel)]='contact.email'
    [required]='!contact.phone' >

How do I perform query filtering in django templates

For anyone looking for an answer in 2020. This worked for me.

In Views:

 class InstancesView(generic.ListView):
        model = AlarmInstance
        context_object_name = 'settings_context'
        queryset = Group.objects.all()
        template_name = 'insta_list.html'

        @register.filter
        def filter_unknown(self, aVal):
            result = aVal.filter(is_known=False)
            return result

        @register.filter
        def filter_known(self, aVal):
            result = aVal.filter(is_known=True)
            return result

In template:

{% for instance in alarm.qar_alarm_instances|filter_unknown:alarm.qar_alarm_instances %}

In pseudocode:

For each in model.child_object|view_filter:filter_arg

Hope that helps.

Which TensorFlow and CUDA version combinations are compatible?

if you are coding in jupyter notebook, and want to check which cuda version tf is using, run the follow command directly into jupyter cell:

!conda list cudatoolkit

!conda list cudnn

and to check if the gpu is visible to tf:

tf.test.is_gpu_available(
    cuda_only=False, min_cuda_compute_capability=None
)

What is JSONP, and why was it created?

JSONP works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is tht JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.

For Further Reading Visit: https://blogs.sap.com/2013/07/15/secret-behind-jsonp/

client side snippet of code

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <title>AvLabz - CORS : The Secrets Behind JSONP </title>
     <meta charset="UTF-8" />
    </head>
    <body>
      <input type="text" id="username" placeholder="Enter Your Name"/>
      <button type="submit" onclick="sendRequest()"> Send Request to Server </button>
    <script>
    "use strict";
    //Construct the script tag at Runtime
    function requestServerCall(url) {
      var head = document.head;
      var script = document.createElement("script");

      script.setAttribute("src", url);
      head.appendChild(script);
      head.removeChild(script);
    }

    //Predefined callback function    
    function jsonpCallback(data) {
      alert(data.message); // Response data from the server
    }

    //Reference to the input field
    var username = document.getElementById("username");

    //Send Request to Server
    function sendRequest() {
      // Edit with your Web Service URL
      requestServerCall("http://localhost/PHP_Series/CORS/myService.php?callback=jsonpCallback&message="+username.value+"");
    }    

  </script>
   </body>
   </html>

Server side piece of PHP code

<?php
    header("Content-Type: application/javascript");
    $callback = $_GET["callback"];
    $message = $_GET["message"]." you got a response from server yipeee!!!";
    $jsonResponse = "{\"message\":\"" . $message . "\"}";
    echo $callback . "(" . $jsonResponse . ")";
?>

How to extract multiple JSON objects from one file?

So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.

The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function.

import json
def json_reader(filename):
    with open(filename) as f:
        for line in f:
            yield json.loads(line)

However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.

def json_writer(file, json_objects):
    with open(file, "w") as f:
        for jsonobj in json_objects:
            jsonstr = json.dumps(jsonobj)
            f.write(jsonstr + "\n")

You could also do the same operation with file.writelines() and a list comprehension:

...
    json_strs = [json.dumps(j) + "\n" for j in json_objects]
    f.writelines(json_strs)
...

And if you wanted to append the data instead of writing a new file just change open(file, "w") to open(file, "a").

In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.

On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write

lst = list(json_reader(file))

Using an authorization header with Fetch in React Native

It turns out, I was using the fetch method incorrectly.

fetch expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.

I was wrapping the intended object within a second object, which did not get me any desired result.

Here's how it looks on a high level:

fetch('API_ENDPOINT', OBJECT)  
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

I structured my object as such:

var obj = {  
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Origin': '',
    'Host': 'api.producthunt.com'
  },
  body: JSON.stringify({
    'client_id': '(API KEY)',
    'client_secret': '(API SECRET)',
    'grant_type': 'client_credentials'
  })

Running ASP.Net on a Linux based server

I can speak from experience. Even if your ASP.net website only uses .NET libraries supported by Mono you are going to have a hard time getting it to run if its anything beyond Hello World.

You won't have to re-write much code but you will spend hours/days/weeks dealing with little issues with mod_mono/xsp/apache configuration and file permissions and error handling and all the little things that go into a large website. (Be prepared to spend a lot of time asking questions on serverfault :) )

The problem is that a lot of people don't use Mono for ASP.net websites and so there aren't as many people reporting bugs so a lot of things that are minor bugs go un-fixed for a long time.

How do I get logs from all pods of a Kubernetes replication controller?

Not sure if this is a new thing, but with deployments it is possible to do it like this:

kubectl logs deployment/app1

What's the difference between text/xml vs application/xml for webservice response

According to this article application/xml is preferred.


EDIT

I did a little follow-up on the article.

The author claims that the encoding declared in XML processing instructions, like:

<?xml version="1.0" encoding="UTF-8"?>

can be ignored when text/xml media type is used.

They support the thesis with the definition of text/* MIME type family specification in RFC 2046, specifically the following fragment:

4.1.2.  Charset Parameter

   A critical parameter that may be specified in the Content-Type field
   for "text/plain" data is the character set.  This is specified with a
   "charset" parameter, as in:

     Content-type: text/plain; charset=iso-8859-1

   Unlike some other parameter values, the values of the charset
   parameter are NOT case sensitive.  The default character set, which
   must be assumed in the absence of a charset parameter, is US-ASCII.

   The specification for any future subtypes of "text" must specify
   whether or not they will also utilize a "charset" parameter, and may
   possibly restrict its values as well.  For other subtypes of "text"
   than "text/plain", the semantics of the "charset" parameter should be
   defined to be identical to those specified here for "text/plain",
   i.e., the body consists entirely of characters in the given charset.
   In particular, definers of future "text" subtypes should pay close
   attention to the implications of multioctet character sets for their
   subtype definitions.

According to them, such difficulties can be avoided when using application/xml MIME type. Whether it's true or not, I wouldn't go as far as to avoid text/xml. IMHO, it's best just to follow the semantics of human-readability(non-readability) and always remember to specify the charset.

How can I make a countdown with NSTimer?

Make Countdown app Xcode 8.1, Swift 3

import UIKit
import Foundation

class ViewController: UIViewController, UITextFieldDelegate {

    var timerCount = 0
    var timerRunning = false

    @IBOutlet weak var timerLabel: UILabel! //ADD Label
    @IBOutlet weak var textField: UITextField! //Add TextField /Enter any number to Countdown

    override func viewDidLoad() {
        super.viewDidLoad()

        //Reset
        timerLabel.text = ""
        if timerCount == 0 {
            timerRunning = false
        }
}

       //Figure out Count method
    func Counting() {
        if timerCount > 0 {
        timerLabel.text = "\(timerCount)"
            timerCount -= 1
        } else {
            timerLabel.text = "GO!"

        }

    }

    //ADD Action Button
    @IBAction func startButton(sender: UIButton) {

        //Figure out timer
        if timerRunning == false {
         _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.Counting), userInfo: nil, repeats: true)
            timerRunning = true
        }

        //unwrap textField and Display result
        if let countebleNumber = Int(textField.text!) {
            timerCount = countebleNumber
            textField.text = "" //Clean Up TextField
        } else {
            timerCount = 3 //Defoult Number to Countdown if TextField is nil
            textField.text = "" //Clean Up TextField
        }

    }

    //Dismiss keyboard
    func keyboardDismiss() {
        textField.resignFirstResponder()
    }

    //ADD Gesture Recignizer to Dismiss keyboard then view tapped
    @IBAction func viewTapped(_ sender: AnyObject) {
        keyboardDismiss()
    }

    //Dismiss keyboard using Return Key (Done) Button
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        keyboardDismiss()

        return true
    }

}

https://github.com/nikae/CountDown-

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

How do I include a JavaScript script file in Angular and call a function from that script?

Refer the scripts inside the angular-cli.json (angular.json when using angular 6+) file.

"scripts": [
    "../path" 
 ];

then add in typings.d.ts (create this file in src if it does not already exist)

declare var variableName:any;

Import it in your file as

import * as variable from 'variableName';

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Maven2 property that indicates the parent directory

I needed to solve similar problem for local repository placed in the main project of multi-module project. Essentially the real path was ${basedir}/lib. Finally I settled on this in my parent.pom:

<repository>
    <id>local-maven-repo</id>
    <url>file:///${basedir}/${project.parent.relativePath}/lib</url>
</repository>

That basedir always shows to current local module, there is no way to get path to "master" project (Maven's shame). Some of my submodules are one dir deeper, some are two dirs deeper, but all of them are direct submodules of the parent that defines the repo URL.

So this does not resolve the problem in general. You may always combine it with Clay's accepted answer and define some other property - works fine and needs to be redefined only for cases where the value from parent.pom is not good enough. Or you may just reconfigure the plugin - which you do only in POM artifacts (parents of other sub-modules). Value extracted into property is probably better if you need it on more places, especially when nothing in the plugin configuration changes.

Using basedir in the value was the essential part here, because URL file://${project.parent.relativePath}/lib did not want to do the trick (I removed one slash to make it relative). Using property that gives me good absolute path and then going relative from it was necessary.

When the path is not URL/URI, it probably is not such a problem to drop basedir.

ASP.NET Setting width of DataBound column in GridView

hey recently i figured it out how to set width if your gridview databound with sql dataset.first set these control RowStyle-Wrap="false" HeaderStyle-Wrap="false" and then you can set the column width as much as you like. ex : ItemStyle-Width="150px" HeaderStyle-Width="150px"

Perform a Shapiro-Wilk Normality Test

You are applying shapiro.test() to a data.frame instead of the column. Try the following:

shapiro.test(heisenberg$HWWIchg)

Setting Short Value Java

You can use setTableId((short)100). I think this was changed in Java 5 so that numeric literals assigned to byte or short and within range for the target are automatically assumed to be the target type. That latest J2ME JVMs are derived from Java 4 though.

How to set the font style to bold, italic and underlined in an Android TextView?

Or just like this in Kotlin:

val tv = findViewById(R.id.textViewOne) as TextView
tv.setTypeface(null, Typeface.BOLD_ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD or Typeface.ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD)
// OR
tv.setTypeface(null, Typeface.ITALIC)
// AND
tv.paintFlags = tv.paintFlags or Paint.UNDERLINE_TEXT_FLAG

Or in Java:

TextView tv = (TextView)findViewById(R.id.textViewOne);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD|Typeface.ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD);
// OR
tv.setTypeface(null, Typeface.ITALIC);
// AND
tv.setPaintFlags(tv.getPaintFlags()|Paint.UNDERLINE_TEXT_FLAG);

Keep it simple and in one line :)

Set object property using reflection

Yes, you can use Type.InvokeMember():

using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
    Type.DefaultBinder, obj, "Value");

This will throw an exception if obj doesn't have a property called Name, or it can't be set.

Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:

using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
    prop.SetValue(obj, "Value", null);
}

Python AttributeError: 'module' object has no attribute 'Serial'

Yes this topic is a bit old but i wanted to share the solution that worked for me for those who might need it anyway

As Ali said, try to locate your program using the following from terminal :

 sudo python3
 import serial

print(serial.__file__) --> Copy

CTRL+D #(to get out of python)

sudo python3-->paste/__init__.py

Activating __init__.py will say to your program "ok i'm going to use Serial from python3". My problem was that my python3 program was using Serial from python 2.7

Other solution: remove other python versions

Cao

Sources : https://raspberrypi.stackexchange.com/questions/74742/python-serial-serial-module-not-found-error/85930#85930

Tryhard

Git - How to fix "corrupted" interactive rebase?

I had the same problem. I used process explorer as suggested in other post (i am not able to find that post) and figured out which process has a lock on the file and kill it. then execute the --continue or --abort as per needs