Programs & Examples On #Missing features

Threading pool similar to the multiprocessing Pool?

The overhead of creating the new processes is minimal, especially when it's just 4 of them. I doubt this is a performance hot spot of your application. Keep it simple, optimize where you have to and where profiling results point to.

Function overloading in Python: Missing

You can pass a mutable container datatype into a function, and it can contain anything you want.

If you need a different functionality, name the functions differently, or if you need the same interface, just write an interface function (or method) that calls the functions appropriately based on the data received.

It took a while to me to get adjusted to this coming from Java, but it really isn't a "big handicap".

Check existence of directory and create if doesn't exist

I know this question was asked a while ago, but in case useful, the here package is really helpful for not having to reference specific file paths and making code more portable. It will automatically define your working directory as the one that your .Rproj file resides in, so the following will often suffice without having to define the file path to your working directory:

library(here)

if (!dir.exists(here(outputDir))) {dir.create(here(outputDir))}

how to check if string contains '+' character

[+]is simpler

    String s = "ddjdjdj+kfkfkf";

    if(s.contains ("+"))
    {
        String parts[] = s.split("[+]");
        s =  parts[0]; // i want to strip part after  +
    }
    System.out.println(s);

How do you check that a number is NaN in JavaScript?

While @chiborg 's answer IS correct, there is more to it that should be noted:

parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true

Point being, if you're using this method for validation of input, the result will be rather liberal.

So, yes you can use parseFloat(string) (or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.

twitter bootstrap text-center when in xs mode

html

<div class="text-lg-right text-center">
  center in xs and right in lg devices
</div>

Linker Error C++ "undefined reference "

Your header file Hash.h declares "what class hash should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp. By including the header in your main file, the compiler is informed of the description of class Hash when compiling the file, but not how class Hash actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)) cannot be found.

The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:

g++ -o main Hash.cpp main.cpp

will create the main program called "main".

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

using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
    sw.WriteLine(message);
}

How to get current user who's accessing an ASP.NET application?

The quick answer is User = System.Web.HttpContext.Current.User

Ensure your web.config has the following authentication element.

<configuration>
    <system.web>
        <authentication mode="Windows" />
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</configuration>

Further Reading: Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

What is the difference between single-quoted and double-quoted strings in PHP?

A single-quoted string does not have variables within it interpreted. A double-quoted string does.

Also, a double-quoted string can contain apostrophes without backslashes, while a single-quoted string can contain unescaped quotation marks.

The single-quoted strings are faster at runtime because they do not need to be parsed.

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

Look for GSpread.NET. You can work with Google Spreadsheets by using API from Microsoft Excel. You don't need to rewrite old code with the new Google API usage. Just add a few row:

Set objExcel = CreateObject("GSpreadCOM.Application");

app.MailLogon(Name, ClientIdAndSecret, ScriptId);

It's an OpenSource project and it doesn't require Office to be installed.

The documentation available over here http://scand.com/products/gspread/index.html

Manually put files to Android emulator SD card

Use the adb tool that comes with the SDK.

adb push myDirectory /sdcard/targetDir

If you only specify /sdcard/ (with the trailing slash) as destination, then the CONTENTS of myDirectory will end up in the root of /sdcard.

Best way to convert text files between character sets?

My favorite tool for this is Jedit (a java based text editor) which has two very convenient features :

  • One which enables the user to reload a text with a different encoding (and, as such, to control visually the result)
  • Another one which enables the user to explicitly choose the encoding (and end of line char) before saving

HTML entity for check mark

Something like this?

if so, type the HTML &#10004;

And &#10003; gives a lighter one:

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

How can we programmatically detect which iOS version is device running on?

Best current version, without need to deal with numeric search within NSString is to define macros (See original answer: Check iPhone iOS Version)

Those macros do exist in github, see: https://github.com/carlj/CJAMacros/blob/master/CJAMacros/CJAMacros.h

Like this:

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

and use them like this:

if (SYSTEM_VERSION_LESS_THAN(@"5.0")) {
    // code here
}

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
    // code here
}

Outdated version below

to get OS version:

[[UIDevice currentDevice] systemVersion]

returns string, which can be turned into int/float via

-[NSString floatValue]
-[NSString intValue]

like this

Both values (floatValue, intValue) will be stripped due to its type, 5.0.1 will become 5.0 or 5 (float or int), for comparing precisely, you will have to separate it to array of INTs check accepted answer here: Check iPhone iOS Version

NSString *ver = [[UIDevice currentDevice] systemVersion];
int ver_int = [ver intValue];
float ver_float = [ver floatValue];

and compare like this

NSLog(@"System Version is %@",[[UIDevice currentDevice] systemVersion]);
NSString *ver = [[UIDevice currentDevice] systemVersion];
float ver_float = [ver floatValue];
if (ver_float < 5.0) return false;

For Swift 4.0 syntax

below example is just checking if the device is of iOS11 or greater version.

let systemVersion = UIDevice.current.systemVersion
if systemVersion.cgFloatValue >= 11.0 {
    //"for ios 11"
  }
else{
   //"ios below 11")
  }

Apache is downloading php files instead of displaying them

When i upgraded from PHP 7.2 to PHP 7.4, i also got same issue. Worked by doing following:-

  1. In [domain].conf file, commented following:

    php_admin_value engine Off
    

    And Added:

    AddType  application/x-httpd-php-source  .phps
    AddType text/html .php
    
  2. Disable mod 7.2 and enable 7.4 by following:

    a2dismod php7.2
    a2enmod php7.4
    
  3. In /etc/apache2/mods-enabled/php7.4.conf file, comment following:

    SetHandler application/x-httpd-php
    php_admin_flag engine Off
    

Which to use <div class="name"> or <div id="name">?

The object itself will not change. The main difference between these 2 keyword is the use:

  • The ID is usually single in the page
  • The class can have one or many occurences

In the CSS or Javascript files:

  • The ID will be accessed by the character #
  • The class will be accessed by the character .

Unique random string generation

  • not sure Microsoft's link are randomly generated
  • have a look to new Guid().ToString()

How should I unit test multithreaded code?

The following article suggests 2 solutions. Wrapping a semaphore (CountDownLatch) and adds functionality like externalize data from internal thread. Another way of achieving this purpose is to use Thread Pool (see Points of Interest).

Sprinkler - Advanced synchronization object

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

How to concatenate items in a list to a single string?

Edit from the future: Please don't use this, this function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.

Although @Burhan Khalid's answer is good, I think it's more understandable like this:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

The second argument to join() is optional and defaults to " ".

CSS set li indent

Also try:

ul {
  list-style-position: inside;
}

How can I call a method in Objective-C?

To send an objective-c message in this instance you would do

[self score];

I suggest you read the Objective-C programming guide Objective-C Programming Guide

How do I break out of nested loops in Java?

It's fairly easy to use label, You can break the outer loop from inner loop using the label, Consider the example below,

public class Breaking{
    public static void main(String[] args) {
        outerscope:
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (condition) {
                    break outerscope;
                }
            }
        }
    }
}

Another approach is to use the breaking variable/flag to keep track of required break. consider the following example.

public class Breaking{ 
    public static void main(String[] args) {
        boolean isBreaking = false;
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (condition) {
                    isBreaking = true;
                    break;
                }
            }
            if(isBreaking){
                break;
            }
        }
    }
}

However, I prefer using the first approach.

How does Java deal with multiple conditions inside a single IF statement

Yes,that is called short-circuiting.

Please take a look at this wikipedia page on short-circuiting

Android/Eclipse: how can I add an image in the res/drawable folder?

You can just put it in on the file system. Eclipse will pick up the change on the next refresh. Click the folder and press F5 to refresh. BTW, make sure the file name does not have any capital letters... it will break android... and eclipse will let you know.

recursion versus iteration

Yes, as said by Thanakron Tandavas,

Recursion is good when you are solving a problem that can be solved by divide and conquer technique.

For example: Towers of Hanoi

  1. N rings in increasing size
  2. 3 poles
  3. Rings start stacked on pole 1. Goal is to move rings so that they are stacked on pole 3 ...But
    • Can only move one ring at a time.
    • Can’t put larger ring on top of smaller.
  4. Iterative solution is “powerful yet ugly”; recursive solution is “elegant”.

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

you can add the selected values in an array and set it as the value for default selection

eg:

var selectedItems =[];
selectedItems.push("your selected items");
..
$('#drp_Books_Ill_Illustrations').select2('val',selectedItems );

Try this, this should definitely work!

Testing Private method using mockito

Think about this in terms of behaviour, not in terms of what methods there are. The method called method has a particular behaviour if b is true. It has different behaviour if b is false. This means you should write two different tests for method; one for each case. So instead of having three method-oriented tests (one for method, one for method1, one for method2, you have two behaviour-oriented tests.

Related to this (I suggested this in another SO thread recently, and got called a four-letter word as a result, so feel free to take this with a grain of salt); I find it helpful to choose test names that reflect the behaviour that I'm testing, rather than the name of the method. So don't call your tests testMethod(), testMethod1(), testMethod2() and so forth. I like names like calculatedPriceIsBasePricePlusTax() or taxIsExcludedWhenExcludeIsTrue() that indicate what behaviour I'm testing; then within each test method, test only the indicated behaviour. Most such behaviours will involve just one call to a public method, but may involve many calls to private methods.

Hope this helps.

Variable name as a string in Javascript

Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.

_x000D_
_x000D_
var obj = { myFirstName: 'John' };_x000D_
obj.foo = 'Another name';_x000D_
for(key in obj)_x000D_
    console.log(key + ': ' + obj[key]);
_x000D_
_x000D_
_x000D_

Count Vowels in String Python

...

vowels = "aioue"
text = input("Please enter your text: ")
count = 0

for i in text:
    if i in vowels:
        count += 1

print("There are", count, "vowels in your text")

...

Textarea to resize based on content length

A jquery solution has been implemented, and source code is available in github at: https://github.com/jackmoore/autosize .

Updating .class file in jar

This tutorial details how to update a jar file

jar -uf jar-file <optional_folder_structure>/input-file(s)     

where 'u' means update.

javascript regex - look behind alternative?

^(?!filename).+\.js works for me

tested against:

  • test.js match
  • blabla.js match
  • filename.js no match

A proper explanation for this regex can be found at Regular expression to match string not containing a word?

Look ahead is available since version 1.5 of javascript and is supported by all major browsers

Updated to match filename2.js and 2filename.js but not filename.js

(^(?!filename\.js$).).+\.js

Adding rows to dataset

To add rows to existing DataTable in Dataset:

DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);

In HTML5, should the main navigation be inside or outside the <header> element?

It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.

The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?

Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.

Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.

CSS 100% height with padding/margin

This is one of the outright idiocies of CSS - I have yet to understand the reasoning (if someone knows, pls. explain).

100% means 100% of the container height - to which any margins, borders and padding are added. So it is effectively impossible to get a container which fills it's parent and which has a margin, border, or padding.

Note also, setting height is notoriously inconsistent between browsers, too.


Another thing I've learned since I posted this is that the percentage is relative the container's length, that is, it's width, making a percentage even more worthless for height.

Nowadays, the vh and vw viewport units are more useful, but still not especially useful for anything other than the top-level containers.

How to redirect output to a file and stdout

Using tail -f output should work.

What's the difference between align-content and align-items?

align-content

align-content controls the cross-axis (i.e. vertical direction if the flex-direction is row, and horizontal if the flex-direction is column) positioning of multiple lines relative to each other.

(Think lines of a paragraph being vertically spread out, stacked toward the top, stacked toward the bottom. This is under a flex-direction row paradigm).

align-items

align-items controls the cross-axis of an individual line of flex elements.

(Think how an individual line of a paragraph is aligned, if it contains some normal text and some taller text like math equations. In that case, will it be the bottom, top, or center of each type of text in a line that will be aligned?)

is python capable of running on multiple cores?

Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.

Where is SQL Server Management Studio 2012?

Late answer but could be of use to other readers

Although SQL Server Management Studio installation is user friendly (more or less) people still seem to bump into different issues. There are lots of tutorials and instructions online, and I personally followed the ones found in this article: http://www.sqlshack.com/sql-server-management-studio-step-step-installation-guide/

It explains installing a standalone SSMS, but you can also install SSMS along with SQL Server – just make sure that you have selected Management Tools in the Feature selection screen.

I also recommend reading a step-by-step tutorial on installing SSMS 2008 Express after Visual Studio 2010 which can be found here: http://blogs.msdn.com/b/bethmassi/archive/2011/02/18/step-by-step-installing-sql-server-management-studio-2008-express-after-visual-studio-2010.aspx

It can help if you’ve just installed Visual Studio 2010 but also want to install SQL Server Management Studio.

How to check if current thread is not main thread

Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

Configuring Git over SSH to login once

I think there are two different things here. The first one is that normal SSH authentication requires the user to put the account's password (where the account password will be authenticated against different methods, depending on the sshd configuration).

You can avoid putting that password using certificates. With certificates you still have to put a password, but this time is the password of your private key (that's independent of the account's password).

To do this you can follow the instructions pointed out by steveth45:

With Public Key Authentication.

If you want to avoid putting the certificate's password every time then you can use ssh-agent, as pointed out by DigitalRoss

The exact way you do this depends on Unix vs Windows, but essentially you need to run ssh-agent in the background when you log in, and then the first time you log in, run ssh-add to give the agent your passphrase. All ssh-family commands will then consult the agent and automatically pick up your passphrase.

Start here: man ssh-agent.

The only problem of ssh-agent is that, on *nix at least, you have to put the certificates password on every new shell. And then the certificate is "loaded" and you can use it to authenticate against an ssh server without putting any kind of password. But this is on that particular shell.

With keychain you can do the same thing as ssh-agent but "system-wide". Once you turn on your computer, you open a shell and put the password of the certificate. And then, every other shell will use that "loaded" certificate and your password will never be asked again until you restart your PC.

Gnome has a similar application, called Gnome Keyring that asks for your certificate's password the first time you use it and then it stores it securely so you won't be asked again.

Convert a string to integer with decimal in Python

What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:

s = '234.67'
i = int(round(float(s)))

Otherwise, just do:

s = '234.67'
i = int(float(s))

Check if any type of files exist in a directory using BATCH script

You can use this

@echo off
for /F %%i in ('dir /b "c:\test directory\*.*"') do (
   echo Folder is NON empty
   goto :EOF
)
echo Folder is empty or does not exist

Taken from here.

That should do what you need.

Which exception should I raise on bad/illegal argument combinations in Python?

I would inherit from ValueError

class IllegalArgumentError(ValueError):
    pass

It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.

If you need to catch that specific error, it is helpful to have a name.

Flask - Calling python function on button OnClick event

It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.

I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.

With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:

from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/forward/", methods=['POST'])
def move_forward():
    #Moving forward code
    forward_message = "Moving Forward..."
    return render_template('index.html', forward_message=forward_message);

Then in your html, use this:

<form action="/forward/" method="post">
    <button name="forwardBtn" type="submit">Forward</button>
</form>

...To execute your moving forward code. And include this:

{{ forward_message }} 

... where you want the moving forward message to appear on your template.

This will cause your page to reload, which is inevitable without using AJAX and Javascript.

How do I uninstall a Windows service if the files do not exist anymore?

You can uninstall your windows service by command prompt also just write this piece of command

cd\                                                                   

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319(or version in which you developed your service)                                           

installutil c:\\xxx.exe(physical path of your service) -d

Spring security CORS Filter

Class WebMvcConfigurerAdapter is deprecated as of 5.0 WebMvcConfigurer has default methods and can be implemented directly without the need for this adapter. For this case:

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:3000");
    }
}

See also: Same-Site flag for session cookie

currently unable to handle this request HTTP ERROR 500

Your site is serving a 500 Internal Server Error. This can be caused by a number of things, such as:

  • File Permissions
  • Fatal Code Errors
  • Web Server Issues

EDIT

As you have highlighted it is a permission issue. You need to ensure that your files are executable by the web server user

Please see below article for some guidance on proper file permissions. https://www.digitalocean.com/community/questions/proper-permissions-for-web-server-s-directory

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

Reading a List from properties file and load with spring annotation @Value

if using property placeholders then ser1702544 example would become

@Value("#{myConfigProperties['myproperty'].trim().replaceAll(\"\\s*(?=,)|(?<=,)\\s*\", \"\").split(',')}") 

With placeholder xml:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
    <property name="properties" ref="myConfigProperties" />
    <property name="placeholderPrefix"><value>$myConfigProperties{</value></property>
</bean>    

<bean id="myConfigProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
     <property name="locations">
         <list>
                <value>classpath:myprops.properties</value>
         </list>
     </property>
</bean> 

Is there a Pattern Matching Utility like GREP in Windows?

TL;DR: ripgrep

Since 2009, a lot happened. Rust delivered many CLI utilities, among them ripgrep. It is advertised as a recursively searches directories for a regex pattern, supports Windows, MacOSX and Linux.

It is fast. Look at this performance comparison with similar tools. It also has many explanations on the design of the tool. Quite informative and geeky. =)

Supports a wide range of features that the POSIX grep tools support. Look at the comparison by ack author here.

If you have Scoop, you can install it with scoop install ripgrep. Else head over to the installation section of the doc.

Multiple commands in an alias for bash

Does this not work?

alias whatever='gnome-screensaver ; gnome-screensaver-command --lock'

How to select <td> of the <table> with javascript?

var t = document.getElementById("table"),
    d = t.getElementsByTagName("tr"),
    r = d.getElementsByTagName("td");

needs to be:

var t = document.getElementById("table"),
    tableRows = t.getElementsByTagName("tr"),
    r = [], i, len, tds, j, jlen;

for ( i =0, len = tableRows.length; i<len; i++) {
    tds = tableRows[i].getElementsByTagName('td');
    for( j = 0, jlen = tds.length; j < jlen; j++) {
        r.push(tds[j]);
    }
}

Because getElementsByTagName returns a NodeList an Array-like structure. So you need to loop through the return nodes and then populate you r like above.

How does lock work exactly?

The performance impact depends on the way you lock. You can find a good list of optimizations here: http://www.thinkingparallel.com/2007/07/31/10-ways-to-reduce-lock-contention-in-threaded-programs/

Basically you should try to lock as little as possible, since it puts your waiting code to sleep. If you have some heavy calculations or long lasting code (e.g. file upload) in a lock it results in a huge performance loss.

How to dynamically set bootstrap-datepicker's date value?

For Bootstrap 4

If you are using input group in Bootstrap, you need to attach the new date to parent of the textbox, otherwise if you click on the calendar icon and click outside the date will be cleared.

<div class="input-group date" id="my-date-component">
   <input type="text" />
    <div class="input-group-append">
      <span class="input-group-text"><i class="fa fa-calendar"></i></span>
    </div>
</div>

You need to set date to input-group.date.

$('#my-date-component').datepicker("update", new Date("01/10/2014"));

Also check datepicker update method

Android transparent status bar and actionbar

Just add these lines of code to your activity/fragment java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

Jquery Ajax Posting json to webservice

You mentioned using json2.js to stringify your data, but the POSTed data appears to be URLEncoded JSON You may have already seen it, but this post about the invalid JSON primitive covers why the JSON is being URLEncoded.

I'd advise against passing a raw, manually-serialized JSON string into your method. ASP.NET is going to automatically JSON deserialize the request's POST data, so if you're manually serializing and sending a JSON string to ASP.NET, you'll actually end up having to JSON serialize your JSON serialized string.

I'd suggest something more along these lines:

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
               { "position": "235.1944023323615", "markerPosition": "19" },
               { "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({
    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    error: function(errMsg) {
        alert(errMsg);
    }
});

The key to avoiding the invalid JSON primitive issue is to pass jQuery a JSON string for the data parameter, not a JavaScript object, so that jQuery doesn't attempt to URLEncode your data.

On the server-side, match your method's input parameters to the shape of the data you're passing in:

public class Marker
{
  public decimal position { get; set; }
  public int markerPosition { get; set; }
}

[WebMethod]
public string CreateMarkers(List<Marker> Markers)
{
  return "Received " + Markers.Count + " markers.";
}

You can also accept an array, like Marker[] Markers, if you prefer. The deserializer that ASMX ScriptServices uses (JavaScriptSerializer) is pretty flexible, and will do what it can to convert your input data into the server-side type you specify.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Get SELECT's value and text in jQuery

$('select').val()  // Get's the value

$('select option:selected').val() ; // Get's the value

$('select').find('option:selected').val() ; // Get's the value

$('select option:selected').text()  // Gets you the text of the selected option

Check FIDDLE

How to use OpenCV SimpleBlobDetector

// creation 
            cv::SimpleBlobDetector * blob_detector; 
            blob_detector = new SimpleBlobDetector(); 
            blob_detector->create("SimpleBlobDetector"); 
// change params - first move it to public!! 
            blob_detector->params.filterByArea = true; 
            blob_detector->params.minArea = 1; 
            blob_detector->params.maxArea = 32000; 
// or read / write them with file 
            FileStorage fs("test_fs.yml", FileStorage::WRITE); 
            FileNode fn = fs["features"]; 

            //blob_detector->read(fn); 
// detect 
            vector<KeyPoint> keypoints; 
            blob_detector->detect(img_text, keypoints); 
            fs.release(); 

I do know why, but params are protected. So I moved it in file features2d.hpp to be public:

  virtual void read( const FileNode& fn ); 
  virtual void write( FileStorage& fs ) const; 

public: 
Params params; 




protected: 
struct CV_EXPORTS Center 
  { 
      Point2d loc 

If you will not do this, the only way to change params is to create file (FileStorage fs("test_fs.yml", FileStorage::WRITE);), than open it in notepad, and edit. Or maybe there is another way, but I`m not aware of it.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

......../info/refs?service=git-upload-pack not found: did you run git update-server-info on the server?

For me the issue was a password issue. I run Keychain and deleted Github passwords. I run the pull command after that and it asked me for username and password. After that it worked ok.

Combining two expressions (Expression<Func<T, bool>>)

I combined some beautiful answers here to make it possible to easily support more Expression operators.

This is based on the answer of @Dejan but now it's quite easy to add the OR as well. I chose not to make the Combine function public, but you could do that to be even more flexible.

public static class ExpressionExtensions
{
    public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> leftExpression,
        Expression<Func<T, bool>> rightExpression) =>
        Combine(leftExpression, rightExpression, Expression.AndAlso);

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> leftExpression,
        Expression<Func<T, bool>> rightExpression) =>
        Combine(leftExpression, rightExpression, Expression.Or);

    public static Expression<Func<T, bool>> Combine<T>(Expression<Func<T, bool>> leftExpression, Expression<Func<T, bool>> rightExpression, Func<Expression, Expression, BinaryExpression> combineOperator)
    {
        var leftParameter = leftExpression.Parameters[0];
        var rightParameter = rightExpression.Parameters[0];

        var visitor = new ReplaceParameterVisitor(rightParameter, leftParameter);

        var leftBody = leftExpression.Body;
        var rightBody = visitor.Visit(rightExpression.Body);

        return Expression.Lambda<Func<T, bool>>(combineOperator(leftBody, rightBody), leftParameter);
    }

    private class ReplaceParameterVisitor : ExpressionVisitor
    {
        private readonly ParameterExpression _oldParameter;
        private readonly ParameterExpression _newParameter;

        public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
        {
            _oldParameter = oldParameter;
            _newParameter = newParameter;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            return ReferenceEquals(node, _oldParameter) ? _newParameter : base.VisitParameter(node);
        }
    }
}

Usage is not changed and still like this:

Expression<Func<Result, bool>> noFilterExpression = item => filters == null;

Expression<Func<Result, bool>> laptopFilterExpression = item => item.x == ...
Expression<Func<Result, bool>> dateFilterExpression = item => item.y == ...

var combinedFilterExpression = noFilterExpression.Or(laptopFilterExpression.AndAlso(dateFilterExpression));
    
efQuery.Where(combinedFilterExpression);

(This is an example based on my actual code, but read is as pseudo-code)

android - How to get view from context?

first use this:

LayoutInflater inflater = (LayoutInflater) Read_file.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Read file is current activity in which you want your context.

View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));

then you can use this to find any element in layout.

ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);

Composer: Command Not Found

Step 1 : Open Your terminal

Step 2 : Run bellow command

          curl -sS https://getcomposer.org/installer | php

Step 3 : After installation run bellow command

          sudo mv composer.phar /usr/local/bin/

Step 4 : Open bash_profile file create alias follow bellow steps

           vim ~/.bash_profile

Step 5 : Add bellow line in bash_profile file

          alias composer="php /usr/local/bin/composer.phar"

Step 6 : Close your terminal and reopen your terminal and run bellow command composer

How to show row number in Access query like ROW_NUMBER in SQL

One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:

SELECT a.ID, 
       a.AText, 
       (SELECT Count(ID) 
        FROM table1 b WHERE b.ID <= a.ID 
        AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;

Getting a list of files in a directory with a glob

Swift 5

This works for cocoa

        let bundleRoot = Bundle.main.bundlePath
        let manager = FileManager.default
        let dirEnum = manager.enumerator(atPath: bundleRoot)


        while let filename = dirEnum?.nextObject() as? String {
            if filename.hasSuffix(".data"){
                print("Files in resource folder: \(filename)")
            }
        }

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

builder for HashMap

Here is a very simple one ...

public class FluentHashMap<K, V> extends java.util.HashMap<K, V> {
  public FluentHashMap<K, V> with(K key, V value) {
    put(key, value);
    return this;
  }

  public static <K, V> FluentHashMap<K, V> map(K key, V value) {
    return new FluentHashMap<K, V>().with(key, value);
  }
}

then

import static FluentHashMap.map;

HashMap<String, Integer> m = map("a", 1).with("b", 2);

See https://gist.github.com/culmat/a3bcc646fa4401641ac6eb01f3719065

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

That only works for numbers less than 1.

select to_char(12.34, '0D99') from dual;
-- Result: #####

This won't work.

You could do something like this but this results in leading whitespaces:

select to_char(12.34, '999990D99') from dual;
-- Result: '     12,34'

Ultimately, you could add a TRIM to get rid of the whitespaces again but I wouldn't consider that a proper solution either...

select trim(to_char(12.34, '999990D99')) from dual;
-- Result: 12,34

Again, this will only work for numbers with 6 digits max.

Edit: I wanted to add this as a comment on DCookie's suggestion but I can't.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Code for WebTestPlugIn

public class Protocols : WebTestPlugin
{

    public override void PreRequest(object sender, PreRequestEventArgs e)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    }

}

How to create Custom Ratings bar in Android

You can create custom material rating bar by defining drawable xml using material icon of your choice and then applying custom drawable to rating bar using progressDrawable attribute.

For infomration about customizing rating bar see http://www.zoftino.com/android-ratingbar-and-custom-ratingbar-example

Below drawable xml uses thumbs up icon for rating bar.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlNormal" />
    </item>
    <item android:id="@android:id/secondaryProgress">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlActivated" />
    </item>
    <item android:id="@android:id/progress">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlActivated" />
    </item>
</layer-list>

Remove git mapping in Visual Studio 2015

Connect to a different repository (I tried with a TFS repository), then go to Manage Connections, right click the Git repository and you might be able to remove it.

But you still have to manually remove the .git folder and files from your project path before opening the solution again.

Nested JSON: How to add (push) new items to an object?

You can achieve this using Lodash _.assign function.

library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });

_x000D_
_x000D_
// This is my JSON object generated from a database_x000D_
var library = {_x000D_
  "Gold Rush": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["1.jpg", "", "2.jpg"]_x000D_
  },_x000D_
  "California": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["3.jpg", "4.jpg", "5.jpg"]_x000D_
  }_x000D_
}_x000D_
_x000D_
// These will be dynamically generated vars from editor_x000D_
var title = "Gold Rush";_x000D_
var foregrounds = ["Howdy", "Slide 2"];_x000D_
var backgrounds = ["1.jpg", ""];_x000D_
_x000D_
function save() {_x000D_
_x000D_
  // If title already exists, modify item_x000D_
  if (library[title]) {_x000D_
_x000D_
    // override one Object with the values of another (lodash)_x000D_
    library[title] = _.assign({}, {_x000D_
      'foregrounds': foregrounds_x000D_
    }, {_x000D_
      'backgrounds': backgrounds_x000D_
    });_x000D_
    console.log(library[title]);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    // console.log('Changes Saved to <b>' + title + '</b>');_x000D_
  }_x000D_
_x000D_
  // If title does not exist, add new item_x000D_
  else {_x000D_
    // Format it for the JSON object_x000D_
    var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');_x000D_
_x000D_
    // THE PROBLEM SEEMS TO BE HERE??_x000D_
    // Error: "Result of expression 'library.push' [undefined] is not a function"_x000D_
    library.push(item);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    console.log('Added: <b>' + title + '</b>');_x000D_
  }_x000D_
}_x000D_
_x000D_
save();
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

The Best Solution I found is below:

onSavedInstanceState(): always called inside fragment when activity is going to shut down(Move activity from one to another or config changes). So if we are calling multiple fragments on same activity then We have to use the following approach:

Use OnDestroyView() of the fragment and save the whole object inside that method. Then OnActivityCreated(): Check that if object is null or not(Because this method calls every time). Now restore state of an object here.

Its works always!

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Show/Hide Div on Scroll

$.fn.scrollEnd = function(callback, timeout) {          
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

$(window).scroll(function(){
    $('.main').fadeOut();
});

$(window).scrollEnd(function(){
    $('.main').fadeIn();
}, 700);

That should do the Trick!

Setting the correct PATH for Eclipse

Go to System Properties > Advanced > Enviroment Variables and look under System variables

First, create/set your JAVA_HOME variable

Even though Eclipse doesn't consult the JAVA_HOME variable, it's still a good idea to set it. See How do I run Eclipse? for more information.

If you have not created and/or do not see JAVA_HOME under the list of System variables, do the following:

  1. Click New... at the very bottom
  2. For Variable name, type JAVA_HOME exactly
  3. For Variable value, this could be different depending on what bits your computer and java are.
    • If both your computer and java are 64-bit, type C:\Program Files\Java\jdk1.8.0_60
    • If both your computer and java are 32-bit, type C:\Program Files\Java\jdk1.8.0_60
    • If your computer is 64-bit, but your java is 32-bit, type C:\Program Files (x86)\Java\jdk1.8.0_60

If you have created and/or do see JAVA_HOME, do the following:

  1. Click on the row under System variables that you see JAVA_HOME in
  2. Click Edit... at the very bottom
  3. For Variable value, change it to what was stated in #3 above based on java's and your computer's bits. To repeat:
    • If both your computer and java are 64-bit, change it to C:\Program Files\Java\jdk1.8.0_60
    • If both your computer and java are 32-bit, change it to C:\Program Files\Java\jdk1.8.0_60
    • If your computer is 64-bit, but your java is 32-bit, change it to C:\Program Files (x86)\Java\jdk1.8.0_60

Next, add to your PATH variable

  1. Click on the row under System variables with PATH in it
  2. Click Edit... at the very bottom
  3. If you have a newer version of windows:
    • Click New
    • Type in C:\Program Files (x86)\Java\jdk1.8.0_60 OR C:\Program Files\Java\jdk1.8.0_60 depending on the bits of your computer and java (see above ^).
    • Press Enter and Click New again.
    • Type in C:\Program Files (x86)\Java\jdk1.8.0_60\jre OR C:\Program Files\Java\jdk1.8.0_60\jre depending on the bits of your computer and java (see above again ^).
    • Press Enter and press OK on all of the related windows
  4. If you have an older version of windows
    • In the Variable value textbox (or something similar) drag the cursor all the way to the very end
    • Add a semicolon (;) if there isn't one already
    • C:\Program Files (x86)\Java\jdk1.8.0_60 OR C:\Program Files\Java\jdk1.8.0_60
    • Add another semicolon (;)
    • C:\Program Files (x86)\Java\jdk1.8.0_60\jre OR C:\Program Files\Java\jdk1.8.0_60\jre

Changing eclipse.ini

  1. Find your eclipse.ini file and copy-paste it in the same directory (should be named eclipse(1).ini)
  2. Rename eclipse.ini to eclipse.ini.old just in case something goes wrong
  3. Rename eclipse(1).ini to eclipse.ini
  4. Open your newly-renamed eclipse.ini and replace all of it with this:

    -startup
    plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
    --launcher.library
    plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
    -product
    org.eclipse.epp.package.java.product
    --launcher.defaultAction
    openFile
    --launcher.XXMaxPermSize
    256M
    -showsplash
    org.eclipse.platform
    --launcher.XXMaxPermSize
    256m
    --launcher.defaultAction
    openFile
    -vm
    C:\Program Files\Java\jdk1.8.0_60\bin\javaw.exe
    -vmargs
    -Dosgi.requiredJavaVersion=1.5
    -Xms40m
    -Xmx1024m
    

XXMaxPermSize may be deprecated, so it might not work. If eclipse still does not launch, do the following:

  1. Delete the newer eclipse.ini
  2. Rename eclipse.ini.old to eclipse.ini
  3. Open command prompt
  4. type in eclipse -vm C:\Program Files (x86)\Java\jdk1.8.0_60\bin\javaw.exe

If the problem remains

Try updating your eclipse and java to the latest version. 8u60 (1.8.0_60) is not the latest version of java. Sometimes, the latest version of java doesn't work with older versions of eclipse and vice versa. Otherwise, leave a comment if you're still having problems. You could also try a fresh reinstallation of Java.

Correct way to use Modernizr to detect IE?

Well, after doing more research on this topic I ended up using following solution for targeting IE 10+. As IE10&11 are the only browsers which support the -ms-high-contrast media query, that is a good option without any JS:

@media screen and (-ms-high-contrast: active), screen and (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

Works perfectly.

Convert string to int if string is a number

Cast to long or cast to int, be aware of the following.

These functions are one of the view functions in Excel VBA that are depending on the system regional settings. So if you use a comma in your double like in some countries in Europe, you will experience an error in the US.

E.g., in european excel-version 0,5 will perform well with CDbl(), but in US-version it will result in 5. So I recommend to use the following alternative:

Public Function CastLong(var As Variant)

    ' replace , by .
    var = Replace(var, ",", ".")        

    Dim l As Long
    On Error Resume Next
    l = Round(Val(var))

    ' if error occurs, l will be 0
    CastLong = l

End Function

' similar function for cast-int, you can add minimum and maximum value if you like
' to prevent that value is too high or too low.
Public Function CastInt(var As Variant)

    ' replace , by .
    var = Replace(var, ",", ".")

    Dim i As Integer
    On Error Resume Next
    i = Round(Val(var))

    ' if error occurs, i will be 0
    CastInt = i

End Function

Of course you can also think of cases where people use commas and dots, e.g., three-thousand as 3,000.00. If you require functionality for these kind of cases, then you have to check for another solution.

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

How can I color a UIImage in Swift?

Swift 4.

Use this extension to create a solid colored image

extension UIImage {   

    public func coloredImage(color: UIColor) -> UIImage? {
        return coloredImage(color: color, size: CGSize(width: 1, height: 1))
    }

    public func coloredImage(color: UIColor, size: CGSize) -> UIImage? {

        UIGraphicsBeginImageContextWithOptions(size, false, 0)

        color.setFill()
        UIRectFill(CGRect(origin: CGPoint(), size: size))

        guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
        UIGraphicsEndImageContext()

        return image
    }
}

How to sort by dates excel?

For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.

How to determine whether a year is a leap year?

Your function doesn't return anything, so that's why when you use it with the print statement you get None. So either just call your function like this:

leapyr(1900)

or modify your function to return a value (by using the return statement), which then would be printed by your print statement.

Note: This does not address any possible problems you have with your leap year computation, but ANSWERS YOUR SPECIFIC QUESTION as to why you are getting None as a result of your function call in conjunction with your print.

Explanation:

Some short examples regarding the above:

def add2(n1, n2):
    print 'the result is:', n1 + n2  # prints but uses no *return* statement

def add2_New(n1, n2):
    return n1 + n2    # returns the result to caller

Now when I call them:

print add2(10, 5)

this gives:

the result is: 15
None

The first line comes form the print statement inside of add2(). The None from the print statement when I call the function add2() which does not have a return statement, causing the None to be printed. Incidentally, if I had just called the add2() function simply with (note, no print statement):

add2()

I would have just gotten the output of the print statement the result is: 15 without the None (which looks like what you are trying to do).

Compare this with:

print add2_New(10, 5)

which gives:

15

In this case the result is computed in the function add2_New() and no print statement, and returned to the caller who then prints it in turn.

Jquery function BEFORE form submission

You can do something like the following these days by referencing the "beforeSubmit" jquery form event. I'm disabling and enabling the submit button to avoid duplicate requests, submitting via ajax, returning a message that's a json array and displaying the information in a pNotify:

jQuery('body').on('beforeSubmit', "#formID", function() {
    $('.submitter').prop('disabled', true);
    var form = $('#formID');
    $.ajax({
        url    : form.attr('action'),
        type   : 'post',
        data   : form.serialize(),
        success: function (response)
        {
            response = jQuery.parseJSON(response);
            new PNotify({
                text: response.message,
                type: response.status,
                styling: 'bootstrap3',
                delay: 2000,
            });
            $('.submitter').prop('disabled', false);
        },
        error  : function ()
        {
            console.log('internal server error');
        }
    });
});

Vertically centering a div inside another div

I have been using the following solution since over a year, it works with IE 7 and 8 as well.

<style>
.outer {
    font-size: 0;
    width: 400px;
    height: 400px;
    background: orange;
    text-align: center;
    display: inline-block;
}

.outer .emptyDiv {
    height: 100%;
    background: orange;
    visibility: collapse;
}

.outer .inner {
    padding: 10px;
    background: red;
    font: bold 12px Arial;
}

.verticalCenter {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
}
</style>

<div class="outer">
    <div class="emptyDiv verticalCenter"></div>
    <div class="inner verticalCenter">
        <p>Line 1</p>
        <p>Line 2</p>
    </div>
</div>

How to enable bulk permission in SQL Server

USE Master GO

ALTER Server Role [bulkadmin] ADD MEMBER [username] GO Command failed even tried several command parameters

master..sp_addsrvrolemember @loginame = N'username', @rolename = N'bulkadmin' GO Command was successful..

Partly JSON unmarshal into a map in Go

This can be accomplished by Unmarshaling into a map[string]json.RawMessage.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

To further parse sendMsg, you could then do something like:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

For say, you can do the same thing and unmarshal into a string:

var str string
err = json.Unmarshal(objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/OrIjvqIsi4-

Running Python on Windows for Node.js dependencies

TL;DR Make a copy or alias of your python.exe with name python2.7.exe

My python 2.7 was installed as

D:\app\Python27\python.exe

I always got this error no matter how I set (and verified) PYTHON env variable:

gyp ERR! stack Error: Can't find Python executable "python2.7", you can set the PYTHON env variable.
gyp ERR! stack     at failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:103:14)

The reason for this was that in node-gyp's configure.js the python executable was resolved like:

var python = gyp.opts.python || process.env.PYTHON || 'python'

And it turned out that gyp.opts.python had value 'python2.7' thus overriding process.env.PYTHON.

I resolved this by creating an alias for python.exe executable with name node-gyp was looking for:

D:\app\Python27>mklink python2.7.exe python.exe

You need admin rights for this operation.

MySQL Trigger: Delete From Table AFTER DELETE

Why not set ON CASCADE DELETE on Foreign Key patron_info.pid?

batch file to copy files to another location?

Batch file to copy folder is easy.

xcopy /Y C:\Source\*.* C:\NewFolder

Save the above as a batch file, and get Windows to run it on start up.

To do the same thing when folder is updated is trickier, you'll need a program that monitors the folder every x time and check for changes. You can write the program in VB/Java/whatever then schedule it to run every 30mins.

Short rot13 function - Python

def rot13(s):
    lower_chars = ''.join(chr(c) for c in range (97,123)) #ASCII a-z
    upper_chars = ''.join(chr(c) for c in range (65,91)) #ASCII A-Z
    lower_encode = lower_chars[13:] + lower_chars[:13] #shift 13 bytes
    upper_encode = upper_chars[13:] + upper_chars[:13] #shift 13 bytes
    output = "" #outputstring
    for c in s:
        if c in lower_chars:
                output = output + lower_encode[lower_chars.find(c)]
        elif c in upper_chars:
            output = output + upper_encode[upper_chars.find(c)]
        else:
            output = output + c
    return output

Another solution with shifting. Maybe this code helps other people to understand rot13 better. Haven't tested it completely.

Check for null variable in Windows batch

To test for the existence of a command line paramater, use empty brackets:

IF [%1]==[] echo Value Missing

or

IF [%1] EQU [] echo Value Missing

The SS64 page on IF will help you here. Under "Does %1 exist?".

You can't set a positional parameter, so what you should do is do something like

SET MYVAR=%1

You can then re-set MYVAR based on its contents.

sql how to cast a select query

Yes you can do.

Syntax for CAST:

CAST ( expression AS data_type [ ( length ) ] )

For example:

CAST(MyColumn AS Varchar(10))

CAST in SELECT Statement:

Select CAST(MyColumn AS Varchar(10)) AS MyColumn
FROM MyTable

See for more information CAST and CONVERT (Transact-SQL)

How to change JAVA.HOME for Eclipse/ANT

Set environment variables

This is the part that I always forget. Because you’re installing Ant by hand, you also need to deal with setting environment variables by hand.

For Windows XP: To set environment variables on Windows XP, right click on My Computer and select Properties. Then go to the Advanced tab and click the Environment Variables button at the bottom.

For Windows 7: To set environment variables on Windows 7, right click on Computer and select Properties. Click on Advanced System Settings and click the Environment Variables button at the bottom.

The dialog for both Windows XP and Windows 7 is the same. Make sure you’re only working on system variables and not user variables.

The only environment variable that you absolutely need is JAVA_HOME, which tells Ant the location of your JRE. If you’ve installed the JDK, this is likely c:\Program Files\Java\jdk1.x.x\jre on Windows XP and c:\Program Files(x86)\Java\jdk1.x.x\jre on Windows 7. You’ll note that both have spaces in their paths, which causes a problem. You need to use the mangled name[3] instead of the complete name. So for Windows XP, use C:\Progra~1\Java\jdk1.x.x\jre and for Windows 7, use C:\Progra~2\Java\jdk1.6.0_26\jre if it’s installed in the Program Files(x86) folder (otherwise use the same as Windows XP).

That alone is enough to get Ant to work, but for convenience, it’s a good idea to add the Ant binary path to the PATH variable. This variable is a semicolon-delimited list of directories to search for executables. To be able to run ant in any directory, Windows needs to know both the location for the ant binary and for the java binary. You’ll need to add both of these to the end of the PATH variable. For Windows XP, you’ll likely add something like this:

;c:\java\ant\bin;C:\Progra~1\Java\jdk1.x.x\jre\bin

For Windows 7, it will look something like this:

;c:\java\ant\bin;C:\Progra~2\Java\jdk1.x.x\jre\bin

Done

Once you’ve done that and applied the changes, you’ll need to open a new command prompt to see if the variables are set properly. You should be able to simply run ant and see something like this:

Buildfile: build.xml does not exist!
Build failed

Find commit by hash SHA in Git

There are two ways to do this.

1. providing the SHA of the commit you want to see to git log

git log -p a2c25061

Where -p is short for patch

2. use git show

git show a2c25061

The output for both commands will be:

  • the commit
  • the author
  • the date
  • the commit message
  • the patch information

How to run Rake tasks from within Rake tasks?

task :build_all do
  [ :debug, :release ].each do |t|
    $build_type = t
    Rake::Task["build"].reenable
    Rake::Task["build"].invoke
  end
end

That should sort you out, just needed the same thing myself.

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my case I've used this:

var query = "select * from table where Id IN @Ids";
var result = conn.Query<MyEntity>(query, new { Ids = ids });

my variable "ids" in the second line is an IEnumerable of strings, also they can be integers I guess.

What is a CSRF token? What is its importance and how does it work?

Yes, the post data is safe. But the origin of that data is not. This way somebody can trick user with JS into logging in to your site, while browsing attacker's web page.

In order to prevent that, django will send a random key both in cookie, and form data. Then, when users POSTs, it will check if two keys are identical. In case where user is tricked, 3rd party website cannot get your site's cookies, thus causing auth error.

How can I create a copy of an object in Python?

Shallow copy with copy.copy()

#!/usr/bin/env python3

import copy

class C():
    def __init__(self):
        self.x = [1]
        self.y = [2]

# It copies.
c = C()
d = copy.copy(c)
d.x = [3]
assert c.x == [1]
assert d.x == [3]

# It's shallow.
c = C()
d = copy.copy(c)
d.x[0] = 3
assert c.x == [3]
assert d.x == [3]

Deep copy with copy.deepcopy()

#!/usr/bin/env python3
import copy
class C():
    def __init__(self):
        self.x = [1]
        self.y = [2]
c = C()
d = copy.deepcopy(c)
d.x[0] = 3
assert c.x == [1]
assert d.x == [3]

Documentation: https://docs.python.org/3/library/copy.html

Tested on Python 3.6.5.

Converting an int to a binary string representation in Java?

This can be expressed in pseudocode as:

while(n > 0):
    remainder = n%2;
    n = n/2;
    Insert remainder to front of a list or push onto a stack

Print list or stack

Check if object is a jQuery object

For those who want to know if an object is a jQuery object without having jQuery installed, the following snippet should do the work :

function isJQuery(obj) {
  // Each jquery object has a "jquery" attribute that contains the version of the lib.
  return typeof obj === "object" && obj && obj["jquery"];
}

How to set Internet options for Android emulator?

If someone have a Internet Permission in AndroidManifest and still have a problem with Internet Connection, maybe that will be helpful: Android - Fixing the no internet connection issue on emulator.

I followed steps from that website, and everything works for me. The most important:

  • Configuring the proxy server on the emulator
  • Incorrect DNS Used by the Emulator

That is my first post, so I hope it will be helpful.

reading from app.config file

ConfigurationSettings.AppSettings is obsolete, you should use ConfigurationManager.AppSettings instead (you will need to add a reference to System.Configuration)

int value = Int32.Parse(ConfigurationManager.AppSettings["StartingMonthColumn"]);

If you still have problems reading in your app settings then check that your app.config file is named correctly. Specifically, it should be named according to the executing assembly i.e. MyApp.exe.config, and should reside in the same directory as MyApp.exe.

Reading file using relative path in python project

For Python 3.4+:

import csv
from pathlib import Path

base_path = Path(__file__).parent
file_path = (base_path / "../data/test.csv").resolve()

with open(file_path) as f:
    test = [line for line in csv.reader(f)]

Matrix Transpose in Python

The "best" answer has already been submitted, but I thought I would add that you can use nested list comprehensions, as seen in the Python Tutorial.

Here is how you could get a transposed array:

def matrixTranspose( matrix ):
    if not matrix: return []
    return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]

How do I install an R package from source?

In addition, you can build the binary package using the --binary option.

R CMD build --binary RJSONIO_0.2-3.tar.gz

Scroll Element into View with Selenium

JAVA

Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".

Following import:

import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;

First you need get x y location the element.

//initialize element
WebElement element = driver.findElement(By.id("..."));

//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();

//scroll to x y 
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");

CardView not showing Shadow in Android L

My recyclerview was slow in loading so by reading the stackoverflow.com I changed hardwareAccelerated to "false" then the elevation is not showing in the device. The I changed back to true. It works for me.

If Browser is Internet Explorer: run an alternative script instead

This article is quite explanatory: http://msdn.microsoft.com/en-us/library/ms537509%28v=vs.85%29.aspx.

If your JS is unobtrusive, you can just use:

<![if !IE]>
   <script src...
<![endif]>

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

If you want to use default mailtrip.io you don't need to modify mail.php file.

  1. Create account on mailtrip.io
  2. Go to Inboxes > My Inbox > SMTP Settings > Integration Laravel
  3. Modify .env file and replace all nulls of correct credentials:
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
  1. Run:
php artisan config:cache

If you are using Gmail there is an instruction for Gmail: https://stackoverflow.com/a/64582540/7082164

AngularJS ng-class if-else expression

Use nested inline if-then statements (Ternary Operators)

<div ng-class=" ... ? 'class-1' : ( ... ? 'class-2' : 'class-3')">

for example :

<div ng-class="apt.name.length >= 15 ? 'col-md-12' : (apt.name.length >= 10 ? 'col-md-6' : 'col-md-4')">
    ...
</div>

And make sure it's readable by your colleagues :)

Multi-gradient shapes

You CAN do it using only xml shapes - just use layer-list AND negative padding like this:

    <layer-list>

        <item>
            <shape>
                <solid android:color="#ffffff" />

                <padding android:top="20dp" />
            </shape>
        </item>

        <item>
            <shape>
                <gradient android:endColor="#ffffff" android:startColor="#efefef" android:type="linear" android:angle="90" />

                <padding android:top="-20dp" />
            </shape>
        </item>

    </layer-list>

Loading DLLs at runtime in C#

foreach (var f in Directory.GetFiles(".", "*.dll"))
            Assembly.LoadFrom(f);

That loads all the DLLs present in your executable's folder.

In my case I was trying to use Reflection to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.

EDIT: I timed it, and it only seems to load them the first time.

Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
    stopwatch.Restart();
    foreach (var f in Directory.GetFiles(".", "*.dll"))
        Assembly.LoadFrom(f);
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
}

Output: 34 0 0 0

So one could potentially run that code before any Reflection searches just in case.

HTML text input allow only numeric input

This is the easy solution

Replace .price-input input.quantity with the class of your input feild

$(".price-input input.quantity").on("keypress keyup blur",function (event) {    
       $(this).val($(this).val().replace(/[^\d].+/, ""));
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });

Scrollbar without fixed height/Dynamic height with scrollbar

A quick, clean approach using very little JS and CSS padding: http://jsfiddle.net/benjamincharity/ZcTsT/14/

var headerHeight = $('#header').height(),
    footerHeight = $('#footer').height();

$('#content').css({
  'padding-top': headerHeight,
  'padding-bottom': footerHeight
});

How to initialize a List<T> to a given size (as opposed to capacity)?

Initializing the contents of a list like that isn't really what lists are for. Lists are designed to hold objects. If you want to map particular numbers to particular objects, consider using a key-value pair structure like a hash table or dictionary instead of a list.

Python conversion from binary string to hexadecimal

format(int(bits, 2), '0' + str(len(bits) / 4) + 'x')

Divide a number by 3 without using *, /, +, -, % operators

I think the right answer is:

Why would I not use a basic operator to do a basic operation?

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

for xcode 11.1which doesn't contain ipad pro iPad Pro (2nd Gen) 12.9" Display run this command in terminal

xcrun simctl create "iPad Pro (12.9-inch) (2nd generation)" "com.apple.CoreSimulator.SimDeviceType.iPad-Pro--12-9-inch---2nd-generation-" "com.apple.CoreSimulator.SimRuntime.iOS-13-1"

look here

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

Git vs Team Foundation Server

For me the major difference is all the ancilliary files that TFS will add to your solution (.vssscc) to 'support' TFS - we've had recent issues with these files ending up mapped to the wrong branch, which lead to some interesting debugging...

Remove characters from C# string

It seems that the shortest way is to combine LINQ and string.Concat:

var input = @"My name @is ,Wan.;'; Wan";
var chrs = new[] {'@', ',', '.', ';', '\''};
var result = string.Concat(input.Where(c => !chrs.Contains(c)));
// => result = "My name is Wan Wan" 

See the C# demo. Note that string.Concat is a shortcut to string.Join("", ...).

Note that using a regex to remove individual known chars is still possible to build dynamically, although it is believed that regex is slower. However, here is a way to build such a dynamic regex (where all you need is a character class):

var pattern = $"[{Regex.Escape(new string(chrs))}]+";
var result = Regex.Replace(input, pattern, string.Empty);

See another C# demo. The regex will look like [@,\.;']+ (matching one or more (+) consecutive occurrences of @, ,, ., ; or ' chars) where the dot does not have to be escaped, but Regex.Escape will be necessary to escape other chars that must be escaped, like \, ^, ] or - whose position inside the character class you cannot predict.

How to pause for specific amount of time? (Excel/VBA)

I usually use the Timer function to pause the application. Insert this code to yours

T0 = Timer
Do
    Delay = Timer - T0
Loop Until Delay >= 1 'Change this value to pause time for a certain amount of seconds

Styling multi-line conditions in 'if' statements?

Here's my very personal take: long conditions are (in my view) a code smell that suggests refactoring into a boolean-returning function/method. For example:

def is_action__required(...):
    return (cond1 == 'val1' and cond2 == 'val2'
            and cond3 == 'val3' and cond4 == 'val4')

Now, if I found a way to make multi-line conditions look good, I would probably find myself content with having them and skip the refactoring.

On the other hand, having them perturb my aesthetic sense acts as an incentive for refactoring.

My conclusion, therefore, is that multiple line conditions should look ugly and this is an incentive to avoid them.

How do I get the last day of a month?

From DateTimePicker:

First date:

DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);

Last date:

DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));

Selecting pandas column by location

The method .transpose() converts columns to rows and rows to column, hence you could even write

df.transpose().ix[3]

How to convert time milliseconds to hours, min, sec format in JavaScript?

Human-readable code for human-readable output and you can extend this to light years or nanoseconds or what have you very intuitively. Obviously you'd want to convert this to a function and re-use some of those intermediate modulo calls.

second = 1000 
minute = second * 60
hour = minute * 60 
day = hour * 24

test = 3 * day + 2 * hour + 11 * minute + 58 * second

console.log(Math.floor(test / day))
console.log(Math.floor(test % day / hour))
console.log(Math.floor(test % day % hour / minute))
console.log(Math.floor(test % day % hour % minute / second))

How can I get all a form's values that would be submitted without submitting

Depending on the type of input types you're using on your form, you should be able to grab them using standard jQuery expressions.

Example:

// change forms[0] to the form you're trying to collect elements from...  or remove it, if you need all of them
var input_elements = $("input, textarea", document.forms[0]);

Check out the documentation for jQuery expressions on their site for more info: http://docs.jquery.com/Core/jQuery#expressioncontext

Checking if a list is empty with LINQ

LINQ itself must be doing some serious optimization around the Count() method somehow.

Does this surprise you? I imagine that for IList implementations, Count simply reads the number of elements directly while Any has to query the IEnumerable.GetEnumerator method, create an instance and call MoveNext at least once.

/EDIT @Matt:

I can only assume that the Count() extension method for IEnumerable is doing something like this:

Yes, of course it does. This is what I meant. Actually, it uses ICollection instead of IList but the result is the same.

Call to undefined function mysql_query() with Login

You are mixing the deprecated mysql extension with mysqli.

Try something like:

$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);

What is aria-label and how should I use it?

In the example you give, you're perfectly right, you have to set the title attribute.

If the aria-label is one tool used by assistive technologies (like screen readers), it is not natively supported on browsers and has no effect on them. It won't be of any help to most of the people targetted by the WCAG (except screen reader users), for instance a person with intellectal disabilities.

The "X" is not sufficient enough to give information to the action led by the button (think about someone with no computer knowledge). It might mean "close", "delete", "cancel", "reduce", a strange cross, a doodle, nothing.

Despite the fact that the W3C seems to promote the aria-label rather that the title attribute here: http://www.w3.org/TR/2014/NOTE-WCAG20-TECHS-20140916/ARIA14 in a similar example, you can see that the technology support does not include standard browsers : http://www.w3.org/WAI/WCAG20/Techniques/ua-notes/aria#ARIA14

In fact aria-label, in this exact situation might be used to give more context to an action:

For instance, blind people do not perceive popups like those of us with good vision, it's like a change of context. "Back to the page" will be a more convenient alternative for a screen reader, when "Close" is more significant for someone with no screen reader.

  <button
      aria-label="Back to the page"
      title="Close" onclick="myDialog.close()">X</button>

Angular 2: How to write a for loop, not a foreach loop

you can use _.range([optional] start, end). It creates a new Minified list containing an interval of numbers from start (inclusive) until the end (exclusive). Here I am using lodash.js ._range() method.

Example:

CODE

var dayOfMonth = _.range(1,32);  // It creates a new list from 1 to 31.

//HTML Now, you can use it in For loop

<div *ngFor="let day of dayOfMonth">{{day}}</div>

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

what is numeric(18, 0) in sql server 2008 r2

This page explains it pretty well.

As a numeric the allowable range that can be stored in that field is -10^38 +1 to 10^38 - 1.

The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.

The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.

So the range that can be stored in this particular field is -(10^18 - 1) to (10^18 - 1)

Or -999999999999999999 to 999999999999999999 Integers only

How to implement a Keyword Search in MySQL?

You can find another simpler option in a thread here: Match Against.. with a more detail help in 11.9.2. Boolean Full-Text Searches

This is just in case someone need a more compact option. This will require to create an Index FULLTEXT in the table, which can be accomplish easily.

Information on how to create Indexes (MySQL): MySQL FULLTEXT Indexing and Searching

In the FULLTEXT Index you can have more than one column listed, the result would be an SQL Statement with an index named search:

SELECT *,MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*') as relevance  FROM `documents`USE INDEX(search) WHERE MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*' IN BOOLEAN MODE) ORDER BY relevance;

I tried with multiple columns, with no luck. Even though multiple columns are allowed in indexes, you still need an index for each column to use with Match/Against Statement.

Depending in your criterias you can use either options.

Laravel redirect back to original destination after login

You may use Redirect::intended function. It will redirect the user to the URL they were trying to access before being caught by the authenticaton filter. A fallback URI may be given to this method in case the intended destinaton is not available.

In post login/register:

return Redirect::intended('defaultpageafterlogin');

How to properly stop the Thread in Java?

Using Thread.interrupt() is a perfectly acceptable way of doing this. In fact, it's probably preferrable to a flag as suggested above. The reason being that if you're in an interruptable blocking call (like Thread.sleep or using java.nio Channel operations), you'll actually be able to break out of those right away.

If you use a flag, you have to wait for the blocking operation to finish and then you can check your flag. In some cases you have to do this anyway, such as using standard InputStream/OutputStream which are not interruptable.

In that case, when a thread is interrupted, it will not interrupt the IO, however, you can easily do this routinely in your code (and you should do this at strategic points where you can safely stop and cleanup)

if (Thread.currentThread().isInterrupted()) {
  // cleanup and stop execution
  // for example a break in a loop
}

Like I said, the main advantage to Thread.interrupt() is that you can immediately break out of interruptable calls, which you can't do with the flag approach.

Is there a GUI design app for the Tkinter / grid geometry?

You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.

On the other hand, you have PAGE that seems active and works in python 2.7 and py3k

As you indicate on your comment, none of these use the grid geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.

It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:

enter image description here

By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I found that useful, stabbing service function as sinon.stub().returns($q.when({})):

this.myService = {
   myFunction: sinon.stub().returns( $q.when( {} ) )
};

this.scope = $rootScope.$new();
this.angularStubs = {
    myService: this.myService,
    $scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );

controller:

this.someMethod = function(someObj) {
   myService.myFunction( someObj ).then( function() {
        someObj.loaded = 'bla-bla';
   }, function() {
        // failure
   } );   
};

and test

const obj = {
    field: 'value'
};
this.ctrl.someMethod( obj );

this.scope.$digest();

expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );

TypeError: 'list' object is not callable in python

Before you can fully understand what the error means and how to solve, it is important to understand what a built-in name is in Python.

What is a built-in name?

In Python, a built-in name is a name that the Python interpreter already has assigned a predefined value. The value can be either a function or class object. These names are always made available by default, no matter the scope. Some of the values assigned to these names represent fundamental types of the Python language, while others are simple useful.

As of the latest version of Python - 3.6.2 - there are currently 61 built-in names. A full list of the names and how they should be used, can be found in the documentation section Built-in Functions.

An important point to note however, is that Python will not stop you from re-assigning builtin names. Built-in names are not reserved, and Python allows them to be used as variable names as well.

Here is an example using the dict built-in:

>>> dict = {}
>>> dict
{}
>>>

As you can see, Python allowed us to assign the dict name, to reference a dictionary object.

What does "TypeError: 'list' object is not callable" mean?

To put it simply, the reason the error is occurring is because you re-assigned the builtin name list in the script:

list = [1, 2, 3, 4, 5]

When you did this, you overwrote the predefined value of the built-in name. This means you can no longer use the predefined value of list, which is a class object representing Python list.

Thus, when you tried to use the list class to create a new list from a range object:

myrange = list(range(1, 10))

Python raised an error. The reason the error says "'list' object is not callable", is because as said above, the name list was referring to a list object. So the above would be the equivalent of doing:

[1, 2, 3, 4, 5](range(1, 10))

Which of course makes no sense. You cannot call a list object.

How can I fix the error?

Suppose you have code such as the following:

list = [1, 2, 3, 4, 5]
myrange = list(range(1, 10))

for number in list:
    if number in myrange:
        print(number, 'is between 1 and 10')

Running the above code produces the following error:

Traceback (most recent call last):
  File "python", line 2, in <module>
TypeError: 'list' object is not callable

If you are getting a similar error such as the one above saying an "object is not callable", chances are you used a builtin name as a variable in your code. In this case and other cases the fix is as simple as renaming the offending variable. For example, to fix the above code, we could rename our list variable to ints:

ints = [1, 2, 3, 4, 5] # Rename "list" to "ints"
myrange = list(range(1, 10))

for number in ints: # Renamed "list" to "ints"
    if number in myrange:
        print(number, 'is between 1 and 10')

PEP8 - the official Python style guide - includes many recommendations on naming variables.

This is a very common error new and old Python users make. This is why it's important to always avoid using built-in names as variables such as str, dict, list, range, etc.

Many linters and IDEs will warn you when you attempt to use a built-in name as a variable. If your frequently make this mistake, it may be worth your time to invest in one of these programs.

I didn't rename a built-in name, but I'm still getting "TypeError: 'list' object is not callable". What gives?

Another common cause for the above error is attempting to index a list using parenthesis (()) rather than square brackets ([]). For example:

>>> lst = [1, 2]
>>> lst(0)

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    lst(0)
TypeError: 'list' object is not callable

For an explanation of the full problem and what can be done to fix it, see TypeError: 'list' object is not callable while trying to access a list.

Android custom dropdown/popup menu

Update: To create a popup menu in android with Kotlin refer my answer here.

To create a popup menu in android with Java:

Create a layout file activity_main.xml under res/layout directory which contains only one button.

Filename: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:paddingBottom="@dimen/activity_vertical_margin"  
    android:paddingLeft="@dimen/activity_horizontal_margin"  
    android:paddingRight="@dimen/activity_horizontal_margin"  
    android:paddingTop="@dimen/activity_vertical_margin"  
    tools:context=".MainActivity" >  

    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="62dp"  
        android:layout_marginTop="50dp"  
        android:text="Show Popup" />  

</RelativeLayout>  

Create a file popup_menu.xml under res/menu directory

It contains three items as shown below.

Filename: poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >  

    <item  
        android:id="@+id/one"  
        android:title="One"/>  

    <item  
        android:id="@+id/two"  
        android:title="Two"/>  

    <item  
        android:id="@+id/three"  
        android:title="Three"/>  

</menu>  

MainActivity class which displays the popup menu on button click.

Filename: MainActivity.java

public class MainActivity extends Activity {  
    private Button button1;  

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

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                PopupMenu popup = new PopupMenu(MainActivity.this, button1);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                    .inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                            MainActivity.this,
                            "You Clicked : " + item.getTitle(),
                            Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }
        }); //closing the setOnClickListener method
    }
}

To add programmatically:

PopupMenu menu = new PopupMenu(this, view);

menu.getMenu().add("One");
menu.getMenu().add("Two");
menu.getMenu().add("Three");

menu.show();

Follow this link for creating menu programmatically.

How do I set a program to launch at startup

Thanks to everyone for responding so fast. Joel, I used your option 2 and added a registry key to the "Run" folder of the current user. Here's the code I used for anyone else who's interested.

    using Microsoft.Win32;
    private void SetStartup()
    {
        RegistryKey rk = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        if (chkStartUp.Checked)
            rk.SetValue(AppName, Application.ExecutablePath);
        else
            rk.DeleteValue(AppName,false);            

    }

Drawing Circle with OpenGL

glBegin(GL_POLYGON);                        // Middle circle
double radius = 0.2;
double ori_x = 0.0;                         // the origin or center of circle
double ori_y = 0.0;
for (int i = 0; i <= 300; i++) {
    double angle = 2 * PI * i / 300;
    double x = cos(angle) * radius;
    double y = sin(angle) * radius;
    glVertex2d(ori_x + x, ori_y + y);
}
glEnd();

How to run or debug php on Visual Studio Code (VSCode)

The best solution for me was to add a key binding to run PHP code directly in the terminal

To do so you just need to download terminal-command-keys from VS code extensions marketplace:

enter image description here

Then got to File>Preferences>Keyboard Shortcuts and click on the following icon at the upper right corner:

enter image description here

It will open up the keybindings.json file

Add the following settings

[
    {
        "key": "ctrl+s",
        "command":"terminalCommandKeys.run",
        "when": "editorLangId == php",
        "args": {
            "cmd":"php ${file}",
            "newTerminal":true,
            "saveAllfiles": true,
            "showTerminal": true,
        }
    }
]

key is the shortcut to run your PHP file (I use ctrl+s) you can change it as you wish

when to run different commands for different file types (I set it for PHP files only) vscode's "when" clauses

See the full settings documentation from here

That's it, I hope it helps.

How can I use goto in Javascript?

To achieve goto-like functionality while keeping the call stack clean, I am using this method:

// in other languages:
// tag1:
// doSomething();
// tag2:
// doMoreThings();
// if (someCondition) goto tag1;
// if (otherCondition) goto tag2;

function tag1() {
    doSomething();
    setTimeout(tag2, 0); // optional, alternatively just tag2();
}

function tag2() {
    doMoreThings();
    if (someCondition) {
        setTimeout(tag1, 0); // those 2 lines
        return;              // imitate goto
    }
    if (otherCondition) {
        setTimeout(tag2, 0); // those 2 lines
        return;              // imitate goto
    }
    setTimeout(tag3, 0); // optional, alternatively just tag3();
}

// ...

Please note that this code is slow since the function calls are added to timeouts queue, which is evaluated later, in browser's update loop.

Please also note that you can pass arguments (using setTimeout(func, 0, arg1, args...) in browser newer than IE9, or setTimeout(function(){func(arg1, args...)}, 0) in older browsers.

AFAIK, you shouldn't ever run into a case that requires this method unless you need to pause a non-parallelable loop in an environment without async/await support.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

1) in a query window in SQL Server Management Studio, run the command:

SET SHOWPLAN_ALL ON

2) run your slow query

3) your query will not run, but the execution plan will be returned. store this output

4) run your fast version of the query

5) your query will not run, but the execution plan will be returned. store this output

6) compare the slow query version output to the fast query version output.

7) if you still don't know why one is slower, post both outputs in your question (edit it) and someone here can help from there.

INSERT INTO...SELECT for all MySQL columns

For the syntax, it looks like this (leave out the column list to implicitly mean "all")

INSERT INTO this_table_archive
SELECT *
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00'

For avoiding primary key errors if you already have data in the archive table

INSERT INTO this_table_archive
SELECT t.*
FROM this_table t
LEFT JOIN this_table_archive a on a.id=t.id
WHERE t.entry_date < '2011-01-01 00:00:00'
  AND a.id is null  # does not yet exist in archive

What is git tag, How to create tags & How to checkout git remote tag(s)

This is bit out of context but in case you are here because you want to tag a specific commit like i do

Here's a command to do that :-

Example:

git tag -a v1.0 7cceb02 -m "Your message here"

Where 7cceb02 is the beginning part of the commit id.

You can then push the tag using git push origin v1.0.

You can do git log to show all the commit id's in your current branch.

Using python map and other functional tools

The easiest way would be not to pass bars through the different functions, but to access it directly from maptest:

foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]

def maptest(foo):
    print foo, bars

map(maptest, foos)

With your original maptest function you could also use a lambda function in map:

map((lambda foo: maptest(foo, bars)), foos)

fetch in git doesn't get all branches

I had this issue today on a repo.

It wasn't the +refs/heads/*:refs/remotes/origin/* issue as per top solution.

Symptom was simply that git fetch origin or git fetch just didn't appear to do anything, although there were remote branches to fetch.

After trying lots of things, I removed the origin remote, and recreated it. That seems to have fixed it. Don't know why.

remove with: git remote rm origin

and recreate with: git remote add origin <git uri>

String.equals versus ==

It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.

Only right way is using .equals() -> datos[0].equals(usuario). == says only if two objects are the same instance of object (ie. have same memory address)

Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language

Change directory in Node.js command prompt

If you mean to change default directory for "Node.js command prompt", when you launch it, then (Windows case)

  1. go the directory where NodeJS was installed
  2. find file nodevars.bat
  3. open it with editor as administrator
  4. change the default path in the row which looks like

    if "%CD%\"=="%~dp0" cd /d "%HOMEDRIVE%%HOMEPATH%"
    

with your path. It could be for example

    if "%CD%\"=="%~dp0" cd /d "c://MyDirectory/"

if you mean to change directory once when you launched "Node.js command prompt", then execute the following command in the Node.js command prompt:

     cd c:/MyDirectory/

Best way to change font colour halfway through paragraph?

<span> will allow you to style text, but it adds no semantic content.

As you're emphasizing some text, it sounds like you'd be better served by wrapping the text in <em></em> and using CSS to change the color of the <em> element. For example:

CSS

.description {
  color: #fff;
}

.description em {
  color: #ffa500;
}

Markup

<p class="description">Lorem ipsum dolor sit amet, consectetur 
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat 
massa, <em>eget vulputate tellus fermentum.</em></p>

In fact, I'd go to great pains to avoid the <span> element, as it's completely meaningless to everything that doesn't render your style sheet (bots, screen readers, luddites who disable styles, parsers, etc.) or renders it in unexpected ways (personal style sheets). In many ways, it's no better than using the <font> element.

_x000D_
_x000D_
.description {_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.description em {_x000D_
  color: #ffa500;_x000D_
}
_x000D_
<p class="description">Lorem ipsum dolor sit amet, consectetur _x000D_
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat _x000D_
massa, <em>eget vulputate tellus fermentum.</em></p>
_x000D_
_x000D_
_x000D_

what is Promotional and Feature graphic in Android Market/Play Store?

Starting with Google Play 4.9, the app info display has been changed and the promo graphic is displayed at the top.

The promo graphic will be required soon.

The promo text has turned into a short description and is now shown on the main info page, before the user presses it to view the full description.

Automated testing for REST Api

One of the problems of doing automated testing for APIs is that many of the tools require you to have the API server up and running before you run your test suite. It can be a real advantage to have a unit testing framework that is capable of running and querying the APIs in a fully automated test environment.

An option that's good for APIs implemented with Node.JS / Express is to use mocha for automated testing. In addition to unit tests, its easy to write functional tests against the APIs, separated into different test suites. You can start up the API server automatically in the local test environment and set up a local test database. Using make, npm, and a build server, you can create a "make test" target and an incremental build that will run the entire test suite every time a piece of code is submitted to your repository. For the truly fastidious developer, it will even generate a nice HTML code-coverage report showing you which parts of your code base are covered by tests or not. If this sounds interesting, here's a blog post that provides all the technical details.

If you're not using node, then whatever the defacto unit testing framework for the language is (jUnit, cucumber/capybara, etc) - look at its support for spinning up servers in the local test environment and running the HTTP queries. If it's a large project, the effort to get automated API testing and continual integration working will pay off pretty quickly.

Hope that helps.

How can I read command line parameters from an R script?

Dirk's answer here is everything you need. Here's a minimal reproducible example.

I made two files: exmpl.bat and exmpl.R.

  • exmpl.bat:

    set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe"
    %R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1
    

    Alternatively, using Rterm.exe:

    set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe"
    %R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1
    
  • exmpl.R:

    options(echo=TRUE) # if you want see commands in output file
    args <- commandArgs(trailingOnly = TRUE)
    print(args)
    # trailingOnly=TRUE means that only your arguments are returned, check:
    # print(commandArgs(trailingOnly=FALSE))
    
    start_date <- as.Date(args[1])
    name <- args[2]
    n <- as.integer(args[3])
    rm(args)
    
    # Some computations:
    x <- rnorm(n)
    png(paste(name,".png",sep=""))
    plot(start_date+(1L:n), x)
    dev.off()
    
    summary(x)
    

Save both files in the same directory and start exmpl.bat. In the result you'll get:

  • example.png with some plot
  • exmpl.batch with all that was done

You could also add an environment variable %R_Script%:

"C:\Program Files\R-3.0.2\bin\RScript.exe"

and use it in your batch scripts as %R_Script% <filename.r> <arguments>

Differences between RScript and Rterm:

How do I find the location of Python module sources?

The sys.path list contains the list of directories which will be searched for modules at runtime:

python -v
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]

Parsing command-line arguments in C

It's a bit too big to include in a Stack Overflow answer, but I made a library for defining commands lines declaratively. It takes advantage of the the C++14 ability to build up a class constructor by giving initial values to each member variable.

The library is mostly a base class. To define your command syntax, you declare a struct that derives from it. Here's a sample:

struct MyCommandLine : public core::CommandLine {
    Argument<std::string> m_verb{this, "program", "program.exe",
        "this is what my program does"};
    Option<bool> m_help{this, "help", false,
        "displays information about the command line"};
    Alias<bool> alias_help{this, '?', &m_help};
    Option<bool> m_demo{this, "demo", false,
        "runs my program in demonstration mode"};
    Option<bool> m_maximize{this, "maximize", false,
        "opens the main window maximized"};
    Option<int> m_loops{this, "loops", 1,
        "specifies the number of times to repeat"};
    EnumOption<int> m_size{this, "size", 3,
                           { {"s", 1},
                             {"small", 1},
                             {"m", 3},
                             {"med", 3},
                             {"medium", 3},
                             {"l", 5},
                             {"large", 5} } };
    BeginOptionalArguments here{this};
    Argument<std::string> m_file{this, "file-name", "",
        "name of an existing file to open"};
} cl;

The Argument, Option, and Alias class templates are declared in the scope of the CommandLine base class, and you can specialize them for your own types. Each one takes the this pointer, the option name, the default value, and a description for use in printing the command synopsis/usage.

I'm still looking to eliminate the need to sprinkle all the this pointers in there, but I haven't found a way to do it without introducing macros. Those pointers allow each member to register itself with the tables in the base class that drive the parsing.

Once you have an instance, there are several overloads of a method to parse the input from a string or a main-style argument vector. The parser handles both Windows-style and Unix-style option syntax.

if (!cl.Parse(argc, argv)) {
    std::string message;
    for (const auto &error : cl.GetErrors()) {
        message += error + "\n";
    }
    std::cerr << message;
    exit(EXIT_FAILURE);
}

Once it's parsed, you can access the value of any of the options using operator():

if (cl.m_help()) { std::cout << cl.GetUsage(); }
for (int i = 0; i < cl.m_loops(); ++i) { ... }

The whole library is only about 300 lines (excluding tests). The instances are a bit bloaty, since the parsing tables are part of the instance (rather than the class). But you generally only need one instance per program, and the convenience of this purely declarative approach is pretty powerful, and an instance can be reset simply by parsing new input.

Equivalent VB keyword for 'break'

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

How do I create a master branch in a bare Git repository?

By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.

https://git-scm.com/docs

Simplest way to do a recursive self-join?

Check following to help the understand the concept of CTE recursion

DECLARE
@startDate DATETIME,
@endDate DATETIME

SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'

; WITH CTE AS (
    SELECT
        YEAR(@startDate) AS 'yr',
        MONTH(@startDate) AS 'mm',
        DATENAME(mm, @startDate) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        @startDate 'new_date'
    UNION ALL
    SELECT
        YEAR(new_date) AS 'yr',
        MONTH(new_date) AS 'mm',
        DATENAME(mm, new_date) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        DATEADD(d,1,new_date) 'new_date'
    FROM CTE
    WHERE new_date < @endDate
    )
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)

Why is C so fast, and why aren't other languages as fast or faster?

I know plenty of people have said it in a long winded way, but:

C is faster because it does less (for you).

md-table - How to update the column width

you can using fxFlex from "@angular/flex-layout" in th and td like this:

<ng-container matColumnDef="value">
      <th mat-header-cell fxFlex="15%" *matHeaderCellDef>Value</th>
            <td mat-cell *matCellDef="let element" fxFlex="15%" fxLayoutAlign="start center">
                           {{'value'}}
            </td>
       </th>
</ng-container>

Lock, mutex, semaphore... what's the difference?

Take a look at Multithreading Tutorial by John Kopplin.

In the section Synchronization Between Threads, he explain the differences among event, lock, mutex, semaphore, waitable timer

A mutex can be owned by only one thread at a time, enabling threads to coordinate mutually exclusive access to a shared resource

Critical section objects provide synchronization similar to that provided by mutex objects, except that critical section objects can be used only by the threads of a single process

Another difference between a mutex and a critical section is that if the critical section object is currently owned by another thread, EnterCriticalSection() waits indefinitely for ownership whereas WaitForSingleObject(), which is used with a mutex, allows you to specify a timeout

A semaphore maintains a count between zero and some maximum value, limiting the number of threads that are simultaneously accessing a shared resource.

Object reference not set to an instance of an object.

I know this was posted about a year ago, but this is for users for future reference.

I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.

while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.

if (email == null)
{     
     break;    
}
else
{    
     // your code here    
}

Laravel Eloquent limit and offset

You can use skip and take functions as below:

$products = $art->products->skip($offset*$limit)->take($limit)->get();

// skip should be passed param as integer value to skip the records and starting index

// take gets an integer value to get the no. of records after starting index defined by skip

EDIT

Sorry. I was misunderstood with your question. If you want something like pagination the forPage method will work for you. forPage method works for collections.

REf : https://laravel.com/docs/5.1/collections#method-forpage

e.g

$products = $art->products->forPage($page,$limit);

How to send cookies in a post request with the Python Requests library?

If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:

import requests
...


def application(environ, start_response):
    cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
    response_headers = [('Content-type', 'text/plain')]
    response_headers.append(('Set-Cookie',cookie))
...

    return [bytes(post_env),response_headers]

I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.

Oracle pl-sql escape character (for a " ' ")

you can use ESCAPE like given example below

The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL.

SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/';

The same works inside PL/SQL:

 if( id like '%/_%' ESCAPE '/' )

This applies only to like patterns, for example in an insert there is no need to escape _ or %, they are used as plain characters anyhow. In arbitrary strings only ' needs to be escaped by ''.

The difference between sys.stdout.write and print?

>>> sys.stdout.write(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1

Observing the example above:

  1. sys.stdout.write won't write non-string object, but print will

  2. sys.stdout.write won't add a new line symbol in the end, but print will

If we dive deeply,

sys.stdout is a file object which can be used for the output of print()

if file argument of print() is not specified, sys.stdout will be used

Why would we call cin.clear() and cin.ignore() after reading input?

Why do we use:

1) cin.ignore

2) cin.clear

?

Simply:

1) To ignore (extract and discard) values that we don't want on the stream

2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.

Long version:

If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)

Look at the example:

string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6

What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?

Run the program to see for yourself.

You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".

And "Wlodarczyk" is not shown. It seems like if it was gone (?)*

What happened? ;-)

Because there is a space between "Arkadiusz" and "Wlodarczyk".

"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.

The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.

So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;

Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).

It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...


All right all right. But how to fix it?!

Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)

I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)

After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"

You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.

Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?

Yes!

internal state of cin set to 4 is like an alarm that is howling and making noise.

cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".

All right let's do so! Let's use cin.clear().

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl; 
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl;  //new line is here :-)

We can surely see after executing above code that the state is equal to goodbit.

Great so the problem is solved?

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;; 
cin.clear(); 
cout << cin.rdstate() << endl; 
cin >> age;//new line is here :-)

Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.

WHY?!

Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.

You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)

So it's time for another tool:

cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.

So could we use it even before making the alarm goes off?

Yes:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;

The "Wlodarczyk" is gonna be removed before making the noise in line 7.

What is 10000 and '\n'?

It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.


So the main cause of problem is gone before noise was made...

Why do we need 'clear' then?

What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?

Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.

So we must use clear in case like that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

But should you clear the state 'just in case'?

Of course not.

If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.

So we can use conditional statement to check if the user put wrong type on the stream

int age;
if (cin >> age) //it's gonna return false if types doesn't match
    cout << "You put integer";
else
    cout << "You bad boy! it was supposed to be int";

All right so we can fix our initial problem like for example that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

int age;
cout << "Give me your age:" << endl;
if (cin >> age)
  cout << "Your age is equal to:" << endl;
else
{
 cin.clear();
 cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
 cout << "Give me your age name as string I dare you";
 cin >> age;
}

Of course this can be improved by for example doing what you did in question using loop while.

BONUS:

You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?

Sure, you can do it two ways:

1)

string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;

cout << "Hello, " << name << " " << surname << endl;

2) or by using getline function.

getline(cin, nameOfStringVariable);

and that's how to do it:

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

The second option might backfire you in case you use it after you use 'cin' before the getline.

Let's check it out:

a)

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

If you put "20" as age you won't be asked for nameAndSurname.

But if you do it that way:

b)

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll

everything is fine.

WHAT?!

Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.

b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.

a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.

So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.

So the proper code would be:

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n') 
cout << "Your age is" << age << endl;


string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

I hope streams are more clear to you know.

Hah silence me please! :-)

Use different Python version with virtualenv

Yes, the above answers are correct and works fine on Unix based systems like Linux & MAC OS X.

I tried to create virtualenv for Python2 & Python3 with the following commands.

Here I have used venv2 & venv3 as their names for Python2 & Python3 respectively.

Python2 »

MacBook-Pro-2:~ admin$ virtualenv venv2 --python=`which python2`
Running virtualenv with interpreter /usr/local/bin/python2
New python executable in /Users/admin/venv2/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ ls venv2/bin/
activate        easy_install        pip2.7          python2.7
activate.csh        easy_install-2.7    python          wheel
activate.fish       pip         python-config
activate_this.py    pip2            python2
MacBook-Pro-2:~ admin$ 

Python3 »

MacBook-Pro-2:~ admin$ virtualenv venv3 --python=`which python3`
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/admin/venv3/bin/python3
Also creating executable in /Users/admin/venv3/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ ls venv3/bin/
activate        easy_install        pip3.6          python3.6
activate.csh        easy_install-3.6    python          wheel
activate.fish       pip         python-config
activate_this.py    pip3            python3
MacBook-Pro-2:~ admin$ 

Checking Python installation locations

MacBook-Pro-2:~ admin$ which python2
/usr/local/bin/python2
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ which python3
/usr/local/bin/python3
MacBook-Pro-2:~ admin$ 

Convert hex string to int

you may use like that

System.out.println(Integer.decode("0x4d2"))    // output 1234
//and vice versa 
System.out.println(Integer.toHexString(1234); //  output is 4d2);

Getting A File's Mime Type In Java

Apache Tika offers in tika-core a mime type detection based based on magic markers in the stream prefix. tika-core does not fetch other dependencies, which makes it as lightweight as the currently unmaintained Mime Type Detection Utility.

Simple code example (Java 7), using the variables theInputStream and theFileName

try (InputStream is = theInputStream;
        BufferedInputStream bis = new BufferedInputStream(is);) {
    AutoDetectParser parser = new AutoDetectParser();
    Detector detector = parser.getDetector();
    Metadata md = new Metadata();
    md.add(Metadata.RESOURCE_NAME_KEY, theFileName);
    MediaType mediaType = detector.detect(bis, md);
    return mediaType.toString();
}

Please note that MediaType.detect(...) cannot be used directly (TIKA-1120). More hints are provided at https://tika.apache.org/1.24/detection.html.

justify-content property isn't working

Screenshot

Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.

If so, please update bootstrap, worked for me.

Full width image with fixed height

#image {
  width: 100%;
  height: 100px; //static
  object-fit: cover;
}

Print JSON parsed object?

Just use

console.info("CONSOLE LOG : ")
console.log(response);
console.info("CONSOLE DIR : ")
console.dir(response);

and you will get this in chrome console :

CONSOLE LOG : 
facebookSDK_JS.html:56 Object {name: "Diego Matos", id: "10155988777540434"}
facebookSDK_JS.html:57 CONSOLE DIR : 
facebookSDK_JS.html:58 Objectid: "10155988777540434"name: "Diego Matos"__proto__: Object

Disable button after click in JQuery

Consider also .attr()

$("#roommate_but").attr("disabled", true); worked for me.

Using JAXB to unmarshal/marshal a List<String>

From a personal blog post, it is not necessary to create a specific JaxbList < T > object.

Assuming an object with a list of strings:

@XmlRootElement
public class ObjectWithList {

    private List<String> list;

    @XmlElementWrapper(name="MyList")
    @XmlElement
    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

}

A JAXB round trip:

public static void simpleExample() throws JAXBException {

    List<String> l = new ArrayList<String>();
    l.add("Somewhere");
    l.add("This and that");
    l.add("Something");

    // Object with list
    ObjectWithList owl = new ObjectWithList();
    owl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(ObjectWithList.class);
    ObjectWithList retr = marshallUnmarshall(owl, jc);

    for (String s : retr.getList()) {
        System.out.println(s);
    } System.out.println(" ");

}

Produces the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithList>
    <MyList>
        <list>Somewhere</list>
        <list>This and that</list>
        <list>Something</list>
    </MyList>
</objectWithList>

How to view kafka message

Old version includes kafka-simple-consumer-shell.sh (https://kafka.apache.org/downloads#1.1.1) which is convenient since we do not need cltr+c to exit.

For example

kafka-simple-consumer-shell.sh --broker-list $BROKERIP:$BROKERPORT --topic $TOPIC1 --property print.key=true --property key.separator=":"  --no-wait-at-logend

How to enter in a Docker container already running with a new TTY

What about running tmux/GNU Screen within the container? Seems the smoother way to access as many vty as you want with a simple:

$ docker attach {container id}

Add spaces between the characters of a string in Java?

public static void main(String[] args) {
    String name = "Harendra";
    System.out.println(String.valueOf(name).replaceAll(".(?!$)", "$0  "));
    System.out.println(String.valueOf(name).replaceAll(".", "$0  "));
}

This gives output as following use any of the above:

H a r e n d r a

H a r e n d r a

Getting the client's time zone (and offset) in JavaScript

Timezone in hours-

_x000D_
_x000D_
var offset = new Date().getTimezoneOffset();_x000D_
if(offset<0)_x000D_
    console.log( "Your timezone is- GMT+" + (offset/-60));_x000D_
else_x000D_
    console.log( "Your timezone is- GMT-" + offset/60);
_x000D_
_x000D_
_x000D_

If you want to be precise as you mentioned in comment, then you should try like this-

_x000D_
_x000D_
var offset = new Date().getTimezoneOffset();_x000D_
_x000D_
if(offset<0)_x000D_
{_x000D_
    var extraZero = "";_x000D_
    if(-offset%60<10)_x000D_
      extraZero="0";_x000D_
_x000D_
    console.log( "Your timezone is- GMT+" + Math.ceil(offset/-60)+":"+extraZero+(-offset%60));_x000D_
}_x000D_
else_x000D_
{_x000D_
    var extraZero = "";_x000D_
    if(offset%60<10)_x000D_
      extraZero="0";_x000D_
_x000D_
    console.log( "Your timezone is- GMT-" + Math.floor(offset/60)+":"+extraZero+(offset%60));_x000D_
}
_x000D_
_x000D_
_x000D_

WooCommerce return product object by id

Alright, I deserve to be throttled. definitely an RTM but not for WooCommerce, for Wordpress. Solution found due to a JOLT cola (all hail JOLT cola).

TASK: Field named 'related_product_ids' added to a custom post type. So when that post is displayed mini product displays can be displayed with it.

PROBLEM: Was having a problem getting the multiple ids returned via WP_Query.

SOLUTION:

$related_id_list          = get_post_custom_values('related_product_ids');
    // Get comma delimited list from current post
$related_product_ids      = explode(",", trim($related_id_list[0],','));
    // Return an array of the IDs ensure no empty array elements from extra commas
$related_product_post_ids = array( 'post_type' => 'product', 
                                   'post__in'  => $related_product_ids,
                                   'meta_query'=> array( 
                                        array( 'key'    => '_visibility',
                                               'value'  => array('catalog', 'visible'),'compare' => 'IN'
                                        )
                            ) 
);      
    // Query to get all product posts matching given IDs provided it is a published post
$loop = new WP_Query( $related_posts );
    // Execute query
while ( $loop->have_posts() ) : $loop->the_post(); $_product = get_product( $loop->post->ID );
    // Do stuff here to display your products 
endwhile;

Thank you for anyone who may have spent some time on this.

Tim

SQL, Postgres OIDs, What are they and why are they useful?

OIDs basically give you a built-in id for every row, contained in a system column (as opposed to a user-space column). That's handy for tables where you don't have a primary key, have duplicate rows, etc. For example, if you have a table with two identical rows, and you want to delete the oldest of the two, you could do that using the oid column.

OIDs are implemented using 4-byte unsigned integers. They are not unique–OID counter will wrap around at 2³²-1. OID are also used to identify data types (see /usr/include/postgresql/server/catalog/pg_type_d.h).

In my experience, the feature is generally unused in most postgres-backed applications (probably in part because they're non-standard), and their use is essentially deprecated:

In PostgreSQL 8.1 default_with_oids is off by default; in prior versions of PostgreSQL, it was on by default.

The use of OIDs in user tables is considered deprecated, so most installations should leave this variable disabled. Applications that require OIDs for a particular table should specify WITH OIDS when creating the table. This variable can be enabled for compatibility with old applications that do not follow this behavior.

How to create an email form that can send email using html

Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

How to create friendly URL in php?

It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

The answers here helped me up to a point, but I had a problem on HTML5 Number input fields when clicking the up/down buttons in Chrome.

If you click one of the buttons, and left the mouse over the button the number would keep changing as if you were holding the mouse button because the mouseup was being thrown away.

I solved this by removing the mouseup handler as soon as it had been triggered as below:

    $("input:number").focus(function () {
        var $elem = $(this);
        $elem.select().mouseup(function (e) {
            e.preventDefault();
            $elem.unbind(e.type);
        });
    });

Hope this helps people in the future...

Force IE8 Into IE7 Compatiblity Mode

If you add this to your meta tags:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

IE8 will render the page like IE7.

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

Web colors in an Android color xml resource file

I specifically was looking for the XML representation for Android.Graphics.Color. I didn't find these, so here you are. More details are in the help document.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="sysBlack">#FF000000</color>
    <color name="sysBlue">#FF0000FF</color>
    <color name="sysCyan">#FF00FFFF</color>
    <color name="sysDkGray">#FF444444</color>
    <color name="sysGray">#FF888888</color>
    <color name="sysGreen">#FF00FF00</color>
    <color name="sysLtGray">#FFCCCCCC</color>
    <color name="sysMagenta">#FFFF00FF</color>
    <color name="sysRed">#FFFF0000</color>
    <color name="sysTransparent">#00000000</color>
    <color name="sysWhite">#FFFFFFFF</color>
    <color name="sysYellow">#FFFFFF00</color>
</resources>

Of course, this is used like this:

android:textColor="@color/sysGray"

Remove spaces from a string in VB.NET

What about Regex.Replace solution?

myStr = Regex.Replace(myStr, "\s", "")

2D cross-platform game engine for Android and iOS?

You mention Haxe/NME but you seem to instinctively dislike it. However, my experience with it has been very positive. Sure, the API is a reimplementation of the Flash API, but you're not limited to targeting Flash, you can also compile to HTML5 or native Windows, Mac, iOS and Android apps. Haxe is a pleasant, modern language similar to Java or C#.

If you're interested, I've written a bit about my experience using Haxe/NME: link

How can I increment a char?

There is a way to increase character using ascii_letters from string package which ascii_letters is a string that contains all English alphabet, uppercase and lowercase:

>>> from string import ascii_letters
>>> ascii_letters[ascii_letters.index('a') + 1]
'b'
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Also it can be done manually;

>>> letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> letters[letters.index('c') + 1]
'd'

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

pandas: find percentile stats of a given column

assume series s

s = pd.Series(np.arange(100))

Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]

s.quantile(np.linspace(.1, 1, 9, 0))

0.1     9.9
0.2    19.8
0.3    29.7
0.4    39.6
0.5    49.5
0.6    59.4
0.7    69.3
0.8    79.2
0.9    89.1
dtype: float64

OR

s.quantile(np.linspace(.1, 1, 9, 0), 'lower')

0.1     9
0.2    19
0.3    29
0.4    39
0.5    49
0.6    59
0.7    69
0.8    79
0.9    89
dtype: int32