Programs & Examples On #Multipart

Multipart is content type that allows multiple MIME types to be embedded in a single message.

How can I make a multipart/form-data POST request using Java?

If size of the JARs matters (e.g. in case of applet), one can also directly use httpmime with java.net.HttpURLConnection instead of HttpClient.

httpclient-4.2.4:      423KB
httpmime-4.2.4:         26KB
httpcore-4.2.4:        222KB
commons-codec-1.6:     228KB
commons-logging-1.1.1:  60KB
Sum:                   959KB

httpmime-4.2.4:         26KB
httpcore-4.2.4:        222KB
Sum:                   248KB

Code:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");

FileBody fileBody = new FileBody(new File(fileName));
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);

connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
OutputStream out = connection.getOutputStream();
try {
    multipartEntity.writeTo(out);
} finally {
    out.close();
}
int status = connection.getResponseCode();
...

Dependency in pom.xml:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.2.4</version>
</dependency>

Multipart File upload Spring Boot

   @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("5120MB");
        factory.setMaxRequestSize("5120MB");
        return factory.createMultipartConfig();
    }

put it in class where you are defining beans

What is http multipart request?

A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

Example of multipart/form-data

Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:

Example:

POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"

content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"

content of picture_of_sunset.jpg ...
--12345--

I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:

POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde

--abcde
Content-Disposition: file; file="picture.jpg"

content of jpg...
--abcde
Content-Disposition: file; file="test.py"

content of test.py file ....
--abcde--
--12345--

Take a look at the link above.

Where to change the value of lower_case_table_names=2 on windows xampp

Also works in Wampserver. Click on the Green Wampserver Icon, choose MySql, then my.ini. This will allow you to open the my.ini file. Then -

  1. look up for: # The MySQL server [mysqld]
  2. add this right below it: lower_case_table_names = 2
  3. save the file and restart MySQL service

Important Note - add the lower_case_table_names = 2 statement NOT under the [mysql] statement, but under the [mysqld] statement

Reference - http://doc.silverstripe.org/framework/en/installation/windows-wamp

Is there a way to add/remove several classes in one single instruction with classList?

To add class to a element

document.querySelector(elem).className+=' first second third';

UPDATE:

Remove a class

document.querySelector(elem).className=document.querySelector(elem).className.split(class_to_be_removed).join(" ");

Override devise registrations controller

I believe there is a better solution than rewrite the RegistrationsController. I did exactly the same thing (I just have Organization instead of Company).

If you set properly your nested form, at model and view level, everything works like a charm.

My User model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_many :owned_organizations, :class_name => 'Organization', :foreign_key => :owner_id

  has_many :organization_memberships
  has_many :organizations, :through => :organization_memberships

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :owned_organizations_attributes

  accepts_nested_attributes_for :owned_organizations
  ...
end

My Organization Model:

class Organization < ActiveRecord::Base
  belongs_to :owner, :class_name => 'User'
  has_many :organization_memberships
  has_many :users, :through => :organization_memberships
  has_many :contracts

  attr_accessor :plan_name

  after_create :set_owner_membership, :set_contract
  ...
end

My view : 'devise/registrations/new.html.erb'

<h2>Sign up</h2>

<% resource.owned_organizations.build if resource.owned_organizations.empty? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :name %><br />
    <%= f.text_field :name %></p>

  <p><%= f.label :email %><br />
    <%= f.text_field :email %></p>

  <p><%= f.label :username %><br />
    <%= f.text_field :username %></p>

  <p><%= f.label :password %><br />
    <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %></p>

  <%= f.fields_for :owned_organizations do |organization_form| %>

    <p><%= organization_form.label :name %><br />
      <%= organization_form.text_field :name %></p>

    <p><%= organization_form.label :subdomain %><br />
      <%= organization_form.text_field :subdomain %></p>

    <%= organization_form.hidden_field :plan_name, :value => params[:plan] %>

  <% end %>

  <p><%= f.submit "Sign up" %></p>
<% end %>

<%= render :partial => "devise/shared/links" %>

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Well pandas use bitwise & | and each condition should be wrapped in a ()

For example following works

data_query = data[(data['year'] >= 2005) & (data['year'] <= 2010)]

But the same query without proper brackets does not

data_query = data[(data['year'] >= 2005 & data['year'] <= 2010)]

WaitAll vs WhenAll

What do they do:

  • Internally both do the same thing.

What's the difference:

  • WaitAll is a blocking call
  • WhenAll - not - code will continue executing

Use which when:

  • WaitAll when cannot continue without having the result
  • WhenAll when what just to be notified, not blocked

What determines the monitor my app runs on?

Important note: If you remember the position of your application and shutdown and then start up again at that position, keep in mind that the user's monitor configuration may have changed while your application was closed.

Laptop users, for example, frequently change their display configuration. When docked there may be a 2nd monitor that disappears when undocked. If the user closes an application that was running on the 2nd monitor and the re-opens the application when the monitor is disconnected, restoring the window to the previous coordinates will leave it completely off-screen.

To figure out how big the display really is, check out GetSystemMetrics.

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:

/Applications/mampstack-7.1.21-0/php/bin
  1. In terminal run vim ~/.bash_profile to open ~/.bash_profile

  2. Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:

    export PATH="/Applications/mampstack-7.1.21-0/php/bin/:$PATH"

  3. Hit ESC, Type :wq, and hit Enter

  4. In Terminal run source ~/.bash_profile
  5. In Terminal type which php, output should be the path to MAMP PHP install.

How to read the RGB value of a given pixel in Python?

Image manipulation is a complex topic, and it's best if you do use a library. I can recommend gdmodule which provides easy access to many different image formats from within Python.

Adding space/padding to a UILabel

Swift 3 Code with Implementation Example

class UIMarginLabel: UILabel {

    var topInset:       CGFloat = 0
    var rightInset:     CGFloat = 0
    var bottomInset:    CGFloat = 0
    var leftInset:      CGFloat = 0

    override func drawText(in rect: CGRect) {
        let insets: UIEdgeInsets = UIEdgeInsets(top: self.topInset, left: self.leftInset, bottom: self.bottomInset, right: self.rightInset)
        self.setNeedsLayout()
        return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }
}

class LabelVC: UIViewController {

    //Outlets
    @IBOutlet weak var labelWithMargin: UIMarginLabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Label settings.
        labelWithMargin.leftInset = 10
        view.layoutIfNeeded()
    }
}

Don't forget to add class name UIMarginLabel in storyboard label object. Happy Coding!

Cut Java String at a number of character

String strOut = str.substring(0, 8) + "...";

How to get first character of a string in SQL?

If you search the first char of string in Sql string

SELECT CHARINDEX('char', 'my char')

=> return 4

Visual Studio Code: How to show line endings

Render Line Endings is a VS Code extension that is still actively maintained (as of Apr 2020):

https://marketplace.visualstudio.com/items?itemName=medo64.render-crlf

https://github.com/medo64/render-crlf/

It can be configured like this:

{
    "editor.renderWhitespace": "all",
    "code-eol.newlineCharacter": "¬",
    "code-eol.returnCharacter" : "¤",
    "code-eol.crlfCharacter"   : "¤¬",
}

and looks like this:

enter image description here

How to insert data into elasticsearch

Let me explain clearly.. If you are familiar With rdbms.. Index is database.. And index type is table.. It mean index is collection of index types., like collection of tables as database (DB).

in NOSQL.. Index is database and index type is collections. Group of collection as database..

To execute those queries... U need to install CURL for Windows.

Curl is nothing but a command line rest tool.. If you want a graphical tool.. Try

Sense plugin for chrome...

Hope it helps..

Leverage browser caching, how on apache or .htaccess?

This is what I use to control headers/caching, I'm not an Apache pro, so let me know if there is room for improvement, but I know that this has been working well on all of my sites for some time now.

Mod_expires

http://httpd.apache.org/docs/2.2/mod/mod_expires.html

This module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.

These HTTP headers are an instruction to the client about the document's validity and persistence. If cached, the document may be fetched from the cache rather than from the source until this time has passed. After that, the cache copy is considered "expired" and invalid, and a new copy must be obtained from the source.

# BEGIN Expires
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifModule>
# END Expires

Mod_headers

http://httpd.apache.org/docs/2.2/mod/mod_headers.html

This module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.

# BEGIN Caching
<ifModule mod_headers.c>
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "max-age=216000, private"
</filesMatch>
<filesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=216000, public, must-revalidate"
</filesMatch>
<filesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=1, private, must-revalidate"
</filesMatch>
</ifModule>
# END Caching

How can I use Helvetica Neue Condensed Bold in CSS?

I had the same problem and trouble getting it to work on all browsers.

So this is the best font stack for Helvetica Neue Condensed Bold I could find:

font-family: "HelveticaNeue-CondensedBold", "HelveticaNeueBoldCondensed", "HelveticaNeue-Bold-Condensed", "Helvetica Neue Bold Condensed", "HelveticaNeueBold", "HelveticaNeue-Bold", "Helvetica Neue Bold", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosCnBold', "Helvetica", "Tahoma", "Geneva", "Arial Narrow", "Arial", sans-serif; font-weight:600; font-stretch:condensed;

Even more stacks to find at:

http://rachaelmoore.name/posts/design/css/web-safe-helvetica-font-stack/

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

SQL Server - after insert trigger - update another column in the same table

Another option would be to enclose the update statement in an IF statement and call TRIGGER_NESTLEVEL() to restrict the update being run a second time.

CREATE TRIGGER Table_A_Update ON Table_A AFTER UPDATE 
AS
IF ((SELECT TRIGGER_NESTLEVEL()) < 2)
BEGIN
    UPDATE a
    SET Date_Column = GETDATE()
    FROM Table_A a
    JOIN inserted i ON a.ID = i.ID
END

When the trigger initially runs the TRIGGER_NESTLEVEL is set to 1 so the update statement will be executed. That update statement will in turn fire that same trigger except this time the TRIGGER_NESTLEVEL is set to 2 and the update statement will not be executed.

You could also check the TRIGGER_NESTLEVEL first and if its greater than 1 then call RETURN to exit out of the trigger.

IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;

How do I rename a repository on GitHub?

It is worth noting that if you fork a GitHub project and then rename the newly spawned copy, the new name appears in the members network graph of the parent project. The complementary relationship is preserved as well. This should address any reservations associated with the first point in the original question related to redirects, i.e. you can still get here from there, so to speak. I, too, was hesitant because of the irrevocability implied by the warning, so hopefully this will save others that delay.

Change the content of a div based on selection from dropdown menu

I am not a coder, but you could save a few lines:

<div>
            <select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
                <option value="">hire me for real estate</option>
                <option value="me!!!">Who is a good Broker? </option>
                <option value="yes!!!">Can I buy a house with no down payment</option>
                <option value="send me a note!">Get my contact info?</option>
            </select>
        </div>

<div id="less_is_more"></div>

Here is demo.

How do I get the YouTube video ID from a URL?

Slightly stricter version:

^https?://(?:www\.)?youtu(?:\.be|be\.com)/(?:\S+/)?(?:[^\s/]*(?:\?|&)vi?=)?([^#?&]+)

Tested on:

http://www.youtube.com/user/dreamtheater#p/u/1/oTJRivZTMLs
https://youtu.be/oTJRivZTMLs?list=PLToa5JuFMsXTNkrLJbRlB--76IAOjRM9b
http://www.youtube.com/watch?v=oTJRivZTMLs&feature=youtu.be
https://youtu.be/oTJRivZTMLs
http://youtu.be/oTJRivZTMLs&feature=channel
http://www.youtube.com/ytscreeningroom?v=oTJRivZTMLs
http://www.youtube.com/embed/oTJRivZTMLs?rel=0
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/vi/oTJRivZTMLs&feature=channel
http://youtube.com/?v=oTJRivZTMLs&feature=channel
http://youtube.com/?feature=channel&v=oTJRivZTMLs
http://youtube.com/?vi=oTJRivZTMLs&feature=channel
http://youtube.com/watch?v=oTJRivZTMLs&feature=channel
http://youtube.com/watch?vi=oTJRivZTMLs&feature=channel

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

Change MySQL default character set to UTF-8 in my.cnf?

MySQL versions and Linux distributions may matter when making configurations.

However, the changes under [mysqld] section is encouraged.

I want to give a short explanation of tomazzlender's answer:

[mysqld] 
init_connect='SET collation_connection = utf8_unicode_ci' 
init_connect='SET NAMES utf8' 
character-set-server=utf8 
collation-server=utf8_unicode_ci 
skip-character-set-client-handshake

[mysqld]

This will change collation_connection to utf8_unicode_ci

init_connect='SET collation_connection = utf8_unicode_ci'

Using SET NAMES:

init_connect='SET NAMES utf8'

The SET NAMES will influence three characters, that is:

character_set_client
character_set_results
character_set_connection

This will set character_set_database & character_set_server

character-set-server=utf8

This will only affect collation_database & collation_server

collation-server=utf8_unicode_ci

Sorry, I'm not so sure what is this for. I don't use it however:

skip-character-set-client-handshake

Find the max of 3 numbers in Java with different data types

I have a very simple idea:

 int smallest = Math.min(a, Math.min(b, Math.min(c, d)));

Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.

Regards, Norbert

Center align with table-cell

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.

How to define several include path in Makefile

Make's substitutions feature is nice and helped me to write

%.i: src/%.c $(INCLUDE)
        gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@

You might find this useful, because it asks make to check for changes in include folders too

AngularJs event to call after content is loaded

The solution that work for me is the following

app.directive('onFinishRender', ['$timeout', '$parse', function ($timeout, $parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                    if (!!attr.onFinishRender) {
                        $parse(attr.onFinishRender)(scope);
                    }
                });
            }

            if (!!attr.onStartRender) {
                if (scope.$first === true) {
                    $timeout(function () {
                        scope.$emit('ngRepeatStarted');
                        if (!!attr.onStartRender) {
                            $parse(attr.onStartRender)(scope);
                        }
                    });
                }
            }
        }
    }
}]);

Controller code is the following

$scope.crearTooltip = function () {
     $('[data-toggle="popover"]').popover();
}

Html code is the following

<tr ng-repeat="item in $data" on-finish-render="crearTooltip()">

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

Save plot to image file instead of displaying it using Matplotlib

Given that today (was not available when this question was made) lots of people use Jupyter Notebook as python console, there is an extremely easy way to save the plots as .png, just call the matplotlib's pylab class from Jupyter Notebook, plot the figure 'inline' jupyter cells, and then drag that figure/image to a local directory. Don't forget %matplotlib inline in the first line!

Date format Mapping to JSON Jackson

Building on @miklov-kriven's very helpful answer, I hope these two additional points of consideration prove helpful to someone:

(1) I find it a nice idea to include serializer and de-serializer as static inner classes in the same class. NB, using ThreadLocal for thread safety of SimpleDateFormat.

public class DateConverter {

    private static final ThreadLocal<SimpleDateFormat> sdf = 
        ThreadLocal.<SimpleDateFormat>withInitial(
                () -> {return new SimpleDateFormat("yyyy-MM-dd HH:mm a z");});

    public static class Serialize extends JsonSerializer<Date> {
        @Override
        public void serialize(Date value, JsonGenerator jgen SerializerProvider provider) throws Exception {
            if (value == null) {
                jgen.writeNull();
            }
            else {
                jgen.writeString(sdf.get().format(value));
            }
        }
    }

    public static class Deserialize extends JsonDeserializer<Date> {
        @Overrride
        public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws Exception {
            String dateAsString = jp.getText();
            try {
                if (Strings.isNullOrEmpty(dateAsString)) {
                    return null;
                }
                else {
                    return new Date(sdf.get().parse(dateAsString).getTime());
                }
            }
            catch (ParseException pe) {
                throw new RuntimeException(pe);
            }
        }
    }
}

(2) As an alternative to using @JsonSerialize and @JsonDeserialize annotations on each individual class member you could also consider overriding Jackson's default serialization by applying the custom serialization at an application level, that is all class members of type Date will be serialized by Jackson using this custom serialization without explicit annotation on each field. If you are using Spring Boot for example one way to do this would as follows:

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

    @Bean
    public Module customModule() {
        SimpleModule module = new SimpleModule();
        module.addSerializer(Date.class, new DateConverter.Serialize());
        module.addDeserializer(Date.class, new Dateconverter.Deserialize());
        return module;
    }
}

private constructor

It is reasonable to make constructor private if there are other methods that can produce instances. Obvious examples are patterns Singleton (every call return the same instance) and Factory (every call usually create new instance).

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

Angular 2 - NgFor using numbers instead collections

Using custom Structural Directive with index:

According Angular documentation:

createEmbeddedView Instantiates an embedded view and inserts it into this container.

abstract createEmbeddedView(templateRef: TemplateRef, context?: C, index?: number): EmbeddedViewRef.

Param          Type           Description
templateRef    TemplateRef    the HTML template that defines the view.
context        C              optional. Default is undefined.
index          number         the 0-based index at which to insert the new view into this container. If not specified, appends the new view as the last entry.

When angular creates template by calling createEmbeddedView it can also pass context that will be used inside ng-template.

Using context optional parameter, you may use it in the component, extracting it within the template just as you would with the *ngFor.

app.component.html:

<p *for="number; let i=index; let c=length; let f=first; let l=last; let e=even; let o=odd">
  item : {{i}} / {{c}}
  <b>
    {{f ? "First,": ""}}
    {{l? "Last,": ""}}
    {{e? "Even." : ""}}
    {{o? "Odd." : ""}}
  </b>
</p>

for.directive.ts:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

class Context {
  constructor(public index: number, public length: number) { }
  get even(): boolean { return this.index % 2 === 0; }
  get odd(): boolean { return this.index % 2 === 1; }
  get first(): boolean { return this.index === 0; }
  get last(): boolean { return this.index === this.length - 1; }
}

@Directive({
  selector: '[for]'
})
export class ForDirective {
  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { }

  @Input('for') set loop(num: number) {
    for (var i = 0; i < num; i++)
      this.viewContainer.createEmbeddedView(this.templateRef, new Context(i, num));
  }
}

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Resetting MySQL Root Password with XAMPP on Localhost

Open the file C:\xampp\phpMyAdmin\config.inc.php in your text editor. Search for the tags below and edit accordingly

$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Where 'password' is your new password. In-between quotes.

GO to your browser and visit link http://localhost/phpmyadmin/. Click on 'GO' without your new password. It would log you in and you would be able to see the "CHANGE PASSWORD". Proceed to change your password and you are done.

How to configure Eclipse build path to use Maven dependencies?

I'm assuming you are using m2eclipse as you mentioned it. However it is not clear whether you created your project under Eclipse or not so I'll try to cover all cases.

  1. If you created a "Java" project under Eclipse (Ctrl+N > Java Project), then right-click the project in the Package Explorer view and go to Maven > Enable Dependency Management (depending on the initial project structure, you may have modify it to match the maven's one, for example by adding src/java to the source folders on the build path).

  2. If you created a "Maven Project" under Eclipse (Ctrl+N > Maven Project), then it should be already "Maven ready".

  3. If you created a Maven project outside Eclipse (manually or with an archetype), then simply import it in Eclipse (right-click the Package Explorer view and select Import... > Maven Projects) and it will be "Maven ready".

Now, to add a dependency, either right-click the project and select Maven > Add Dependency) or edit the pom manually.

PS: avoid using the maven-eclipse-plugin if you are using m2eclipse. There is absolutely no need for it, it will be confusing, it will generate some mess. No, really, don't use it unless you really know what you are doing.

Add rows to CSV File in powershell

Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.

Confused by python file mode "w+"

Actually, there's something wrong about all the other answers about r+ mode.

test.in file's content:

hello1
ok2
byebye3

And the py script's :

with open("test.in", 'r+')as f:
    f.readline()
    f.write("addition")

Execute it and the test.in's content will be changed to :

hello1
ok2
byebye3
addition

However, when we modify the script to :

with open("test.in", 'r+')as f:
    f.write("addition")

the test.in also do the respond:

additionk2
byebye3

So, the r+ mode will allow us to cover the content from the beginning if we did't do the read operation. And if we do some read operation, f.write()will just append to the file.

By the way, if we f.seek(0,0) before f.write(write_content), the write_content will cover them from the positon(0,0).

No server in windows>preferences

Follow the below steps:

1.Goto Help -> Install new Software
2.Give address http://download.eclipse.org/releases/oxygen and name as your choice.
3.Search for Java EE and choose 1.Eclipse Java EE Developer Tools 
4.Search for JST and choose 2.JST Server Adapters 3.JST Server Adapters 
5.Click next and accept the license agreement.

Find the server option in the window-->preferences and add server as you need

ImportError: No module named six

For Mac OS X:

pip install --ignore-installed six

Create ArrayList from array

Another way (although essentially equivalent to the new ArrayList(Arrays.asList(array)) solution performance-wise:

Collections.addAll(arraylist, array);

How do I calculate the MD5 checksum of a file in Python?

You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest(). A function to do this would look like the following:

def File_Checksum_Dis(dirname):
    
    if not os.path.exists(dirname):
        print(dirname+" directory is not existing");
    
    for fname in os.listdir(dirname):
        if not fname.endswith('~'):
            fnaav = os.path.join(dirname, fname);
            fd = open(fnaav, 'rb');
            data = fd.read();
            fd.close();
        
            print("-"*70);
            print("File Name is: ",fname);          
            print(hashlib.md5(data).hexdigest())
            print("-"*70);
                

How to sort an STL vector?

this is my approach to solve this generally. It extends the answer from Steve Jessop by removing the requirement to set template arguments explicitly and adding the option to also use functoins and pointers to methods (getters)

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>

using namespace std;

template <typename T, typename U>
struct CompareByGetter {
    U (T::*getter)() const;
    CompareByGetter(U (T::*getter)() const) : getter(getter) {};
    bool operator()(const T &lhs, const T &rhs) {
        (lhs.*getter)() < (rhs.*getter)();
    }
};

template <typename T, typename U>
CompareByGetter<T,U> by(U (T::*getter)() const) {
    return CompareByGetter<T,U>(getter);
}

//// sort_by
template <typename T, typename U>
struct CompareByMember {
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

template <typename T, typename U>
CompareByMember<T,U> by(U T::*f) {
    return CompareByMember<T,U>(f);
}

template <typename T, typename U>
struct CompareByFunction {
    function<U(T)> f;
    CompareByFunction(function<U(T)> f) : f(f) {}
    bool operator()(const T& a, const T& b) const {
        return f(a) < f(b);
    }
};

template <typename T, typename U>
CompareByFunction<T,U> by(function<U(T)> f) {
    CompareByFunction<T,U> cmp{f};
    return cmp;
}

struct mystruct {
    double x,y,z;
    string name;
    double length() const {
        return sqrt( x*x + y*y + z*z );
    }
};

ostream& operator<< (ostream& os, const mystruct& ms) {
    return os << "{ " << ms.x << ", " << ms.y << ", " << ms.z << ", " << ms.name << " len: " << ms.length() << "}";
}

template <class T>
ostream& operator<< (ostream& os, std::vector<T> v) {
    os << "[";
    for (auto it = begin(v); it != end(v); ++it) {
        if ( it != begin(v) ) {
            os << " ";
        }
        os << *it;
    }
    os << "]";
    return os;
}

void sorting() {
    vector<mystruct> vec1 = { {1,1,0,"a"}, {0,1,2,"b"}, {-1,-5,0,"c"}, {0,0,0,"d"} };

    function<string(const mystruct&)> f = [](const mystruct& v){return v.name;};

    cout << "unsorted  " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::x) );
    cout << "sort_by x " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::length));
    cout << "sort_by len " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(f) );
    cout << "sort_by name " << vec1 << endl;
}

css 100% width div not taking up full width of parent

html, body{ 
  width:100%;
}

This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.

You may want to set a min width instead.

html, body{ 
  min-width:100%;
}

So it will be 100% as a minimum, bot more if needed.

Not able to change TextField Border Color

The code in which you change the color of the primaryColor andprimaryColorDark does not change the color inicial of the border, only after tap the color stay black

The attribute that must be changed is hintColor

BorderSide should not be used for this, you need to change Theme.

To make the red color default to put the theme in MaterialApp(theme: ...) and to change the theme of a specific widget, such as changing the default red color to the yellow color of the widget, surrounds the widget with:

new Theme(
  data: new ThemeData(
    hintColor: Colors.yellow
  ),
  child: ...
)

Below is the code and gif:

Note that if we define the primaryColor color as black, by tapping the widget it is selected with the color black

But to change the label and text inside the widget, we need to set the theme to InputDecorationTheme

The widget that starts with the yellow color has its own theme and the widget that starts with the red color has the default theme defined with the function buildTheme()

enter image description here

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

ThemeData buildTheme() {
  final ThemeData base = ThemeData();
  return base.copyWith(
    hintColor: Colors.red,
    primaryColor: Colors.black,
    inputDecorationTheme: InputDecorationTheme(
      hintStyle: TextStyle(
        color: Colors.blue,
      ),
      labelStyle: TextStyle(
        color: Colors.green,
      ),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: buildTheme(),
      home: new HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String xp = '0';

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: new Container(
        padding: new EdgeInsets.only(top: 16.0),
        child: new ListView(
          children: <Widget>[
            new InkWell(
              onTap: () {},
              child: new Theme(
                data: new ThemeData(
                  hintColor: Colors.yellow
                ),
                child: new TextField(
                  decoration: new InputDecoration(
                      border: new OutlineInputBorder(),
                      hintText: 'Tell us about yourself',
                      helperText: 'Keep it short, this is just a demo.',
                      labelText: 'Life story',
                      prefixIcon: const Icon(Icons.person, color: Colors.green,),
                      prefixText: ' ',
                      suffixText: 'USD',
                      suffixStyle: const TextStyle(color: Colors.green)),
                )
              )
            ),
            new InkWell(
              onTap: () {},                
              child: new TextField(
                decoration: new InputDecoration(
                    border: new OutlineInputBorder(
                      borderSide: new BorderSide(color: Colors.teal)
                    ),
                    hintText: 'Tell us about yourself',
                    helperText: 'Keep it short, this is just a demo.',
                    labelText: 'Life story',
                    prefixIcon: const Icon(Icons.person, color: Colors.green,),
                    prefixText: ' ',
                    suffixText: 'USD',
                    suffixStyle: const TextStyle(color: Colors.green)),
              )
            )
          ],
        ),
      )
    );
  }
}

Is there any way to wait for AJAX response and halt execution?

use async:false attribute along with url and data. this will help to execute ajax call immediately and u can fetch and use data from server.

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        async:false
        success: function(data) {
            return data;
        }
    });
}

How to add new activity to existing project in Android Studio?

In Android Studio 2, just right click on app and select New > Activity > ... to create desired activity type.

enter image description here

How to load a controller from another controller in codeigniter?

While the methods above might work, here is a very good method.

Extend the core controller with a MY controller, then extend this MY controller for all your other controllers. For example, you could have:

class MY_Controller extends CI_Controller {
    public function is_logged()
    {
        //Your code here
    }
public function logout()
    {
        //Your code here
    }
}

Then your other controllers could then extend this as follows:

class Another_Controller extends MY_Controller {
    public function show_home()
    {
         if (!$this->is_logged()) {
           return false;
         }
    }
public function logout()
    {
        $this->logout();
    }
}

What is difference between sleep() method and yield() method of multi threading?

We can prevent a thread from execution by using any of the 3 methods of Thread class:

  1. yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority or higher priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.

  2. join() If any executing thread t1 calls join() on t2 (i.e. t2.join()) immediately t1 will enter into waiting state until t2 completes its execution.

  3. sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).

How to run wget inside Ubuntu Docker image?

You need to install it first. Create a new Dockerfile, and install wget in it:

FROM ubuntu:14.04
RUN  apt-get update \
  && apt-get install -y wget \
  && rm -rf /var/lib/apt/lists/*

Then, build that image:

docker build -t my-ubuntu .

Finally, run it:

docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb

What encoding/code page is cmd.exe using?

Yes, it’s frustrating—sometimes type and other programs print gibberish, and sometimes they do not.

First of all, Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the default Raster Font.

But if the console font doesn’t contain the character you’re trying to display, you’ll see question marks instead of gibberish. When you get gibberish, there’s more going on than just font settings.

When programs use standard C-library I/O functions like printf, the program’s output encoding must match the console’s output encoding, or you will get gibberish. chcp shows and sets the current codepage. All output using standard C-library I/O functions is treated as if it is in the codepage displayed by chcp.

Matching the program’s output encoding with the console’s output encoding can be accomplished in two different ways:

  • A program can get the console’s current codepage using chcp or GetConsoleOutputCP, and configure itself to output in that encoding, or

  • You or a program can set the console’s current codepage using chcp or SetConsoleOutputCP to match the default output encoding of the program.

However, programs that use Win32 APIs can write UTF-16LE strings directly to the console with WriteConsoleW. This is the only way to get correct output without setting codepages. And even when using that function, if a string is not in the UTF-16LE encoding to begin with, a Win32 program must pass the correct codepage to MultiByteToWideChar. Also, WriteConsoleW will not work if the program’s output is redirected; more fiddling is needed in that case.

type works some of the time because it checks the start of each file for a UTF-16LE Byte Order Mark (BOM), i.e. the bytes 0xFF 0xFE. If it finds such a mark, it displays the Unicode characters in the file using WriteConsoleW regardless of the current codepage. But when typeing any file without a UTF-16LE BOM, or for using non-ASCII characters with any command that doesn’t call WriteConsoleW—you will need to set the console codepage and program output encoding to match each other.


How can we find this out?

Here’s a test file containing Unicode characters:

ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

Here’s a Java program to print out the test file in a bunch of different Unicode encodings. It could be in any programming language; it only prints ASCII characters or encoded bytes to stdout.

import java.io.*;

public class Foo {

    private static final String BOM = "\ufeff";
    private static final String TEST_STRING
        = "ASCII     abcde xyz\n"
        + "German    äöü ÄÖÜ ß\n"
        + "Polish    aezznl\n"
        + "Russian   ??????? ???\n"
        + "CJK       ??\n";

    public static void main(String[] args)
        throws Exception
    {
        String[] encodings = new String[] {
            "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" };

        for (String encoding: encodings) {
            System.out.println("== " + encoding);

            for (boolean writeBom: new Boolean[] {false, true}) {
                System.out.println(writeBom ? "= bom" : "= no bom");

                String output = (writeBom ? BOM : "") + TEST_STRING;
                byte[] bytes = output.getBytes(encoding);
                System.out.write(bytes);
                FileOutputStream out = new FileOutputStream("uc-test-"
                    + encoding + (writeBom ? "-bom.txt" : "-nobom.txt"));
                out.write(bytes);
                out.close();
            }
        }
    }
}

The output in the default codepage? Total garbage!

Z:\andrew\projects\sx\1259084>chcp
Active code page: 850

Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢
= bom
´++ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢
== UTF-16LE
= no bom
A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
 = bom
 ¦A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
 == UTF-16BE
= no bom
 A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}
= bom
¦  A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}
== UTF-32LE
= no bom
A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y
   = bom
 ¦  A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y
   == UTF-32BE
= no bom
   A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}
= bom
  ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

However, what if we type the files that got saved? They contain the exact same bytes that were printed to the console.

Z:\andrew\projects\sx\1259084>type *.txt

uc-test-UTF-16BE-bom.txt


¦  A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}

uc-test-UTF-16BE-nobom.txt


 A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}

uc-test-UTF-16LE-bom.txt


ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

uc-test-UTF-16LE-nobom.txt


A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y

uc-test-UTF-32BE-bom.txt


  ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

uc-test-UTF-32BE-nobom.txt


   A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

uc-test-UTF-32LE-bom.txt


 A S C I I           a b c d e   x y z
 G e r m a n         ä ö ü   Ä Ö Ü   ß
 P o l i s h         a e z z n l
 R u s s i a n       ? ? ? ? ? ? ?   ? ? ?
 C J K               ? ?

uc-test-UTF-32LE-nobom.txt


A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y

uc-test-UTF-8-bom.txt


´++ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢

uc-test-UTF-8-nobom.txt


ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢

The only thing that works is UTF-16LE file, with a BOM, printed to the console via type.

If we use anything other than type to print the file, we get garbage:

Z:\andrew\projects\sx\1259084>copy uc-test-UTF-16LE-bom.txt CON
 ¦A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
         1 file(s) copied.

From the fact that copy CON does not display Unicode correctly, we can conclude that the type command has logic to detect a UTF-16LE BOM at the start of the file, and use special Windows APIs to print it.

We can see this by opening cmd.exe in a debugger when it goes to type out a file:

enter image description here

After type opens a file, it checks for a BOM of 0xFEFF—i.e., the bytes 0xFF 0xFE in little-endian—and if there is such a BOM, type sets an internal fOutputUnicode flag. This flag is checked later to decide whether to call WriteConsoleW.

But that’s the only way to get type to output Unicode, and only for files that have BOMs and are in UTF-16LE. For all other files, and for programs that don’t have special code to handle console output, your files will be interpreted according to the current codepage, and will likely show up as gibberish.

You can emulate how type outputs Unicode to the console in your own programs like so:

#include <stdio.h>
#define UNICODE
#include <windows.h>

static LPCSTR lpcsTest =
    "ASCII     abcde xyz\n"
    "German    äöü ÄÖÜ ß\n"
    "Polish    aezznl\n"
    "Russian   ??????? ???\n"
    "CJK       ??\n";

int main() {
    int n;
    wchar_t buf[1024];

    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    n = MultiByteToWideChar(CP_UTF8, 0,
            lpcsTest, strlen(lpcsTest),
            buf, sizeof(buf));

    WriteConsole(hConsole, buf, n, &n, NULL);

    return 0;
}

This program works for printing Unicode on the Windows console using the default codepage.


For the sample Java program, we can get a little bit of correct output by setting the codepage manually, though the output gets messed up in weird ways:

Z:\andrew\projects\sx\1259084>chcp 65001
Active code page: 65001

Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??
? ???
CJK       ??
 ??
?
?
= bom
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??
?? ???
CJK       ??
  ??
?
?
== UTF-16LE
= no bom
A S C I I           a b c d e   x y z
…

However, a C program that sets a Unicode UTF-8 codepage:

#include <stdio.h>
#include <windows.h>

int main() {
    int c, n;
    UINT oldCodePage;
    char buf[1024];

    oldCodePage = GetConsoleOutputCP();
    if (!SetConsoleOutputCP(65001)) {
        printf("error\n");
    }

    freopen("uc-test-UTF-8-nobom.txt", "rb", stdin);
    n = fread(buf, sizeof(buf[0]), sizeof(buf), stdin);
    fwrite(buf, sizeof(buf[0]), n, stdout);

    SetConsoleOutputCP(oldCodePage);

    return 0;
}

does have correct output:

Z:\andrew\projects\sx\1259084>.\test
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

The moral of the story?

  • type can print UTF-16LE files with a BOM regardless of your current codepage
  • Win32 programs can be programmed to output Unicode to the console, using WriteConsoleW.
  • Other programs which set the codepage and adjust their output encoding accordingly can print Unicode on the console regardless of what the codepage was when the program started
  • For everything else you will have to mess around with chcp, and will probably still get weird output.

Python conditional assignment operator

No, the replacement is:

try:
   v
except NameError:
   v = 'bla bla'

However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following:

try:
   v = complicated()
except ComplicatedError: # complicated failed
   v = 'fallback value'

and never be unsure whether v is set or not. If it's one of many options that can either be set or not, use a dictionary and its get method which allows a default value.

How to set the opacity/alpha of a UIImage?

Based on Alexey Ishkov's answer, but in Swift

I used an extension of the UIImage class.

Swift 2:

UIImage Extension:

extension UIImage {
    func imageWithAlpha(alpha: CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        drawAtPoint(CGPointZero, blendMode: .Normal, alpha: alpha)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

To use:

let image = UIImage(named: "my_image")
let transparentImage = image.imageWithAlpha(0.5)

Swift 3/4/5:

Note that this implementation returns an optional UIImage. This is because in Swift 3 UIGraphicsGetImageFromCurrentImageContext now returns an optional. This value could be nil if the context is nil or what not created with UIGraphicsBeginImageContext.

UIImage Extension:

extension UIImage {
    func image(alpha: CGFloat) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: .zero, blendMode: .normal, alpha: alpha)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

To use:

let image = UIImage(named: "my_image")
let transparentImage = image?.image(alpha: 0.5)

What is the best way to know if all the variables in a Class are null?

If you want this for unit testing I just use the hasNoNullFieldsOrProperties() method from assertj

assertThat(myObj).hasNoNullFieldsOrProperties();

PHP, display image with Header()

if you know the file name, but don't know the file extention you can use this function:

public function showImage($name)
    {

         $types = [
             'gif'=> 'image/gif',
             'png'=> 'image/png',
             'jpeg'=> 'image/jpeg',
             'jpg'=> 'image/jpeg',
         ];
         $root_path  = '/var/www/my_app'; //use your framework to get this properly ..
         foreach($types as $type=>$meta){
             if(file_exists($root_path .'/uploads/'.$name  .'.'. $type)){
                 header('Content-type: ' . $meta);
                 readfile($root_path .'/uploads/'.$name .'.'. $type);
                 return;
             }
         }
    }

Note: the correct content-type for JPG files is image/jpeg.

The module ".dll" was loaded but the entry-point was not found

What solved it for me was using :

regasm.exe 'xx.dll' /tlb /codebase /register

It is however, important to understand the difference between regasm.exe and regsvr.exe:

What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32?

asp.net: How can I remove an item from a dropdownlist?

myDropDown.Items.Remove(myDropDown.Items.FindByText("TextToFind"))

Detect iPhone/iPad purely by css

This is how I handle iPhone (and similar) devices [not iPad]:

In my CSS file:

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
   /* CSS overrides for mobile here */
}

In the head of my HTML document:

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">

How to initialize a vector in C++

With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:

std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };

Or even:

std::vector<int> v(2);
v = { 34,23 };

On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:

int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);

Or, for the case of assignment to an existing vector:

int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);

Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:

template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }

And then you can do this without having to repeat the size all over:

int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));

MySQL the right syntax to use near '' at line 1 error

the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.

Either put it on one line or append on each line :o)

Sqlyog must be trimming white spaces on each line which explains why its working.

Example:

$qr2="INSERT INTO wp_bp_activity
      (
            user_id,
 (this stuff)component,
     (is)      `type`,
    (a)        `action`,
  (problem)  content,
             primary_link,
             item_id,....

How do I turn off Unicode in a VC++ project?

None of the above solutions worked for me. But

#include <Windows.h>

worked fine.

Map<String, String>, how to print both the "key string" and "value string" together

There are various ways to achieve this. Here are three.

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println("using entrySet and toString");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry);
    }
    System.out.println();

    System.out.println("using entrySet and manual string creation");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    System.out.println();

    System.out.println("using keySet");
    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    System.out.println();

Output

using entrySet and toString
key1=value1
key2=value2
key3=value3

using entrySet and manual string creation
key1=value1
key2=value2
key3=value3

using keySet
key1=value1
key2=value2
key3=value3

Right way to write JSON deserializer in Spring or extend it

I was trying to @Autowire a Spring-managed service into my Deserializer. Somebody tipped me off to Jackson using the new operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer. Here's how I was able to @Autowire my service class into my Deserializer:

context.xml

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="objectMapper" ref="objectMapper" />
    </bean>
  </mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <!-- Add deserializers that require autowiring -->
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry key="com.acme.Anchor">
                <bean class="com.acme.AnchorDeserializer" />
            </entry>
        </map>
    </property>
</bean>

Now that my Deserializer is a Spring-managed bean, auto-wiring works!

AnchorDeserializer.java

public class AnchorDeserializer extends JsonDeserializer<Anchor> {
    @Autowired
    private AnchorService anchorService;
    public Anchor deserialize(JsonParser parser, DeserializationContext context)
             throws IOException, JsonProcessingException {
        // Do stuff
    }
}

AnchorService.java

@Service
public class AnchorService {}

Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!

Reversing a string in C

You can put your (len/2) test in the for loop:

for(i = 0,k=len-1 ; i < (len/2); i++,k--)
{
        temp = str[k];
        str[k] = str[i];
        str[i] = temp;

}

how to delete files from amazon s3 bucket?

Welcome to 2020 here is the answer in Python/Django:

from django.conf import settings 
import boto3   
s3 = boto3.client('s3')
s3.delete_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=f"media/{item.file.name}")

Took me far too long to find the answer and it was as simple as this.

How do I launch a Git Bash window with particular working directory using a script?

I'm not familiar with Git Bash but assuming that it is a git shell (such as git-sh) residing in /path/to/my/gitshell and your favorite terminal program is called `myterm' you can script the following:

(cd dir1; myterm -e /path/to/my/gitshell) &
(cd dir2; myterm -e /path/to/my/gitshell) &
...

Note that the parameter -e for execution may be named differently with your favorite terminal program.

How do you set the EditText keyboard to only consist of numbers on Android?

Place the below lines in your <EditText>:

android:digits="0123456789"
android:inputType="phone"

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
    System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
    return encoding.GetBytes(str);
}


// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);

wait until all threads finish their work in java

You can join to the threads. The join blocks until the thread completes.

for (Thread thread : threads) {
    thread.join();
}

Note that join throws an InterruptedException. You'll have to decide what to do if that happens (e.g. try to cancel the other threads to prevent unnecessary work being done).

Access-control-allow-origin with multiple domains

You can use owin middleware to define cors policy in which you can define multiple cors origins

return new CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider
            {
                PolicyResolver = context =>
                {
                    var policy = new CorsPolicy()
                    {
                        AllowAnyOrigin = false,
                        AllowAnyMethod = true,
                        AllowAnyHeader = true,
                        SupportsCredentials = true
                    };
                    policy.Origins.Add("http://foo.com");
                    policy.Origins.Add("http://bar.com");
                    return Task.FromResult(policy);
                }
            }
        };

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

AngularJS - add HTML element to dom in directive without jQuery

You could use something like this

var el = document.createElement("svg");
el.style.width="600px";
el.style.height="100px";
....
iElement[0].appendChild(el)

How to make padding:auto work in CSS?

The simplest supported solution is to either use margin

.element {
  display: block;
  margin: 0px auto;
}

Or use a second container around the element that has this margin applied. This will somewhat have the effect of padding: 0px auto if it did exist.

CSS

.element_wrapper {
  display: block;
  margin: 0px auto;
}
.element {
  background: blue;
}

HTML

<div class="element_wrapper">
  <div class="element">
    Hello world
  </div>
</div>

check / uncheck checkbox using jquery?

You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

var prop=false;
if(value == 1) {
   prop=true; 
}
$('#checkbox').prop('checked',prop);

or simply,

$('#checkbox').prop('checked',(value == 1));

Snippet

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var chkbox = $('.customcheckbox');_x000D_
  $(".customvalue").keyup(function() {_x000D_
    chkbox.prop('checked', this.value==1);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">
_x000D_
_x000D_
_x000D_

What are .tpl files? PHP, web design

In this specific case it is Smarty, but it could also be Jinja2 templates. They usually also have a .tpl extension.

here-document gives 'unexpected end of file' error

Please try to remove the preceeding spaces before EOF:-

/var/mail -s "$SUBJECT" "$EMAIL" <<-EOF

Using <tab> instead of <spaces> for ident AND using <<-EOF works fine.

The "-" removes the <tabs>, not <spaces>, but at least this works.

Converting File to MultiPartFile

It's working for me:

File file = path.toFile();
String mimeType = Files.probeContentType(path);     

DiskFileItem fileItem = new DiskFileItem("file", mimeType, false, file.getName(), (int) file.length(),
            file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

C++ Singleton design pattern

Simple singleton class, This must be your header class file

#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H

class SingletonClass
{
    public:
        static SingletonClass* Instance()
        {
           static SingletonClass* instance = new SingletonClass();
           return instance;
        }

        void Relocate(int X, int Y, int Z);

    private:
        SingletonClass();
        ~SingletonClass();
};

#define sSingletonClass SingletonClass::Instance()

#endif

Access your singleton like this:

sSingletonClass->Relocate(1, 2, 5);

Replace all occurrences of a string in a data frame

Equivalent to "find and replace." Don't overthink it.

Try it with one:

library(tidyverse)
df <- data.frame(name = rep(letters[1:3], each = 3), var1 = rep('< 2', 9), var2 = rep('<3', 9))

df %>% 
  mutate(var1 = str_replace(var1, " ", ""))
#>   name var1 var2
#> 1    a   <2   <3
#> 2    a   <2   <3
#> 3    a   <2   <3
#> 4    b   <2   <3
#> 5    b   <2   <3
#> 6    b   <2   <3
#> 7    c   <2   <3
#> 8    c   <2   <3
#> 9    c   <2   <3

Apply to all

df %>% 
  mutate_all(funs(str_replace(., " ", "")))
#>   name var1 var2
#> 1    a   <2   <3
#> 2    a   <2   <3
#> 3    a   <2   <3
#> 4    b   <2   <3
#> 5    b   <2   <3
#> 6    b   <2   <3
#> 7    c   <2   <3
#> 8    c   <2   <3
#> 9    c   <2   <3

If the extra space was produced by uniting columns, think about making str_trim part of your workflow.

Created on 2018-03-11 by the reprex package (v0.2.0).

'console' is undefined error for Internet Explorer

Based on two previous answers by

and the documentations for

Here's a best effort implementation for the issue, meaning if there's a console.log which actually exists, it fills in the gaps for non-existing methods via console.log.

For example for IE6/7 you can replace logging with alert (stupid but works) and then include the below monster (I called it console.js): [Feel free to remove comments as you see fit, I left them in for reference, a minimizer can tackle them]:

<!--[if lte IE 7]>
<SCRIPT LANGUAGE="javascript">
    (window.console = window.console || {}).log = function() { return window.alert.apply(window, arguments); };
</SCRIPT>
<![endif]-->
<script type="text/javascript" src="console.js"></script>

and console.js:

    /**
     * Protect window.console method calls, e.g. console is not defined on IE
     * unless dev tools are open, and IE doesn't define console.debug
     */
    (function() {
        var console = (window.console = window.console || {});
        var noop = function () {};
        var log = console.log || noop;
        var start = function(name) { return function(param) { log("Start " + name + ": " + param); } };
        var end = function(name) { return function(param) { log("End " + name + ": " + param); } };

        var methods = {
            // Internet Explorer (IE 10): http://msdn.microsoft.com/en-us/library/ie/hh772169(v=vs.85).aspx#methods
            // assert(test, message, optionalParams), clear(), count(countTitle), debug(message, optionalParams), dir(value, optionalParams), dirxml(value), error(message, optionalParams), group(groupTitle), groupCollapsed(groupTitle), groupEnd([groupTitle]), info(message, optionalParams), log(message, optionalParams), msIsIndependentlyComposed(oElementNode), profile(reportName), profileEnd(), time(timerName), timeEnd(timerName), trace(), warn(message, optionalParams)
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "msIsIndependentlyComposed", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"

            // Safari (2012. 07. 23.): https://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/Safari_Developer_Guide/DebuggingYourWebsite/DebuggingYourWebsite.html#//apple_ref/doc/uid/TP40007874-CH8-SW20
            // assert(expression, message-object), count([title]), debug([message-object]), dir(object), dirxml(node), error(message-object), group(message-object), groupEnd(), info(message-object), log(message-object), profile([title]), profileEnd([title]), time(name), markTimeline("string"), trace(), warn(message-object)
            // "assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd", "info", "log", "profile", "profileEnd", "time", "markTimeline", "trace", "warn"

            // Firefox (2013. 05. 20.): https://developer.mozilla.org/en-US/docs/Web/API/console
            // debug(obj1 [, obj2, ..., objN]), debug(msg [, subst1, ..., substN]), dir(object), error(obj1 [, obj2, ..., objN]), error(msg [, subst1, ..., substN]), group(), groupCollapsed(), groupEnd(), info(obj1 [, obj2, ..., objN]), info(msg [, subst1, ..., substN]), log(obj1 [, obj2, ..., objN]), log(msg [, subst1, ..., substN]), time(timerName), timeEnd(timerName), trace(), warn(obj1 [, obj2, ..., objN]), warn(msg [, subst1, ..., substN])
            // "debug", "dir", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "time", "timeEnd", "trace", "warn"

            // Chrome (2013. 01. 25.): https://developers.google.com/chrome-developer-tools/docs/console-api
            // assert(expression, object), clear(), count(label), debug(object [, object, ...]), dir(object), dirxml(object), error(object [, object, ...]), group(object[, object, ...]), groupCollapsed(object[, object, ...]), groupEnd(), info(object [, object, ...]), log(object [, object, ...]), profile([label]), profileEnd(), time(label), timeEnd(label), timeStamp([label]), trace(), warn(object [, object, ...])
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "profile", "profileEnd", "time", "timeEnd", "timeStamp", "trace", "warn"
            // Chrome (2012. 10. 04.): https://developers.google.com/web-toolkit/speedtracer/logging-api
            // markTimeline(String)
            // "markTimeline"

            assert: noop, clear: noop, trace: noop, count: noop, timeStamp: noop, msIsIndependentlyComposed: noop,
            debug: log, info: log, log: log, warn: log, error: log,
            dir: log, dirxml: log, markTimeline: log,
            group: start('group'), groupCollapsed: start('groupCollapsed'), groupEnd: end('group'),
            profile: start('profile'), profileEnd: end('profile'),
            time: start('time'), timeEnd: end('time')
        };

        for (var method in methods) {
            if ( methods.hasOwnProperty(method) && !(method in console) ) { // define undefined methods as best-effort methods
                console[method] = methods[method];
            }
        }
    })();

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

I just found a new trick to center a box in the middle of the screen even if you don't have fixed dimensions. Let's say you would like a box 60% width / 60% height. The way to make it centered is by creating 2 boxes: a "container" box that position left: 50% top :50%, and a "text" box inside with reverse position left: -50%; top :-50%;

It works and it's cross browser compatible.

Check out the code below, you probably get a better explanation:

_x000D_
_x000D_
jQuery('.close a, .bg', '#message').on('click', function() {_x000D_
  jQuery('#message').fadeOut();_x000D_
  return false;_x000D_
});
_x000D_
html, body {_x000D_
  min-height: 100%;_x000D_
}_x000D_
_x000D_
#message {_x000D_
  height: 100%;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#message .container {_x000D_
  height: 60%;_x000D_
  left: 50%;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  z-index: 10;_x000D_
  width: 60%;_x000D_
}_x000D_
_x000D_
#message .container .text {_x000D_
  background: #fff;_x000D_
  height: 100%;_x000D_
  left: -50%;_x000D_
  position: absolute;_x000D_
  top: -50%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#message .bg {_x000D_
  background: rgba(0, 0, 0, 0.5);_x000D_
  height: 100%;_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
  z-index: 9;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
  <div class="container">_x000D_
    <div class="text">_x000D_
      <h2>Warning</h2>_x000D_
      <p>The message</p>_x000D_
      <p class="close"><a href="#">Close Window</a></p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="bg"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

Difference between StringBuilder and StringBuffer

StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence.

StringBuilder was added in Java 5. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.

How can I return the difference between two lists?

If you only want find missing values in b, you can do:

List toReturn = new ArrayList(a);
toReturn.removeAll(b);

return toReturn;

If you want to find out values which are present in either list you can execute upper code twice. With changed lists.

How to receive serial data using android bluetooth

I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.

My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

I have faced same issue after install macOS Catalina. I had try below command and its working.

sudo gem update

Linux shell sort file according to the second column?

If this is UNIX:

sort -k 2 file.txt

You can use multiple -k flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

sort -k 2,2 -k 1,1 file.txt

Relevant options from "man sort":

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

How do I include a JavaScript file in another JavaScript file?

If you use Angular, then a plugin module $ocLazyLoad can help you to do that.

Here are some quotes from its documentation:

Load one or more modules & components with multiple files:

$ocLazyLoad.load(['testModule.js', 'testModuleCtrl.js', 'testModuleService.js']);

Load one or more modules with multiple files and specify a type where necessary: Note: When using the requireJS style formatting (with js! at the beginning for example), do not specify a file extension. Use one or the other.

$ocLazyLoad.load([
  'testModule.js',
   {type: 'css', path: 'testModuleCtrl'},
   {type: 'html', path: 'testModuleCtrl.html'},
   {type: 'js', path: 'testModuleCtrl'},
   'js!testModuleService',
   'less!testModuleLessFile'
]);

You can load external libs (not angular):

$ocLazyLoad.load(['testModule.js', 
   'bower_components/bootstrap/dist/js/bootstrap.js', 'anotherModule.js']);

You can also load css and template files:

 $ocLazyLoad.load([
     'bower_components/bootstrap/dist/js/bootstrap.js',
     'bower_components/bootstrap/dist/css/bootstrap.css',
     'partials/template1.html'
 ]);

Fetch API with Cookie

If you are reading this in 2019, credentials: "same-origin" is the default value.

fetch(url).then

Multiple commands in an alias for bash

Add this function to your ~/.bashrc and restart your terminal or run source ~/.bashrc

function lock() {
    gnome-screensaver
    gnome-screensaver-command --lock
}

This way these two commands will run whenever you enter lock in your terminal.

In your specific case creating an alias may work, but I don't recommend it. Intuitively we would think the value of an alias would run the same as if you entered the value in the terminal. However that's not the case:

The rules concerning the definition and use of aliases are somewhat confusing.

and

For almost every purpose, shell functions are preferred over aliases.

So don't use an alias unless you have to. https://ss64.com/bash/alias.html

Should I set max pool size in database connection string? What happens if I don't?

Currently your application support 100 connections in pool. Here is what conn string will look like if you want to increase it to 200:

public static string srConnectionString = 
                "server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;";

You can investigate how many connections with database your application use, by executing sp_who procedure in your database. In most cases default connection pool size will be enough.

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Create code first, many to many, with additional fields in association table

I want to propose a solution where both flavors of a many-to-many configuration can be achieved.

The "catch" is we need to create a view that targets the Join Table, since EF validates that a schema's table may be mapped at most once per EntitySet.

This answer adds to what's already been said in previous answers and doesn't override any of those approaches, it builds upon them.

The model:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<Member> Members { get; set; }
    public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}

public class MemberCommentView
{
    public int MemberID { get; set; }
    public int CommentID { get; set; }
    public int Something { get; set; }
    public string SomethingElse { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }
}

The configuration:

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

public class MemberConfiguration : EntityTypeConfiguration<Member>
{
    public MemberConfiguration()
    {
        HasKey(x => x.MemberID);

        Property(x => x.MemberID).HasColumnType("int").IsRequired();
        Property(x => x.FirstName).HasColumnType("varchar(512)");
        Property(x => x.LastName).HasColumnType("varchar(512)")

        // configure many-to-many through internal EF EntitySet
        HasMany(s => s.Comments)
            .WithMany(c => c.Members)
            .Map(cs =>
            {
                cs.ToTable("MemberComment");
                cs.MapLeftKey("MemberID");
                cs.MapRightKey("CommentID");
            });
    }
}

public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
    public CommentConfiguration()
    {
        HasKey(x => x.CommentID);

        Property(x => x.CommentID).HasColumnType("int").IsRequired();
        Property(x => x.Message).HasColumnType("varchar(max)");
    }
}

public class MemberCommentViewConfiguration : EntityTypeConfiguration<MemberCommentView>
{
    public MemberCommentViewConfiguration()
    {
        ToTable("MemberCommentView");
        HasKey(x => new { x.MemberID, x.CommentID });

        Property(x => x.MemberID).HasColumnType("int").IsRequired();
        Property(x => x.CommentID).HasColumnType("int").IsRequired();
        Property(x => x.Something).HasColumnType("int");
        Property(x => x.SomethingElse).HasColumnType("varchar(max)");

        // configure one-to-many targeting the Join Table view
        // making all of its properties available
        HasRequired(a => a.Member).WithMany(b => b.MemberComments);
        HasRequired(a => a.Comment).WithMany(b => b.MemberComments);
    }
}

The context:

using System.Data.Entity;

public class MyContext : DbContext
{
    public DbSet<Member> Members { get; set; }
    public DbSet<Comment> Comments { get; set; }
    public DbSet<MemberCommentView> MemberComments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new MemberConfiguration());
        modelBuilder.Configurations.Add(new CommentConfiguration());
        modelBuilder.Configurations.Add(new MemberCommentViewConfiguration());

        OnModelCreatingPartial(modelBuilder);
     }
}

From Saluma's (@Saluma) answer

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

This still works...

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

...but could now also be...

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.Comments)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

This still works...

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

...but could now also be...

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        m.Comments
    })
        .ToList();

If you want to remove a comment from a member

var comment = ... // assume comment from member John Smith
var member = ... // assume member John Smith

member.Comments.Remove(comment);

If you want to Include() a member's comments

var member = context.Members
    .Where(m => m.FirstName == "John", m.LastName == "Smith")
    .Include(m => m.Comments);

This all feels like syntactic sugar, however it does get you a few perks if you're willing to go through the additional configuration. Either way you seem to be able to get the best of both approaches.

Programmatically scroll to a specific position in an Android ListView

Handling listView scrolling using UP/ Down using.button

If someone is interested in handling listView one row up/down using button. then.

public View.OnClickListener onChk = new View.OnClickListener() {
             public void onClick(View v) {

                 int index = list.getFirstVisiblePosition();
                 getListView().smoothScrollToPosition(index+1); // For increment. 

}
});

How do you push a Git tag to a branch using a refspec?

For pushing a single tag: git push <reponame> <tagname>

For instance, git push production 1.0.0. Tags are not bound to branches, they are bound to commits.

When you want to have the tag's content in the master branch, do that locally on your machine. I would assume that you continued developing in your local master branch. Then just a git push origin master should suffice.

Replacing blank values (white space) with NaN in pandas

Simplest of all solutions:

df = df.replace(r'^\s+$', np.nan, regex=True)

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

jQuery or JavaScript auto click

You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.

To run code after the page has finished loading, use the $(document).ready callback:

$(document).ready(function(){
  $('#some-id').trigger('click');
});

Is there a Subversion command to reset the working copy?

Delete everything inside your local copy using:

rm -r your_local_svn_dir_path/*

And the revert everything recursively using the below command.

svn revert -R your_local_svn_dir_path

This is way faster than deleting the entire directory and then taking a fresh checkout, because the files are being restored from you local SVN meta data. It doesn't even need a network connection.

Add shadow to custom shape on Android

If you don't mind doing some custom drawing with the Canvas API, check out this answer about drop shadows. Here's a follow-up question to that one which fixes a problem in the original.

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

How do I read CSV data into a record array in NumPy?

This is the easiest way:

import csv
with open('testfile.csv', newline='') as csvfile:
    data = list(csv.reader(csvfile))

Now each entry in data is a record, represented as an array. So you have a 2D array. It saved me so much time.

How to format DateTime columns in DataGridView?

Published by Microsoft in Standard Date and Time Format Strings:

dataGrid.Columns[2].DefaultCellStyle.Format = "d"; // Short date

That should format the date according to the person's location settings.

This is part of Microsoft's larger collection of Formatting Types in .NET.

android: how to align image in the horizontal center of an imageview?

Your ImageView has the attribute wrap_content. I would think that the Image is centered inside the imageview but the imageview itself is not centered in the parentview. If you have only the imageview on the screen try match_parent instead of wrap_content. If you have more then one view in the layout you have to center the imageview.

What is the difference between pip and conda?

I may have found one further difference of a minor nature. I have my python environments under /usr rather than /home or whatever. In order to install to it, I would have to use sudo install pip. For me, the undesired side effect of sudo install pip was slightly different than what are widely reported elsewhere: after doing so, I had to run python with sudo in order to import any of the sudo-installed packages. I gave up on that and eventually found I could use sudo conda to install packages to an environment under /usr which then imported normally without needing sudo permission for python. I even used sudo conda to fix a broken pip rather than using sudo pip uninstall pip or sudo pip --upgrade install pip.

Adding a new value to an existing ENUM Type

Updating pg_enum works, as does the intermediary column trick highlighted above. One can also use USING magic to change the column's type directly:

CREATE TYPE test AS enum('a', 'b');
CREATE TABLE foo (bar test);
INSERT INTO foo VALUES ('a'), ('b');

ALTER TABLE foo ALTER COLUMN bar TYPE varchar;

DROP TYPE test;
CREATE TYPE test as enum('a', 'b', 'c');

ALTER TABLE foo ALTER COLUMN bar TYPE test
USING CASE
WHEN bar = ANY (enum_range(null::test)::varchar[])
THEN bar::test
WHEN bar = ANY ('{convert, these, values}'::varchar[])
THEN 'c'::test
ELSE NULL
END;

As long as you've no functions that explicitly require or return that enum, you're good. (pgsql will complain when you drop the type if there are.)

Also, note that PG9.1 is introducing an ALTER TYPE statement, which will work on enums:

http://developer.postgresql.org/pgdocs/postgres/release-9-1-alpha.html

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

The image below is from the article written by Erwin van der Valk:

image explaining MVC, MVP and MVVM - by Erwin Vandervalk

The article explains the differences and gives some code examples in C#

Make a VStack fill the width of the screen in SwiftUI

A good solution and without "contraptions" is the forgotten ZStack

ZStack(alignment: .top){
    Color.red
    VStack{
        Text("Hello World").font(.title)
        Text("Another").font(.body)
    }
}

Result:

enter image description here

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I solved this simply:

<div ng-repeat="Object in List | filter: (FilterObj.FilterProperty1 ? {'ObjectProperty1': FilterObj.FilterProperty1} : '') | filter:(FilterObj.FilterProperty2 ? {'ObjectProperty2': FilterObj.FilterProperty2} : '')">

How do you add a Dictionary of items into another Dictionary

Swift 3:

extension Dictionary {

    mutating func merge(with dictionary: Dictionary) {
        dictionary.forEach { updateValue($1, forKey: $0) }
    }

    func merged(with dictionary: Dictionary) -> Dictionary {
        var dict = self
        dict.merge(with: dictionary)
        return dict
    }
}

let a = ["a":"b"]
let b = ["1":"2"]
let c = a.merged(with: b)

print(c) //["a": "b", "1": "2"]

Get the closest number out of an array

All of the solutions are over-engineered.

It is as simple as:

const needle = 5;
const haystack = [1, 2, 3, 4, 5, 6, 7, 8, 9];

haystack.sort((a, b) => {
  return Math.abs(a - needle) - Math.abs(b - needle);
})[0];

// 5

How to import classes defined in __init__.py

Edit, since i misunderstood the question:

Just put the Helper class in __init__.py. Thats perfectly pythonic. It just feels strange coming from languages like Java.

Remove padding from columns in Bootstrap 3

Building up on Vitaliy Silin's answer. Covering not only cases where we do not want padding at all, but also cases where we have standard size paddings.

See the live conversion of this code to CSS on sassmeister.com

@mixin padding($side, $size) {
    $padding-size : 0;
    @if $size == 'xs' { $padding-size : 5px; }
    @else if $size == 's' { $padding-size : 10px; }
    @else if $size == 'm' { $padding-size : 15px; }
    @else if $size == 'l' { $padding-size : 20px; }

    @if $side == 'all' {
        .padding--#{$size} {
            padding: $padding-size !important;
        }
    } @else {
        .padding-#{$side}--#{$size} {
            padding-#{$side}: $padding-size !important;
        }
    }
}

$sides-list: all top right bottom left;
$sizes-list: none xs s m l;
@each $current-side in $sides-list {
  @each $current-size in $sizes-list {
    @include padding($current-side,$current-size);
  }
}

This then outputs:

.padding--none {
  padding: 0 !important;
}

.padding--xs {
  padding: 5px !important;
}

.padding--s {
  padding: 10px !important;
}

.padding--m {
  padding: 15px !important;
}

.padding--l {
  padding: 20px !important;
}

.padding-top--none {
  padding-top: 0 !important;
}

.padding-top--xs {
  padding-top: 5px !important;
}

.padding-top--s {
  padding-top: 10px !important;
}

.padding-top--m {
  padding-top: 15px !important;
}

.padding-top--l {
  padding-top: 20px !important;
}

.padding-right--none {
  padding-right: 0 !important;
}

.padding-right--xs {
  padding-right: 5px !important;
}

.padding-right--s {
  padding-right: 10px !important;
}

.padding-right--m {
  padding-right: 15px !important;
}

.padding-right--l {
  padding-right: 20px !important;
}

.padding-bottom--none {
  padding-bottom: 0 !important;
}

.padding-bottom--xs {
  padding-bottom: 5px !important;
}

.padding-bottom--s {
  padding-bottom: 10px !important;
}

.padding-bottom--m {
  padding-bottom: 15px !important;
}

.padding-bottom--l {
  padding-bottom: 20px !important;
}

.padding-left--none {
  padding-left: 0 !important;
}

.padding-left--xs {
  padding-left: 5px !important;
}

.padding-left--s {
  padding-left: 10px !important;
}

.padding-left--m {
  padding-left: 15px !important;
}

.padding-left--l {
  padding-left: 20px !important;
}

Group by with multiple columns using lambda

     class Element
        {
            public string Company;        
            public string TypeOfInvestment;
            public decimal Worth;
        }

   class Program
    {
        static void Main(string[] args)
        {
         List<Element> elements = new List<Element>()
            {
                new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
                new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
                new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
                new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
                new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
                new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
                new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
                new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
                new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
                new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
            };

            //Group by on multiple column in LINQ (Query Method)
            var query = from e in elements
                        group e by new{e.TypeOfInvestment,e.Company} into eg
                        select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};



            foreach (var item in query)
            {
                Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
            }


            //Group by on multiple column in LINQ (Lambda Method)
            var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
                               .Select(g =>
                                            new
                                            {
                                                company = g.Key.Company,
                                                TypeOfInvestment = g.Key.TypeOfInvestment,            
                                                Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
                                            }
                                      );
            foreach (var item in CompanyDetails)
            {
                Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
            }
            Console.ReadLine();

        }
    }

How to run vi on docker container?

Your container probably haven't installed it out of the box.

Run apt-get install vim in the terminal and you should be ready to go.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Personally I'd go with AJAX.

If you cannot switch to @Ajax... helpers, I suggest you to add a couple of properties in your model

public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }

Change your view to a strongly typed Model via

@using MyModel

Before returning the View, in case of successfull creation do something like

MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);

then in your view, add this

@{
   if (model.TriggerOnLoad) {
   <text>
   <script type="text/javascript">
     alert('@Model.TriggerOnLoadMessage');
   </script>
   </text>
   }
}

Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:

$(document).ready(function () {
   alert('@Model.TriggerOnLoadMessage');
});

Please remember to reset the Model properties upon successfully alert emission.

Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:

@Html.EditorFor (m => m.TriggerOnLoadMessage)

But in case you want to build up such a thing, maybe it's better to define your own C# class:

class ClientMessageNotification {
    public bool TriggerOnLoad { get; set; }
    public string TriggerOnLoadMessage { get; set: }
}

and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.

Multiple parameters in a List. How to create without a class?

As said by Scott Chamberlain(and several others), Tuples work best if you don't mind having immutable(ie read-only) objects.

If, like suggested by David, you want to reference the int by the string value, for example, you should use a dictionary

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);
Console.WriteLine(d["string"]);//prints 1

If, however, you want to store your elements mutably in a list, and don't want to use a dictionary-style referencing system, then your best bet(ie only real solution right now) would be to use KeyValuePair, which is essentially std::pair for C#:

var kvp=new KeyValuePair<int, string>(2, "a");
//kvp.Key=2 and a.Value="a";
kvp.Key = 3;//both key and
kvp.Value = "b";//value are mutable

Of course, this is stackable, so if you need a larger tuple(like if you needed 4 elements) you just stack it. Granted this gets ugly really fast:

     var quad=new KeyValuePair<KeyValuePair<int,string>, KeyValuePair<int,string>>
                (new KeyValuePair<int,string>(3,"a"),
                new KeyValuePair<int,string>(4,"b"));
//quad.Key.Key=3

So obviously if you were to do this, you should probably also define an auxiliary function.

My advice is that if your tuple contains more than 2 elements, define your own class. You could use a typedef-esque using statement like :

using quad = KeyValuePair<KeyValuePair<int,string>, KeyValuePair<int,string>>;

but that doesn't make your instantiations any easier. You'd probably spend a lot less time writing template parameters and more time on the non-boilerplate code if you go with a user-defined class when working with tuples of more than 2 elements

How can I divide two integers stored in variables in Python?

Use this line to get the division behavior you want:

from __future__ import division

Alternatively, you could use modulus:

if (a % b) == 0: #do something

random.seed(): What does it do?

All the other answers don't seem to explain the use of random.seed(). Here is a simple example (source):

import random
random.seed( 3 )
print "Random number with seed 3 : ", random.random() #will generate a random number 
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random()   # same random number as before

URL encode sees “&” (ampersand) as “&amp;” HTML entity

There is HTML and URI encodings. &amp; is & encoded in HTML while %26 is & in URI encoding.

So before URI encoding your string you might want to HTML decode and then URI encode it :)

var div = document.createElement('div');
div.innerHTML = '&amp;AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);

result %26AndOtherHTMLEncodedStuff

Hope this saves you some time

pip cannot install anything

I had the same issue with pip 1.5.6.

I just deleted the ~/.pip folder and it worked like a charm.

rm -r ~/.pip/

What's the best practice to "git clone" into an existing folder?

Usually I will clone the initial repository first, and then move everything in the existing folder to the initial repository. It works every time.

The advantage of this method is that you won't missing anything of the initial repository including README or .gitignore.

You can also use the command below to finish the steps:

$ git clone https://github.com/your_repo.git && mv existing_folder/* your_repo

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msgs) {
        //write your code hear which give error
        }
        }

new Thread(new Runnable() {
    @Override
    public void run() {
    handler.sendEmptyMessage(1);
        //this will call handleMessage function and hendal all error
    }
    }).start();

What is a smart pointer and when should I use one?

The existing answers are good but don't cover what to do when a smart pointer is not the (complete) answer to the problem you are trying to solve.

Among other things (explained well in other answers) using a smart pointer is a possible solution to How do we use a abstract class as a function return type? which has been marked as a duplicate of this question. However, the first question to ask if tempted to specify an abstract (or in fact, any) base class as a return type in C++ is "what do you really mean?". There is a good discussion (with further references) of idiomatic object oriented programming in C++ (and how this is different to other languages) in the documentation of the boost pointer container library. In summary, in C++ you have to think about ownership. Which smart pointers help you with, but are not the only solution, or always a complete solution (they don't give you polymorphic copy) and are not always a solution you want to expose in your interface (and a function return sounds an awful lot like an interface). It might be sufficient to return a reference, for example. But in all of these cases (smart pointer, pointer container or simply returning a reference) you have changed the return from a value to some form of reference. If you really needed copy you may need to add more boilerplate "idiom" or move beyond idiomatic (or otherwise) OOP in C++ to more generic polymorphism using libraries like Adobe Poly or Boost.TypeErasure.

logout and redirecting session in php

<?php

session_start();

session_unset();

session_destroy();

header("location:home.php");

exit();

?>

Reading a JSP variable from JavaScript

The cleanest way, as far as I know:

  1. add your JSP variable to an HTML element's data-* attribute
  2. then read this value via Javascript when required

My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.

The HTML part without JSP:

<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
    Here is your regular page main content
</body>

The HTML part when using JSP:

<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
    Here is your regular page main content
</body>

The javascript part (using jQuery for simplicity):

<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
    jQuery(function(){
        var valuePassedFromJSP = $("body").attr("data-customvalueone");
        var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");

        alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>

And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/

Resources:

android.os.NetworkOnMainThreadException with android 4.2

Write below code into your MainActivity file after setContentView(R.layout.activity_main);

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

And below import statement into your java file.

import android.os.StrictMode;

Sort a List of objects by multiple fields

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
    public int compare(GraduationCeremony o1, GraduationCeremony o2) {
        int value1 = o1.campus.compareTo(o2.campus);
        if (value1 == 0) {
            int value2 = o1.faculty.compareTo(o2.faculty);
            if (value2 == 0) {
                return o1.building.compareTo(o2.building);
            } else {
                return value2;
            }
        }
        return value1;
    }
}

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

Execute SQLite script

You want to feed the create.sql into sqlite3 from the shell, not from inside SQLite itself:

$ sqlite3 auction.db < create.sql

SQLite's version of SQL doesn't understand < for files, your shell does.

Composer: how can I install another dependency without updating old ones?

In my case, I had a repo with:

  • requirements A,B,C,D in .json
  • but only A,B,C in the .lock

In the meantime, A,B,C had newer versions with respect when the lock was generated.

For some reason, I deleted the "vendors" and wanted to do a composer install and failed with the message:

Warning: The lock file is not up to date with the latest changes in composer.json.
You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.

I tried to run the solution from Seldaek issuing a composer update vendorD/libraryD but composer insisted to update more things, so .lock had too changes seen my my git tool.

The solution I used was:

  1. Delete all the vendors dir.
  2. Temporarily remove the requirement VendorD/LibraryD from the .json.
  3. run composer install.
  4. Then delete the file .json and checkout it again from the repo (equivalent to re-adding the file, but avoiding potential whitespace changes).
  5. Then run Seldaek's solution composer update vendorD/libraryD

It did install the library, but in addition, git diff showed me that in the .lock only the new things were added without editing the other ones.

(Thnx Seldaek for the pointer ;) )

PHP 7: Missing VCRUNTIME140.dll

I had the same issue, I changed the ports, restarted the services but in vein, only worked for me when I updated the Microsoft Visual c++ filesFrom There yoy can modify MVC

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

The problem was that I needed to have both minGW and MSYS installed and added to PATH.

The problem is now fixed.

What is the difference between a data flow diagram and a flow chart?

Although my experience with DFD diagrams is limited I can tell you that a DFD shows you how the data moves (flows) between the various modules. Furthermore a DFD can be partitioned in levels, that is in the Initial Level you see the system (say, a System to Rent a Movie) as a whole (called the Context Level). That level could be broken down into another Level that contains activities (say, rent a movie, return a movie) and how the data flows into those activities (could be a name, number of days, whatever). Now you can make a sublevel for each activity detailing the many tasks or scenarios of those activities. And so on, so forth. Remember that the data is always passing between levels.

Now as for the flowchart just remember that a flowchart describes an algorithm!

python list in sql query as parameter

string.join the list values separated by commas, and use the format operator to form a query string.

myquery = "select name from studens where id in (%s)" % ",".join(map(str,mylist))

(Thanks, blair-conrad)

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

Add CSS class to a div in code behind

<div runat="server"> is mapped to a HtmlGenericControl. Try using BtnventCss.Attributes.Add("class", "hom_but_a");

How do I open an .exe from another C++ .exe?

Try this:

#include <windows.h>

int main ()

{
    system ("start notepad.exe") // As an example. Change [notepad] to any executable file //

    return 0 ;
}

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

Provide the :name option to add_index, e.g.:

add_index :studies,
  ["user_id", "university_id", "subject_name_id", "subject_type_id"], 
  unique: true,
  name: 'my_index'

If using the :index option on references in a create_table block, it takes the same options hash as add_index as its value:

t.references :long_name, index: { name: :my_index }

Why does the Google Play store say my Android app is incompatible with my own device?

If you're here in 2020 and you think the device receiving the error message should be compatible:

Several other major apps have run into this including Instagram (1B+ installs) and Clash of Clans (100M+ installs). It appears to be an issue with Google's Android operating system.

To fix the “your device is not compatible with this version” error message, try clearing the Google Play Store cache, and then data. Next, restart the Google Play Store and try installing the app again.

[https://support.getupside.com/hc/en-us/articles/226667067--Device-not-compatible-error-message-in-Google-Play-Store]

Here is a link to Google's official support page that you can link to your users on how to clear the cache: https://support.google.com/googleplay/answer/7513003

How to add /usr/local/bin in $PATH on Mac

export PATH=$PATH:/usr/local/git/bin:/usr/local/bin

One note: you don't need quotation marks here because it's on the right hand side of an assignment, but in general, and especially on Macs with their tradition of spacy pathnames, expansions like $PATH should be double-quoted as "$PATH".

Create random list of integers in Python

Firstly, you should use randrange(0,1000) or randint(0,999), not randint(0,1000). The upper limit of randint is inclusive.

For efficiently, randint is simply a wrapper of randrange which calls random, so you should just use random. Also, use xrange as the argument to sample, not range.

You could use

[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]

to generate 10,000 numbers in the range using sample 10 times.

(Of course this won't beat NumPy.)

$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop

$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]' 
100 loops, best of 3: 9.24 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop

$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
>   a = range(x)
>   shuffle(a)
>   return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop

$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop

But since you don't care about the distribution of numbers, why not just use:

range(1000)*(10000/1000)

?

How to concatenate string and int in C?

Strings are hard work in C.

#include <stdio.h>

int main()
{
   int i;
   char buf[12];

   for (i = 0; i < 100; i++) {
      snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
      printf("%s\n", buf); // outputs so you can see it
   }
}

The 12 is enough bytes to store the text "pre_", the text "_suff", a string of up to two characters ("99") and the NULL terminator that goes on the end of C string buffers.

This will tell you how to use snprintf, but I suggest a good C book!

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^\d{1,2}[\W_]?po$

\d defines a number and {1,2} means 1 or two of the expression before, \W defines a non word character.

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

How to make exe files from a node.js app?

Try disclose: https://github.com/pmq20/disclose

disclose essentially makes a self-extracting exe out of your Node.js project and Node.js interpreter with the following characteristics,

  1. No GUI. Pure CLI.
  2. No run-time dependencies
  3. Supports both Windows and Unix
  4. Runs slowly for the first time (extracting to a cache dir), then fast forever

Try node-compiler: https://github.com/pmq20/node-compiler

I have made a new project called node-compiler to compile your Node.js project into one single executable.

It is better than disclose in that it never runs slowly for the first time, since your source code is compiled together with Node.js interpreter, just like the standard Node.js libraries.

Additionally, it redirect file and directory requests transparently to the memory instead of to the file system at runtime. So that no source code is required to run the compiled product.

How it works: https://speakerdeck.com/pmq20/node-dot-js-compiler-compiling-your-node-dot-js-application-into-a-single-executable

Comparing with Similar Projects,

  • pkg(https://github.com/zeit/pkg): Pkg hacked fs.* API's dynamically in order to access in-package files, whereas Node.js Compiler leaves them alone and instead works on a deeper level via libsquash. Pkg uses JSON to store in-package files while Node.js Compiler uses the more sophisticated and widely used SquashFS as its data structure.

  • EncloseJS(http://enclosejs.com/): EncloseJS restricts access to in-package files to only five fs.* API's, whereas Node.js Compiler supports all fs.* API's. EncloseJS is proprietary licensed and charges money when used while Node.js Compiler is MIT-licensed and users are both free to use it and free to modify it.

  • Nexe(https://github.com/nexe/nexe): Nexe does not support dynamic require because of its use of browserify, whereas Node.js Compiler supports all kinds of require including require.resolve.

  • asar(https://github.com/electron/asar): Asar uses JSON to store files' information while Node.js Compiler uses SquashFS. Asar keeps the code archive and the executable separate while Node.js Compiler links all JavaScript source code together with the Node.js virtual machine and generates a single executable as the final product.

  • AppImage(http://appimage.org/): AppImage supports only Linux with a kernel that supports SquashFS, while Node.js Compiler supports all three platforms of Linux, macOS and Windows, meanwhile without any special feature requirements from the kernel.

How to cast the size_t to double or int C++

You can use Boost numeric_cast.

This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double.

Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t is greater than INT_MAX. If you want to detect it use numeric_cast or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.

What is Java String interning?

JLS

JLS 7 3.10.5 defines it and gives a practical example:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Example 3.10.5-1. String Literals

The program consisting of the compilation unit (§7.3):

package testPackage;
class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}
class Other { static String hello = "Hello"; }

and the compilation unit:

package other;
public class Other { public static String hello = "Hello"; }

produces the output:

true true true true false true

JVMS

JVMS 7 5.1 says says that interning is implemented magically and efficiently with a dedicated CONSTANT_String_info struct (unlike most other objects which have more generic representations):

A string literal is a reference to an instance of class String, and is derived from a CONSTANT_String_info structure (§4.4.3) in the binary representation of a class or interface. The CONSTANT_String_info structure gives the sequence of Unicode code points constituting the string literal.

The Java programming language requires that identical string literals (that is, literals that contain the same sequence of code points) must refer to the same instance of class String (JLS §3.10.5). In addition, if the method String.intern is called on any string, the result is a reference to the same class instance that would be returned if that string appeared as a literal. Thus, the following expression must have the value true:

("a" + "b" + "c").intern() == "abc"

To derive a string literal, the Java Virtual Machine examines the sequence of code points given by the CONSTANT_String_info structure.

  • If the method String.intern has previously been called on an instance of class String containing a sequence of Unicode code points identical to that given by the CONSTANT_String_info structure, then the result of string literal derivation is a reference to that same instance of class String.

  • Otherwise, a new instance of class String is created containing the sequence of Unicode code points given by the CONSTANT_String_info structure; a reference to that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked.

Bytecode

Let's decompile some OpenJDK 7 bytecode to see interning in action.

If we decompile:

public class StringPool {
    public static void main(String[] args) {
        String a = "abc";
        String b = "abc";
        String c = new String("abc");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a == c);
    }
}

we have on the constant pool:

#2 = String             #32   // abc
[...]
#32 = Utf8               abc

and main:

 0: ldc           #2          // String abc
 2: astore_1
 3: ldc           #2          // String abc
 5: astore_2
 6: new           #3          // class java/lang/String
 9: dup
10: ldc           #2          // String abc
12: invokespecial #4          // Method java/lang/String."<init>":(Ljava/lang/String;)V
15: astore_3
16: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_1
20: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
26: aload_2
27: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
30: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
33: aload_1
34: aload_3
35: if_acmpne     42
38: iconst_1
39: goto          43
42: iconst_0
43: invokevirtual #7          // Method java/io/PrintStream.println:(Z)V

Note how:

  • 0 and 3: the same ldc #2 constant is loaded (the literals)
  • 12: a new string instance is created (with #2 as argument)
  • 35: a and c are compared as regular objects with if_acmpne

The representation of constant strings is quite magic on the bytecode:

and the JVMS quote above seems to say that whenever the Utf8 pointed to is the same, then identical instances are loaded by ldc.

I have done similar tests for fields, and:

  • static final String s = "abc" points to the constant table through the ConstantValue Attribute
  • non-final fields don't have that attribute, but can still be initialized with ldc

Conclusion: there is direct bytecode support for the string pool, and the memory representation is efficient.

Bonus: compare that to the Integer pool, which does not have direct bytecode support (i.e. no CONSTANT_String_info analogue).

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

Python:Efficient way to check if dictionary is empty or not

This will do it:

while d:
    k, v = d.popitem()
    # now use k and v ...

A dictionary in boolean context is False if empty, True otherwise.

There is no "first" item in a dictionary, because dictionaries aren't ordered. But popitem will remove and return some item for you each time.

addEventListener, "change" and option selection

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

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

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

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

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

A live demo is here on JSfiddle.

How to return Json object from MVC controller to view

<script type="text/javascript">
jQuery(function () {
    var container = jQuery("\#content");
    jQuery(container)
     .kendoGrid({
         selectable: "single row",
         dataSource: new kendo.data.DataSource({
             transport: {
                 read: {
                     url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
                     dataType: "json",
                 },
             },
             batch: true,
         }),
         editable: "popup",
         columns: [
            { field: "Id", title: "Id", width: 250, hidden: true },
            { field: "Data", title: "Message Body", width: 100 },
           { field: "mobile", title: "Mobile Number", width: 100 },
         ]
     });
});

combining two data frames of different lengths

I think I have come up with a quite shorter solution.. Hope it helps someone.

cbind.na<-function(df1, df2){

  #Collect all unique rownames
  total.rownames<-union(x = rownames(x = df1),y = rownames(x=df2))

  #Create a new dataframe with rownames
  df<-data.frame(row.names = total.rownames)

  #Get absent rownames for both of the dataframe
  absent.names.1<-setdiff(x = rownames(df1),y = rownames(df))
  absent.names.2<-setdiff(x = rownames(df2),y = rownames(df))

  #Fill absents with NAs
  df1.fixed<-data.frame(row.names = absent.names.1,matrix(data = NA,nrow = length(absent.names.1),ncol=ncol(df1)))
  colnames(df1.fixed)<-colnames(df1)
  df1<-rbind(df1,df1.fixed)

  df2.fixed<-data.frame(row.names = absent.names.2,matrix(data = NA,nrow = length(absent.names.2),ncol=ncol(df2)))
  colnames(df2.fixed)<-colnames(df2)
  df2<-rbind(df2,df2.fixed)

  #Finally cbind into new dataframe
  df<-cbind(df,df1[rownames(df),],df2[rownames(df),])
  return(df)

}

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

For the same reason C# doesn't allow multiple inheritence but allows you to implement multiple interfaces.

The lesson learned from C++ w/ multiple inheritence was that it lead to more issues than it was worth.

An interface is a contract of things your class has to implement. You don't gain any functionality from the interface. Inheritence allows you to inherit the functionality of a parent class (and in multiple-inheritence, that can get extremely confusing).

Allowing multiple interfaces allows you to use Design Patterns (like Adapter) to solve the same types of issues you can solve using multiple inheritence, but in a much more reliable and predictable manner.

How to set a header for a HTTP GET request, and trigger file download?

i want to post my solution here which was done AngularJS, ASP.NET MVC. The code illustrates how to download file with authentication.

WebApi method along with helper class:

[RoutePrefix("filess")]
class FileController: ApiController
{
    [HttpGet]
    [Route("download-file")]
    [Authorize(Roles = "admin")]
    public HttpResponseMessage DownloadDocument([FromUri] int fileId)
    {
        var file = "someFile.docx"// asking storage service to get file path with id
        return Request.ReturnFile(file);
    }
}

static class DownloadFIleFromServerHelper
{
    public static HttpResponseMessage ReturnFile(this HttpRequestMessage request, string file)
    {
        var result = request.CreateResponse(HttpStatusCode.OK);

        result.Content = new StreamContent(new FileStream(file, FileMode.Open, FileAccess.Read));
        result.Content.Headers.Add("x-filename", Path.GetFileName(file)); // letters of header names will be lowercased anyway in JS.
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = Path.GetFileName(file)
        };

        return result;
    }
}

Web.config file changes to allow sending file name in custom header.

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
                <add name="Access-Control-Allow-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Expose-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Allow-Origin" value="*" />

Angular JS Service Part:

function proposalService($http, $cookies, config, FileSaver) {
        return {
                downloadDocument: downloadDocument
        };

    function downloadFile(documentId, errorCallback) {
    $http({
        url: config.apiUrl + "files/download-file?documentId=" + documentId,
        method: "GET",
        headers: {
            "Content-type": "application/json; charset=utf-8",
            "Authorization": "Bearer " + $cookies.get("api_key")
        },
        responseType: "arraybuffer"  
        })
    .success( function(data, status, headers) {
        var filename = headers()['x-filename'];

        var blob = new Blob([data], { type: "application/octet-binary" });
        FileSaver.saveAs(blob, filename);
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);
        errorCallback(data, status);
    });
};
};

Module dependency for FileUpload: angular-file-download (gulp install angular-file-download --save). Registration looks like below.

var app = angular.module('cool',
[
    ...
    require('angular-file-saver'),
])
. // other staff.

How do relative file paths work in Eclipse?

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

How to connect to a remote Windows machine to execute commands using python?

is it too late?

I personally agree with Beatrice Len, I used paramiko maybe is an extra step for windows, but I have an example project git hub, feel free to clone or ask me.

https://github.com/davcastroruiz/django-ssh-monitor

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

If you want to show user a dialogue with all browser list, so he can choose preferred, here is sample code:

private static final String HTTPS = "https://";
private static final String HTTP = "http://";

public static void openBrowser(final Context context, String url) {

     if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
            url = HTTP + url;
     }

     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
     context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)

}

PHP Get URL with Parameter

$_SERVER['PHP_SELF'] for the page name and $_GET['id'] for a specific parameter.

try print_r($_GET); to print out all the parameters.

for your request echo $_SERVER['PHP_SELF']."?id=".$_GET['id'];

return all the parameters echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];

How to check if a specific key is present in a hash or not?

You can always use Hash#key? to check if the key is present in a hash or not.

If not it will return you false

hash =  { one: 1, two:2 }

hash.key?(:one)
#=> true

hash.key?(:four)
#=> false

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

std::string + const char* results in another std::string. system does not take a std::string, and you cannot concatenate char*'s with the + operator. If you want to use the code this way you will need:

std::string name = "john";
std::string tmp = 
    "quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '" + 
    name + ".jpg'";
system(tmp.c_str());

See std::string operator+(const char*)

How to make readonly all inputs in some div in Angular2?

If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable().

How I can check whether a page is loaded completely or not in web driver?

Below is some code from my BasePageObject class for waits:

public void waitForPageLoadAndTitleContains(int timeout, String pageTitle) {
    WebDriverWait wait = new WebDriverWait(driver, timeout, 1000);
    wait.until(ExpectedConditions.titleContains(pageTitle));
}

public void waitForElementPresence(By locator, int seconds) {
    WebDriverWait wait = new WebDriverWait(driver, seconds);
    wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}

public void jsWaitForPageToLoad(int timeOutInSeconds) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String jsCommand = "return document.readyState";

    // Validate readyState before doing any waits
    if (js.executeScript(jsCommand).toString().equals("complete")) {
        return;
    }

    for (int i = 0; i < timeOutInSeconds; i++) {
        TimeManager.waitInSeconds(3);
        if (js.executeScript(jsCommand).toString().equals("complete")) {
            break;
        }
    }
}

   /**
     * Looks for a visible OR invisible element via the provided locator for up
     * to maxWaitTime. Returns as soon as the element is found.
     *
     * @param byLocator
     * @param maxWaitTime - In seconds
     * @return
     *
     */
    public WebElement findElementThatIsPresent(final By byLocator, int maxWaitTime) {
        if (driver == null) {
            nullDriverNullPointerExeption();
        }
        FluentWait<WebDriver> wait = new FluentWait<>(driver).withTimeout(maxWaitTime, java.util.concurrent.TimeUnit.SECONDS)
                .pollingEvery(200, java.util.concurrent.TimeUnit.MILLISECONDS);

        try {
            return wait.until((WebDriver webDriver) -> {
                List<WebElement> elems = driver.findElements(byLocator);
                if (elems.size() > 0) {
                    return elems.get(0);
                } else {
                    return null;
                }
            });
        } catch (Exception e) {
            return null;
        }
    }

Supporting methods:

     /**
     * Gets locator.
     *
     * @param fieldName
     * @return
     */
    public By getBy(String fieldName) {
        try {
            return new Annotations(this.getClass().getDeclaredField(fieldName)).buildBy();
        } catch (NoSuchFieldException e) {
            return null;
        }
    }

How to hide scrollbar in Firefox?

This is what I needed to disable scrollbars while preserving scroll in Firefox, Chrome and Edge in :

          @-moz-document url-prefix() { /* Disable scrollbar Firefox */
            html{
              scrollbar-width: none;
            }
          }
          body {
            margin: 0; /* remove default margin */
            scrollbar-width: none; /* Also needed to disable scrollbar Firefox */
            -ms-overflow-style: none;  /* Disable scrollbar IE 10+ */
            overflow-y: scroll;
          }
          body::-webkit-scrollbar {
            width: 0px;
            background: transparent; /* Disable scrollbar Chrome/Safari/Webkit */
          }

Unicode via CSS :before

The escaped hex reference of &#xf066; is \f066.

content: "\f066";

Checking if jquery is loaded using Javascript

You can just type window.jQuery in Console . If it return a function(e,n) ... Then it is confirmed that the jquery is loaded and working successfully.

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

How can I make a SQL temp table with primary key and auto-incrementing field?

You are just missing the words "primary key" as far as I can see to meet your specified objective.

For your other columns it's best to explicitly define whether they should be NULL or NOT NULL though so you are not relying on the ANSI_NULL_DFLT_ON setting.

CREATE TABLE #tmp
(
ID INT IDENTITY(1, 1) primary key ,
AssignedTo NVARCHAR(100),
AltBusinessSeverity NVARCHAR(100),
DefectCount int
);

insert into #tmp 
select 'user','high',5 union all
select 'user','med',4


select * from #tmp

How to get a list of sub-folders and their files, ordered by folder-names

Command to put list of all files and folders into a text file is as below:

Eg: dir /b /s | sort > ListOfFilesFolders.txt

How to check if type is Boolean

One more decision with es2015 arrow function

const isBoolean = val => typeof val === 'boolean';

How can I use regex to get all the characters after a specific character, e.g. comma (",")

You can try with the following:

new_string = your_string.split(',').pop().trim();

This is how it works:

  • split(',') creates an array made of the different parts of your_string

(e.g. if the string is "'SELECT___100E___7',24", the array would be ["'SELECT___100E___7'", "24"]).

  • pop() gets the last element of the array

(in the example, it would be "24").

This would already be enough, but in case there might be some spaces (not in the case of the OP, but more in general), we could have:

  • trim() that would remove the spaces around the string (in case it would be " 24 ", it would become simply "24")

It's a simple solution and surely easier than a regexp.

Angular - Set headers for every request

This is how I did for setting token with every request.

import { RequestOptions, BaseRequestOptions, RequestOptionsArgs } from '@angular/http';

export class CustomRequestOptions extends BaseRequestOptions {

    constructor() {
        super();
        this.headers.set('Content-Type', 'application/json');
    }
    merge(options?: RequestOptionsArgs): RequestOptions {
        const token = localStorage.getItem('token');
        const newOptions = super.merge(options);
        if (token) {
            newOptions.headers.set('Authorization', `Bearer ${token}`);
        }

        return newOptions;
    }
}

And register in app.module.ts

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [
        { provide: RequestOptions, useClass: CustomRequestOptions }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Application Installation Failed in Android Studio

Just do the following step...

Build>Clean Project

after that Run project again, this worked for me

Difference between app.use and app.get in express.js

Simply app.use means “Run this on ALL requests”
app.get means “Run this on a GET request, for the given URL”

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

How to show hidden divs on mouseover?

If the divs are hidden, they will never trigger the mouseover event.

You will have to listen to the event of some other unhidden element.

You can consider wrapping your hidden divs into container divs that remain visible, and then act on the mouseover event of these containers.

_x000D_
_x000D_
<div style="width: 80px; height: 20px; background-color: red;" _x000D_
        onmouseover="document.getElementById('div1').style.display = 'block';">_x000D_
   <div id="div1" style="display: none;">Text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You could also listen for the mouseout event if you want the div to disappear when the mouse leaves the container div:

onmouseout="document.getElementById('div1').style.display = 'none';"

Spring Boot without the web server

If you want to use one of the "Getting Started" templates from spring.io site, but you don't need any of the servlet-related stuff that comes with the "default" ("gs/spring-boot") template, you can try the scheduling-tasks template (whose pom* contains spring-boot-starter etc) instead:

https://spring.io/guides/gs/scheduling-tasks/

That gives you Spring Boot, and the app runs as a standalone (no servlets or spring-webmvc etc are included in the pom). Which is what you wanted (though you may need to add some JMS-specific stuff, as someone else points out already).

[* I'm using Maven, but assume that a Gradle build will work similarly].

Insert json file into mongodb

the following two ways work well:

C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs --file example2.json
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs < example2.json

if the collections are under a specific user, you can use -u -p --authenticationDatabase

How to get a cookie from an AJAX response?

xhr.getResponseHeader('Set-Cookie');

It won't work for me.

I use this

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
} 

success: function(output, status, xhr) {
    alert(getCookie("MyCookie"));
},

http://www.w3schools.com/js/js_cookies.asp

Strip out HTML and Special Characters

You can do it in one single line :) specially useful for GET or POST requests

$clear = preg_replace('/[^A-Za-z0-9\-]/', '', urldecode($_GET['id']));

python convert list to dictionary

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))

how to fix Cannot call sendRedirect() after the response has been committed?

you have already forwarded the response in catch block:

RequestDispatcher dd = request.getRequestDispatcher("error.jsp");

dd.forward(request, response);

so, you can not again call the :

response.sendRedirect("usertaskpage.jsp");

because it is already forwarded (committed).

So what you can do is: keep a string to assign where you need to forward the response.

    String page = "";
    try {

    } catch (Exception e) {
      page = "error.jsp";
    } finally {
      page = "usertaskpage.jsp";
    }

RequestDispatcher dd=request.getRequestDispatcher(page);
dd.forward(request, response);

Insert line at middle of file with Python?

Below is a slightly awkward solution for the special case in which you are creating the original file yourself and happen to know the insertion location (e.g. you know ahead of time that you will need to insert a line with an additional name before the third line, but won't know the name until after you've fetched and written the rest of the names). Reading, storing and then re-writing the entire contents of the file as described in other answers is, I think, more elegant than this option, but may be undesirable for large files.

You can leave a buffer of invisible null characters ('\0') at the insertion location to be overwritten later:

num_names = 1_000_000    # Enough data to make storing in a list unideal
max_len = 20             # The maximum allowed length of the inserted line
line_to_insert = 2       # The third line is at index 2 (0-based indexing)

with open(filename, 'w+') as file:
    for i in range(line_to_insert):
        name = get_name(i)                    # Returns 'Alfred' for i = 0, etc.
        file.write(F'{i + 1}. {name}\n')

    insert_position = file.tell()             # Position to jump back to for insertion
    file.write('\0' * max_len + '\n')         # Buffer will show up as a blank line

    for i in range(line_to_insert, num_names):
        name = get_name(i)
        file.write(F'{i + 2}. {name}\n')      # Line numbering now bumped up by 1.

# Later, once you have the name to insert...
with open(filename, 'r+') as file:            # Must use 'r+' to write to middle of file 
    file.seek(insert_position)                # Move stream to the insertion line
    name = get_bonus_name()                   # This lucky winner jumps up to 3rd place
    new_line = F'{line_to_insert + 1}. {name}'
    file.write(new_line[:max_len])            # Slice so you don't overwrite next line

Unfortunately there is no way to delete-without-replacement any excess null characters that did not get overwritten (or in general any characters anywhere in the middle of a file), unless you then re-write everything that follows. But the null characters will not affect how your file looks to a human (they have zero width).

What is a predicate in c#?

In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.

I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.

What to do with "Unexpected indent" in python?

There is a trick that always worked for me:

If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.

It happened to me when used vim, gedit or editors like that.

Try to use only 1 editor for your code.

How to set lifetime of session

The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.

For set the time life in php, you can use the function session_set_cookie_params, before the session_start:

session_set_cookie_params(3600,"/");
session_start();

For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.

But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.

You can have a Table "Sessions":

  • session_id int
  • session_hash varchar(20)
  • session_data text

And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:

On login:

setcookie('sessid', $sessionid, 604800);      // One week or seven days
setcookie('sesshash', $sessionhash, 604800);  // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function

If the user return:

if (isset($_COOKIE['sessid'])) {
    if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
        $_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
    } else {
        // Dont validate the hash, possible session falsification
    }
}

Obviously, save all session/cookies calls, before sending data.

How to stop C# console applications from closing automatically?

If you do not want the program to close even if a user presses anykey;

 while (true) {
      System.Console.ReadKey();                
 };//This wont stop app

To the power of in C?

Actually in C, you don't have an power operator. You will need to manually run a loop to get the result. Even the exp function just operates in that way only. But if you need to use that function, include the following header

#include <math.h>

then you can use pow().

Split List into Sublists with LINQ

If the list is of type system.collections.generic you can use the "CopyTo" method available to copy elements of your array to other sub arrays. You specify the start element and number of elements to copy.

You could also make 3 clones of your original list and use the "RemoveRange" on each list to shrink the list to the size you want.

Or just create a helper method to do it for you.

Getting the last n elements of a vector. Is there a better way than using the length() function?

You can do exactly the same thing in R with two more characters:

x <- 0:9
x[-5:-1]
[1] 5 6 7 8 9

or

x[-(1:5)]

Git status shows files as changed even though contents are the same

Here is how I fixed the problem on Linux while I cloned a project that was created on Windows:

on linux in order for things to work properly you have to have this setting: core.autocrlf=input

this is how to set it: git config --global core.autocrlf input

Then clone the project again from github.

JUnit tests pass in Eclipse but fail in Maven Surefire

I had a similar problem: JUnit tests failed in Maven Surefire but passed in Eclipse when I used JUnit library version 4.11.0 from SpringSource Bundle Repository. Particulary:

<dependency>
    <groupId>org.junit</groupId>
    <artifactId>com.springsource.org.junit</artifactId>
    <version>4.11.0</version>
</dependency>

Then I replaced it with following JUnit library version 4.11 and everything works fine.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
</dependency>

How to suppress "unused parameter" warnings in C?

Labelling the attribute is ideal way. MACRO leads to sometime confusion. and by using void(x),we are adding an overhead in processing.

If not using input argument, use

void foo(int __attribute__((unused))key)
{
}

If not using the variable defined inside the function

void foo(int key)
{
   int hash = 0;
   int bkt __attribute__((unused)) = 0;

   api_call(x, hash, bkt);
}

Now later using the hash variable for your logic but doesn’t need bkt. define bkt as unused, otherwise compiler says'bkt set bt not used".

NOTE: This is just to suppress the warning not for optimization.

How many characters in varchar(max)

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

varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

How to Parse a JSON Object In Android

JSONArray jsonArray = new JSONArray(yourJsonString);

for (int i = 0; i < jsonArray.length(); i++) {
     JSONObject obj1 = jsonArray.getJSONObject(i);
     JSONArray results = patient.getJSONArray("results");
     String indexForPhone =  patientProfile.getJSONObject(0).getString("indexForPhone"));
}

Change to JSONArray, then convert to JSONObject.

What is a daemon thread in Java?

Daemon thread is like daemon process which is responsible for managing resources,a daemon thread is created by the Java VM to serve the user threads. example updating system for unix,unix is daemon process. child of daemon thread is always daemon thread,so by default daemon is false.you can check thread as daemon or user by using "isDaemon()" method. so daemon thread or daemon process are basically responsible for managing resources. for example when you starting jvm there is garbage collector running that is daemon thread whose priority is 1 that is lowest,which is managing memory. jvm is alive as long as user thread is alive,u can not kill daemon thread.jvm is responsible to kill daemon threads.

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

I'm posting a new answer to this because I ran into this error and had to use a different solution that I think is specific to iOS 9.

I had to explicitly disable the Enable Bitcode in Build Settings, which is automatically turned on in the update.

Referenced answer: New warnings in iOS 9