Programs & Examples On #Overhead

Overhead is any combination of excess or indirect computation time, memory, bandwidth, or other resources that are required to attain a particular goal.

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

Android Studio Google JAR file causing GC overhead limit exceeded error

4g is a bit overkill, if you do not want to change buildGradle you can use FILE -> Invalid caches / restart.

Thats work fine for me ...

What is "overhead"?

Overhead is simply the more time consumption in program execution. Example ; when we call a function and its control is passed where it is defined and then its body is executed, this means that we make our CPU to run through a long process( first passing the control to other place in memory and then executing there and then passing the control back to the former position) , consequently it takes alot performance time, hence Overhead. Our goals are to reduce this overhead by using the inline during function definition and calling time, which copies the content of the function at the function call hence we dont pass the control to some other location, but continue our program in a line, hence inline.

ImportError: No module named six

on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve

ImportError: No module named six

when launching Wammu

If it's occurred for python3 program, six come with

pip3 install six

and if you don't have pip3:

apt install python3-pip

with sudo under Ubuntu!

Close virtual keyboard on button press

Try this...

  1. For Showing keyboard

    editText.requestFocus();
    InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    
  2. For Hide keyboard

    InputMethodManager inputManager = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE); 
    inputManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    

How can I refresh c# dataGridView after update ?

I know thats an old topic but i suddenly found the best way of doing it and it does not require nullifying the datasource and reassigning it. Just use a BindingList instead of a List.

for example:

//declare your list
private BindingList<myclass> mMyList = new BindingList<myclass>();

//then bind it to your datagrid, i usually do it on the Load event
private void Form1_Load(object sender, EventArgs e)
{
    _dgMyDatagrig.DataSource = mMyList;
}

//start populating your list 
private void addItem(mycclass item)
{
    mMylist.add(item);

//the datagrid will show automatically the new added/updated items, no need to do anything else

}

Youtube - How to force 480p video quality in embed link / <iframe>

I found that as of May, 2012, if you set the frame size so that the minimum pixel area (width • height) is above a certain threshold, it bumps the quality up from 360p to 480p, if you're video is at least 640 x 360.

I've discovered that setting a frame size to 780 x 480 for the embed frame triggers the 480p quality, without distorting the video (scaling up). 640 x 585 also works in this manner. I also used the &hd=1 parameter, but I doubt this has much control if your video is not uploaded in HD (720p or higher).

For instance:

<iframe width="780" height="480" src="http://www.youtube.com/embed/[VIDEO-ID]?rel=0&fs=1&showinfo=0&autohide=1&hd=1"></iframe>

Of course, the drawback is that by setting these static frame dimensions, you will most likely get black bars on the sides or above and below, depending on what you prefer.

If you didn't care about the controls being cut-off, you could go on to use CSS and overflow: hidden to crop the black bars out of the frame, providing you know the exact dimensions of the video.

Hope this helps, and hope the Embed method soon gets discrete quality parameters again one day!

click command in selenium webdriver does not work

There's nothing wrong with either version of your code. Whatever is causing this, that's not it.

Have you triple checked your locator? Your element definitely has name=submit not id=submit?

How to concatenate text from multiple rows into a single text string in SQL server?

In SQL Server 2005 and later, use the query below to concatenate the rows.

DECLARE @t table
(
    Id int,
    Name varchar(10)
)
INSERT INTO @t
SELECT 1,'a' UNION ALL
SELECT 1,'b' UNION ALL
SELECT 2,'c' UNION ALL
SELECT 2,'d' 

SELECT ID,
stuff(
(
    SELECT ','+ [Name] FROM @t WHERE Id = t.Id FOR XML PATH('')
),1,1,'') 
FROM (SELECT DISTINCT ID FROM @t ) t

Xcode - ld: library not found for -lPods

If you have multiple targets in your project, Cocoapods may have only integrated itself well with just one of them.

I had to manually link to libPods.a in "Link Binary With Libraries" for each additional target I had.

libPods.a in my list of frameworks

no sqljdbc_auth in java.library.path

Here are the steps if you want to do this from Eclipse :

1) Create a folder 'sqlauth' in your C: drive, and copy the dll file sqljdbc_auth.dll to the folder

1) Go to Run> Run Configurations

2) Choose the 'Arguments' tab for your class

3) Add the below code in VM arguments:

-Djava.library.path="C:\\sqlauth"

4) Hit 'Apply' and click 'Run'

Feel free to try other methods .

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

What is the difference between "expose" and "publish" in Docker?

Basically, you have three options:

  1. Neither specify EXPOSE nor -p
  2. Only specify EXPOSE
  3. Specify EXPOSE and -p

1) If you specify neither EXPOSE nor -p, the service in the container will only be accessible from inside the container itself.

2) If you EXPOSE a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.

3) If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker.

The reason why both are separated is IMHO because:

  • choosing a host port depends on the host and hence does not belong to the Dockerfile (otherwise it would be depending on the host),
  • and often it's enough if a service in a container is accessible from other containers.

The documentation explicitly states:

The EXPOSE instruction exposes ports for use within links.

It also points you to how to link containers, which basically is the inter-container communication I talked about.

PS: If you do -p, but do not EXPOSE, Docker does an implicit EXPOSE. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p includes EXPOSE. That's why I didn't list it above as a fourth case.

How to format dateTime in django template?

You can use this:

addedDate = datetime.now().replace(microsecond=0)

Distribution certificate / private key not installed

You can only have one distribution certificate. It unites a public key, known to Apple, with a private key, which lives in the keychain of some computer. If this distribution certificate was created on another computer, then the private key is on the keychain of that computer. And this distribution certificate does not work without it.

So to use this distribution certificate on this computer, you must find that computer, open Keychain Access, locate and export the private key, mail it or otherwise get it to this computer, and import it into the keychain of this computer.

If you go into the Accounts pref pane in Xcode and double-click your Team, you'll see a dialog that gives you help with this. If you see your distribution certificate and it says Not In Keychain, you can control-click that certificate to get a menu item that lets you email whoever created the certificate and ask them to send it to you. That person can use this same import to choose Export Certificate and can email you exported certificate.

Either way, the private key or exported certificate will be passworded. You'll need to know the password in order to use it.

Excel Reference To Current Cell

Full credit to the top answer by @rick-teachey, but you can extend that approach to work with Conditional Formatting. So that this answer is complete, I will duplicate Rick's answer in summary form and then extend it:

  1. Select cell A1 in any worksheet.
  2. Create a Named Range called THIS and set the Refers to: to =!A1.

Attempting to use THIS in Conditional Formatting formulas will result in the error:

You may not use references to other workbooks for Conditional Formatting criteria

If you want THIS to work in Conditional Formatting formulas:

  1. Create another Named Range called THIS_CF and set the Refers to: to =THIS.

You can now use THIS_CF to refer to the current cell in Conditional Formatting formulas.

You can also use this approach to create other relative Named Ranges, such as THIS_COLUMN, THIS_ROW, ROW_ABOVE, COLUMN_LEFT, etc.

curl_exec() always returns false

This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen from the copied link was in a different encoding and hence the curl_exec() was always returning false because it was unable to communicate with the server.

It took me a couple hours to finally understand the diference in the characters bellow:

https://www.e-example.com/api
https://www.e-example.com/api

Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api.

It may seem to you that they are equal but if you check the encoding of the hyphens here you'll see that the first hyphen is a unicode characters U+2010 and the other is a U+002D.

Hope this helps someone.

How to add screenshot to READMEs in github repository?

Add ![ScreenShot](screenshot.png) in the readme markdown as mentioned by many above. Replace screenshot.png with the name of the image you uploaded in your repository.

But here is a newbie tip when you upload the image (as I made this mistake myself):

ensure that your image name does not contain spaces. My original image was saved as "Screenshot day month year id.png". If you don't change the name to something like contentofimage.png, it won't appear as an image in your readme file.

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

While I agree with the previous answers, it's important to note how to access the code of those external libraries.

For example to access a class in the external library, you will want to use the import keyword followed by the external library's name, continued with dot notation until the desired class is reached.

Look at the image below to see how I import CodeGenerationException class from the quickfixj library.

enter image description here

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

What is the difference between a HashMap and a TreeMap?

Use HashMap most of the times but use TreeMap when you need the key to be sorted (when you need to iterate the keys).

android - setting LayoutParams programmatically

int dp1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
            context.getResources().getDisplayMetrics());

tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp1 * 100)); // if you want to set layout height to 100dp

llview.addView(tv);

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

Python script to do something at the same time every day

You can do that like this:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

This will execute a function (eg. hello_world) in the next day at 1a.m.

EDIT:

As suggested by @PaulMag, more generally, in order to detect if the day of the month must be reset due to the reaching of the end of the month, the definition of y in this context shall be the following:

y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)

With this fix, it is also needed to add timedelta to the imports. The other code lines maintain the same. The full solution, using also the total_seconds() function, is therefore:

from datetime import datetime, timedelta
from threading import Timer

x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x

secs=delta_t.total_seconds()

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

Better way to convert file sizes in Python

Here are some easy-to-copy one liners to use if you already know what unit size you want. If you're looking for in a more generic function with a few nice options, see my FEB 2021 update further on...

Bytes

print ('{:,.0f}'.format(os.path.getsize(filepath))+" B")

Kilobits

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<7))+" kb")

Kilobytes

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<10))+" KB")

Megabits

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<17))+" mb")

Megabytes

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<20))+" MB")

Gigabits

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<27))+" gb")

Gigabytes

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<30))+" GB")

Terabytes

print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<40))+" TB")

UPDATE FEB 2021 Here are my updated and fleshed-out functions to a) get file/folder size, b) convert into desired units:

from pathlib import Path

def get_path_size(path = Path('.'), recursive=False):
    """
    Gets file size, or total directory size

    Parameters
    ----------
    path: str | pathlib.Path
        File path or directory/folder path

    recursive: bool
        True -> use .rglob i.e. include nested files and directories
        False -> use .glob i.e. only process current directory/folder

    Returns
    -------
    int:
        File size or recursive directory size in bytes
        Use cleverutils.format_bytes to convert to other units e.g. MB
    """
    path = Path(path)
    if path.is_file():
        size = path.stat().st_size
    elif path.is_dir():
        path_glob = path.rglob('*.*') if recursive else path.glob('*.*')
        size = sum(file.stat().st_size for file in path_glob)
    return size


def format_bytes(bytes, unit, SI=False):
    """
    Converts bytes to common units such as kb, kib, KB, mb, mib, MB

    Parameters
    ---------
    bytes: int
        Number of bytes to be converted

    unit: str
        Desired unit of measure for output


    SI: bool
        True -> Use SI standard e.g. KB = 1000 bytes
        False -> Use JEDEC standard e.g. KB = 1024 bytes

    Returns
    -------
    str:
        E.g. "7 MiB" where MiB is the original unit abbreviation supplied
    """
    if unit.lower() in "b bit bits".split():
        return f"{bytes*8} {unit}"
    unitN = unit[0].upper()+unit[1:].replace("s","")  # Normalised
    reference = {"Kb Kib Kibibit Kilobit": (7, 1),
                 "KB KiB Kibibyte Kilobyte": (10, 1),
                 "Mb Mib Mebibit Megabit": (17, 2),
                 "MB MiB Mebibyte Megabyte": (20, 2),
                 "Gb Gib Gibibit Gigabit": (27, 3),
                 "GB GiB Gibibyte Gigabyte": (30, 3),
                 "Tb Tib Tebibit Terabit": (37, 4),
                 "TB TiB Tebibyte Terabyte": (40, 4),
                 "Pb Pib Pebibit Petabit": (47, 5),
                 "PB PiB Pebibyte Petabyte": (50, 5),
                 "Eb Eib Exbibit Exabit": (57, 6),
                 "EB EiB Exbibyte Exabyte": (60, 6),
                 "Zb Zib Zebibit Zettabit": (67, 7),
                 "ZB ZiB Zebibyte Zettabyte": (70, 7),
                 "Yb Yib Yobibit Yottabit": (77, 8),
                 "YB YiB Yobibyte Yottabyte": (80, 8),
                 }
    key_list = '\n'.join(["     b Bit"] + [x for x in reference.keys()]) +"\n"
    if unitN not in key_list:
        raise IndexError(f"\n\nConversion unit must be one of:\n\n{key_list}")
    units, divisors = [(k,v) for k,v in reference.items() if unitN in k][0]
    if SI:
        divisor = 1000**divisors[1]/8 if "bit" in units else 1000**divisors[1]
    else:
        divisor = float(1 << divisors[0])
    value = bytes / divisor
    if value != 1 and len(unitN) > 3:
            unitN += "s" # Create plural unit of measure
    return "{:,.0f}".format(value) + " " + unitN


# Tests 
>>> assert format_bytes(1,"b") == '8 b'
>>> assert format_bytes(1,"bits") == '8 bits'
>>> assert format_bytes(1024, "kilobyte") == "1 Kilobyte"
>>> assert format_bytes(1024, "kB") == "1 KB"
>>> assert format_bytes(7141000, "mb") == '54 Mb'
>>> assert format_bytes(7141000, "mib") == '54 Mib'
>>> assert format_bytes(7141000, "Mb") == '54 Mb'
>>> assert format_bytes(7141000, "MB") == '7 MB'
>>> assert format_bytes(7141000, "mebibytes") == '7 Mebibytes'
>>> assert format_bytes(7141000, "gb") == '0 Gb'
>>> assert format_bytes(1000000, "kB") == '977 KB'
>>> assert format_bytes(1000000, "kB", SI=True) == '1,000 KB'
>>> assert format_bytes(1000000, "kb") == '7,812 Kb'
>>> assert format_bytes(1000000, "kb", SI=True) == '8,000 Kb'
>>> assert format_bytes(125000, "kb") == '977 Kb'
>>> assert format_bytes(125000, "kb", SI=True) == '1,000 Kb'
>>> assert format_bytes(125*1024, "kb") == '1,000 Kb'
>>> assert format_bytes(125*1024, "kb", SI=True) == '1,024 Kb'

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

You have a sintax error in your code:

try changing this line

$out.='<option value=''.$key.'">'.$value["name"].';

with

$out.='<option value="'.$key.'">'.$value["name"].'</option>';

CSS media queries for screen sizes

Unless you have more style sheets than that, you've messed up your break points:

#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)

The 3rd media query is probably meant to be min-width: 901px. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.

Edit for updated question:

(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)

Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:

(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)

Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.

mysqld: Can't change dir to data. Server doesn't start

I have met same problem. In my case I had no ..\data dir in my C:\mysql\ so I just executed mysqld --initialize command from c:\mysql\bin\ directory and I got the data directory in c:\mysql\data. Afterwards I could use mysqld.exe --console command to test the server startup.

Copy file from source directory to binary directory using CMake

This is what I used to copy some resource files: the copy-files is an empty target to ignore errors

 add_custom_target(copy-files ALL
    COMMAND ${CMAKE_COMMAND} -E copy_directory
    ${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
    ${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
    )

Common elements comparison between 2 lists

Just use list comprehension.

Half line solution:

common_elements = [x for x in list1 if x in list2]

If that helped, consider upvoting my answer.

What's the difference between display:inline-flex and display:flex?

You need a bit more information so that the browser knows what you want. For instance, the children of the container need to be told "how" to flex.

Updated Fiddle

I've added #wrapper > * { flex: 1; margin: auto; } to your CSS and changed inline-flex to flex, and you can see how the elements now space themselves out evenly on the page.

How to pass a JSON array as a parameter in URL

You can pass your json Input as a POST request along with authorization header in this way

public static JSONObject getHttpConn(String json){
        JSONObject jsonObject=null;
        try {
            HttpPost httpPost=new HttpPost("http://google.com/");
            org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
            StringEntity stringEntity=new StringEntity("d="+json);

            httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            String authorization="test:test@123";
            String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());        
            httpPost.addHeader("Authorization", security.get("Authorization"));
            httpPost.setEntity(stringEntity);
            HttpResponse reponse=client.execute(httpPost);
            InputStream inputStream=reponse.getEntity().getContent();
            String jsonResponse=IOUtils.toString(inputStream);
            jsonObject=JSONObject.fromObject(jsonResponse);
            } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return jsonObject;


    }

This Method will return a json response.In same way you can use GET method

How to debug Apache mod_rewrite

One trick is to turn on the rewrite log. To turn it on, try this line in your apache main config or current virtual host file (not in .htaccess):

LogLevel alert rewrite:trace6

Before Apache httpd 2.4 mod_rewrite, such a per-module logging configuration did not exist yet, instead you could use the following logging settings:

RewriteEngine On
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

How can I initialise a static Map?

Well... I like enums ;)

enum MyEnum {
    ONE   (1, "one"),
    TWO   (2, "two"),
    THREE (3, "three");

    int value;
    String name;

    MyEnum(int value, String name) {
        this.value = value;
        this.name = name;
    }

    static final Map<Integer, String> MAP = Stream.of( values() )
            .collect( Collectors.toMap( e -> e.value, e -> e.name ) );
}

Maven dependency for Servlet 3.0 API?

Here is what I use. All of these are in the Central and have sources.

For Tomcat 7 (Java 7, Servlet 3.0)

Note - Servlet, JSP and EL APIs are provided in Tomcat. Only JSTL (if used) needs to be bundled with the web app.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

For Tomcat 8 (Java 8, Servlet 3.1)

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

C# Example of AES256 encryption using System.Security.Cryptography.Aes

public class AesCryptoService
{
    private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
    private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");


    public static string EncryptStringToBytes_Aes(string plainText)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;


        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        
        return Convert.ToBase64String(encrypted);
    }


    
    public static string DecryptStringFromBytes_Aes(string Text)
    {
        if (Text == null || Text.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        string plaintext = null;
        byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;


            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
    }
}

Peak-finding algorithm for Python/SciPy

First things first, the definition of "peak" is vague if without further specifications. For example, for the following series, would you call 5-4-5 one peak or two?

1-2-1-2-1-1-5-4-5-1-1-5-1

In this case, you'll need at least two thresholds: 1) a high threshold only above which can an extreme value register as a peak; and 2) a low threshold so that extreme values separated by small values below it will become two peaks.

Peak detection is a well-studied topic in Extreme Value Theory literature, also known as "declustering of extreme values". Its typical applications include identifying hazard events based on continuous readings of environmental variables e.g. analysing wind speed to detect storm events.

Javascript : natural sort of alphanumerical strings

So you need a natural sort ?

If so, than maybe this script by Brian Huisman based on David koelle's work would be what you need.

It seems like Brian Huisman's solution is now directly hosted on David Koelle's blog:

Can you use @Autowired with static fields?

@Component("NewClass")
public class NewClass{
    private static SomeThing someThing;

    @Autowired
    public void setSomeThing(SomeThing someThing){
        NewClass.someThing = someThing;
    }
}

Auto increment in MongoDB to store sequence of Unique User ID

I had a similar issue, namely I was interested in generating unique numbers, which can be used as identifiers, but doesn't have to. I came up with the following solution. First to initialize the collection:

fun create(mongo: MongoTemplate) {
        mongo.db.getCollection("sequence")
                .insertOne(Document(mapOf("_id" to "globalCounter", "sequenceValue" to 0L)))
    }

An then a service that return unique (and ascending) numbers:

@Service
class IdCounter(val mongoTemplate: MongoTemplate) {

    companion object {
        const val collection = "sequence"
    }

    private val idField = "_id"
    private val idValue = "globalCounter"
    private val sequence = "sequenceValue"

    fun nextValue(): Long {
        val filter = Document(mapOf(idField to idValue))
        val update = Document("\$inc", Document(mapOf(sequence to 1)))
        val updated: Document = mongoTemplate.db.getCollection(collection).findOneAndUpdate(filter, update)!!
        return updated[sequence] as Long
    }
}

I believe that id doesn't have the weaknesses related to concurrent environment that some of the other solutions may suffer from.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Just encase someone else ran into the issues I did I was using Response.End() an async trigger button

<asp:AsyncPostBackTrigger ControlID="btn_login" />

in an update panel. I switched to regular post back not the best but it worked.

<asp:PostBackTrigger ControlID="btn_login" />. 

Since I was only redirecting on the page this was a viable solution.

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

XMLHttpRequest status 0 (responseText is empty)

Actually make sure your button type is Button not Submit, that caused status conflict where I met recently.

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

How do I create a self-signed certificate for code signing on Windows?

Roger's answer was very helpful.

I had a little trouble using it, though, and kept getting the red "Windows can't verify the publisher of this driver software" error dialog. The key was to install the test root certificate with

certutil -addstore Root Demo_CA.cer

which Roger's answer didn't quite cover.

Here is a batch file that worked for me (with my .inf file, not included). It shows how to do it all from start to finish, with no GUI tools at all (except for a few password prompts).

REM Demo of signing a printer driver with a self-signed test certificate.
REM Run as administrator (else devcon won't be able to try installing the driver)
REM Use a single 'x' as the password for all certificates for simplicity.

PATH %PATH%;"c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin";"c:\Program Files\Microsoft SDKs\Windows\v7.0\Bin";c:\WinDDK\7600.16385.1\bin\selfsign;c:\WinDDK\7600.16385.1\Tools\devcon\amd64

makecert -r -pe -n "CN=Demo_CA" -ss CA -sr CurrentUser ^
   -a sha256 -cy authority -sky signature ^
   -sv Demo_CA.pvk Demo_CA.cer

makecert -pe -n "CN=Demo_SPC" -a sha256 -cy end ^
   -sky signature ^
   -ic Demo_CA.cer -iv Demo_CA.pvk ^
   -sv Demo_SPC.pvk Demo_SPC.cer

pvk2pfx -pvk Demo_SPC.pvk -spc Demo_SPC.cer ^
   -pfx Demo_SPC.pfx ^
   -po x

inf2cat /drv:driver /os:XP_X86,Vista_X64,Vista_X86,7_X64,7_X86 /v

signtool sign /d "description" /du "www.yoyodyne.com" ^
   /f Demo_SPC.pfx ^
   /p x ^
   /v driver\demoprinter.cat

certutil -addstore Root Demo_CA.cer

rem Needs administrator. If this command works, the driver is properly signed.
devcon install driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F

rem Now uninstall the test driver and certificate.
devcon remove driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F

certutil -delstore Root Demo_CA

How to center cell contents of a LaTeX table whose columns have fixed widths?

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

Delete specific line number(s) from a text file using sed?

You can delete a particular single line with its line number by

sed -i '33d' file

This will delete the line on 33 line number and save the updated file.

Rollback transaction after @Test

Just add @Transactional annotation on top of your test:

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class StudentSystemTest {

By default Spring will start a new transaction surrounding your test method and @Before/@After callbacks, rolling back at the end. It works by default, it's enough to have some transaction manager in the context.

From: 10.3.5.4 Transaction management (bold mine):

In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that TransactionalTestExecutionListener is configured by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must provide a PlatformTransactionManager bean in the application context loaded by @ContextConfiguration semantics. In addition, you must declare @Transactional either at the class or method level for your tests.

How to parse a query string into a NameValueCollection in .NET

HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:

NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
   {
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();

      queryParameters.Add(key, val);
   }
}

Spring MVC: How to return image in @ResponseBody?

I think you maybe need a service to store file upload and get that file. Check more detail from here

1) Create a Storage Sevice

@Service
public class StorageService {

Logger log = LoggerFactory.getLogger(this.getClass().getName());
private final Path rootLocation = Paths.get("upload-dir");

public void store(MultipartFile file) {
    try {
        Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
    } catch (Exception e) {
        throw new RuntimeException("FAIL!");
    }
}

public Resource loadFile(String filename) {
    try {
        Path file = rootLocation.resolve(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new RuntimeException("FAIL!");
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException("FAIL!");
    }
}

public void deleteAll() {
    FileSystemUtils.deleteRecursively(rootLocation.toFile());
}

public void init() {
    try {
        Files.createDirectory(rootLocation);
    } catch (IOException e) {
        throw new RuntimeException("Could not initialize storage!");
    }
}
}

2) Create Rest Controller to upload and get file

@Controller
public class UploadController {

@Autowired
StorageService storageService;

List<String> files = new ArrayList<String>();

@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
    String message = "";
    try {
        storageService.store(file);
        files.add(file.getOriginalFilename());

        message = "You successfully uploaded " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.OK).body(message);
    } catch (Exception e) {
        message = "FAIL to upload " + file.getOriginalFilename() + "!";
        return      ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
    }
}

@GetMapping("/getallfiles")
public ResponseEntity<List<String>> getListFiles(Model model) {
    List<String> fileNames = files
            .stream().map(fileName -> MvcUriComponentsBuilder
                    .fromMethodName(UploadController.class, "getFile", fileName).build().toString())
            .collect(Collectors.toList());

    return ResponseEntity.ok().body(fileNames);
}

@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
    Resource file = storageService.loadFile(filename);
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
            .body(file);
}

}

Check if input is integer type in C

Just check is your number has any difference with float version of it, or not.

float num; 
scanf("%f",&num);

if(num != (int)num) {
    printf("it's not an integer");
    return;
}

Android RatingBar change star colors

1) declare this xml

<LinearLayout 
             android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:orientation="horizontal"
         android:paddingLeft="20dp"
         android:paddingRight="20dp"
         android:layout_marginBottom="20dp"
         android:background="#323232"
         android:gravity="center_horizontal">

       <com.example.android.custom_ratingbar.CustomRatingBar
        android:id="@+id/coloredRatingBar5"
        style="@style/coloredRatingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"

         />
       </LinearLayout>

2) in style.xml

<style name="coloredRatingBarStyleSmall">
        <item name="indicator">false</item>
        <item name="type">small</item>
    </style>

3)

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class CustomRatingBar extends View{

    private static final String TAG="ColoredRatingBar";
    private static final int NORMAL = 0;
    private static final int SMALL = 1;

    Bitmap[] drawables;
    Bitmap progressBackground;
    Context mContext;
    private int mNumStars =9;
    private float mRating =0;
    private boolean mIndicator;
    private float slidePosition;
    private int mType;

    /**
     * A callback that notifies clients when the rating has been changed. This
     * includes changes that were initiated by the user through a touch gesture
     * or arrow key/trackball as well as changes that were initiated
     * programmatically.
     */
    public interface OnRatingBarChangeListener {

        /**
         * Notification that the rating has changed. Clients can use the
         * fromUser parameter to distinguish user-initiated changes from those
         * that occurred programmatically. This will not be called continuously
         * while the user is dragging, only when the user finalizes a rating by
         * lifting the touch.
         *
         * @param ratingBar The RatingBar whose rating has changed.
         * @param rating The current rating. This will be in the range
         *            0..numStars.
         * @param fromUser True if the rating change was initiated by a user's
         *            touch gesture or arrow key/horizontal trackbell movement.
         */
        void onRatingChanged(CustomRatingBar ratingBar, float rating, boolean fromUser);

    }

    private OnRatingBarChangeListener mOnRatingBarChangeListener;

    public CustomRatingBar(Context context) {
        this(context, null);
    }
    public CustomRatingBar(Context context, AttributeSet attrs) {
        this(context, attrs,0);//R.attr.coloredRatingBarStyle
    }

    public CustomRatingBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomRatingBar,defStyle, 0);
        final boolean indicator = a.getBoolean(R.styleable.CustomRatingBar_indicator, false);
        final float rating = a.getFloat(R.styleable.CustomRatingBar_setrating, -1);
        final int type = a.getInt(R.styleable.CustomRatingBar_type, 0);
        a.recycle();

        setIndicator(indicator);
        setRating(rating);
        setType(type);
        init(context);
    }

    public int getType() {
        return mType;
    }

    public void setType(int type) {
        this.mType = type;
    }

    private void init(Context context) {
        mContext = context;
        Resources res = getResources();
        if(mType==SMALL){
            drawables = new Bitmap[]{BitmapFactory.decodeResource(res, R.drawable.rating_inactive),BitmapFactory.decodeResource(res, R.drawable.rating_active)};
            progressBackground = BitmapFactory.decodeResource(res, R.drawable.rating_inactive);
        }else{
            drawables = new Bitmap[]{BitmapFactory.decodeResource(res, R.drawable.rating_inactive),BitmapFactory.decodeResource(res, R.drawable.rating_active)};
            progressBackground = BitmapFactory.decodeResource(res, R.drawable.rating_inactive);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //draw empty stars bg
        for(int i=0;i< mNumStars;i++){
            drawStar(canvas,i);
        }

    }


    private void drawStar(Canvas canvas, int position) {
        float fraction = mRating -(position);
        Bitmap ratedStar1 = getRatedStar();
        Paint paint=getPaint(position);
        int division=getSize();
        Bitmap ratedStar=null;
        Bitmap emptyStar=null;
       if(!isInEditMode()){
        ratedStar=Bitmap.createScaledBitmap(ratedStar1, division, division, false);
        emptyStar=Bitmap.createScaledBitmap(progressBackground, division, division, false);
       }
        if((position)< mRating){
            if(!isInEditMode()){
           canvas.drawBitmap(ratedStar,(position* division),0,paint);
            }

        } else{

                if(!isInEditMode()){
              canvas.drawBitmap(emptyStar,(position*division),0,null);

            }
        }


    }
    private int getSize(){
        return (getWidth()/mNumStars);
    }

    private Bitmap getRatedStar() {

        if(mRating==0){
            return drawables[0];
        }
        else{
            return drawables[1];
        }
    }

    private Paint getPaint(int position){
        int value=(255*(position+1))/mNumStars;
        String hexString=Integer.toHexString(value).equals("0")?"00":Integer.toHexString(value);
        String hexvalue="#"+hexString+"000000";//FEE98E
        //Log.e("TAG", position+"/"+value+"/"+hexvalue);

        Paint paint=new Paint();

        paint.setColor(Color.parseColor(hexvalue));

        return paint;
    }

    public int getNumStars() {
        return mNumStars;
    }

    public void setNumStars(int numStars) {
        this.mNumStars = numStars;
    }

    public float getRating() {
        return mRating;
    }

    public void setRating(float rating) {
        setRating(rating,false);
    }

    void setRating(float rating,boolean fromUser) {
        if(rating>mNumStars){
            this.mRating = mNumStars;
        }
        this.mRating = rating;
        invalidate();
        dispatchRatingChange(fromUser);
    }

    public boolean isIndicator() {
        return mIndicator;
    }

    public void setIndicator(boolean indicator) {
        this.mIndicator = indicator;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (progressBackground != null) {

            final int width = progressBackground.getWidth() * mNumStars;
            final int height = progressBackground.getHeight();

            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            Bitmap emptyStar=Bitmap.createScaledBitmap(progressBackground, widthSize/mNumStars, widthSize/mNumStars, false);
            int heightSize = emptyStar.getHeight();

            setMeasuredDimension(resolveSizeAndState(widthSize, widthMeasureSpec, 0),
                    resolveSizeAndState(heightSize, heightMeasureSpec, 0));
        }
        else{
              int desiredWidth = 100;
            int desiredHeight = 50;

            int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);

            int width;
            int height;

            //Measure Width
            if (widthMode == MeasureSpec.EXACTLY) {
                //Must be this size
                width = widthSize;
            } else if (widthMode == MeasureSpec.AT_MOST) {
                //Can't be bigger than...
                width = Math.min(desiredWidth, widthSize);
            } else {
                //Be whatever you want
                width = desiredWidth;
            }

            //Measure Height
            if (heightMode == MeasureSpec.EXACTLY) {
                //Must be this size
                height = heightSize;
            } else if (heightMode == MeasureSpec.AT_MOST) {
                //Can't be bigger than...
                height = Math.min(desiredHeight, heightSize);
            } else {
                //Be whatever you want
                height = desiredHeight;
            }

            //MUST CALL THIS
          setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),resolveSizeAndState(height, heightMeasureSpec, 0));
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mIndicator){
            return false;
        }

        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                slidePosition = getRelativePosition(event.getX());

                int newRating = (int)(slidePosition>0?slidePosition+1:0) ;
                if(newRating>mNumStars){
                    newRating=mNumStars;
                }

             //   Log.e("TAG", ""+newRating);
                if (newRating != mRating) {
                    setRating(newRating,true);
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
        }

        return true;
    }

    private float getRelativePosition(float x) {
        Bitmap emptyStar=Bitmap.createScaledBitmap(progressBackground, getWidth()/mNumStars, getWidth()/mNumStars, false);
        int widthSize = emptyStar.getWidth();
      //  Log.e("TAG", widthSize+"/"+x);
         float position = x / widthSize;
       position = Math.max(position, 0);
       return Math.min(position, mNumStars);
    }

    /**
     * Sets the listener to be called when the rating changes.
     *
     * @param listener The listener.
     */
    public void setOnRatingBarChangeListener(OnRatingBarChangeListener listener) {
        mOnRatingBarChangeListener = listener;
    }

    /**
     * @return The listener (may be null) that is listening for rating change
     *         events.
     */
    public OnRatingBarChangeListener getOnRatingBarChangeListener() {
        return mOnRatingBarChangeListener;
    }

    void dispatchRatingChange(boolean fromUser) {
        if (mOnRatingBarChangeListener != null) {
            mOnRatingBarChangeListener.onRatingChanged(this, getRating(),
                    fromUser);
        }
    }
}


5) then in calling activity---

CustomRatingBar coloredRatingBar5=(CustomRatingBar)findViewById(R.id.coloredRatingBar5);
        coloredRatingBar5.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            @Override
            public void onRatingChanged(CustomRatingBar ratingBar, float rating,boolean fromUser) {
                // TODO Auto-generated method stub
                Log.e("RATING", ""+rating);

            }
        });

6) rating active---take any image with dark color coz it will be used as color transparency for different rating

rating_inactive--take any image of same size of above image with light background..it will used when no rating is selected

Importing a CSV file into a sqlite3 database table using Python

import csv, sqlite3

def _get_col_datatypes(fin):
    dr = csv.DictReader(fin) # comma is default delimiter
    fieldTypes = {}
    for entry in dr:
        feildslLeft = [f for f in dr.fieldnames if f not in fieldTypes.keys()]        
        if not feildslLeft: break # We're done
        for field in feildslLeft:
            data = entry[field]

        # Need data to decide
        if len(data) == 0:
            continue

        if data.isdigit():
            fieldTypes[field] = "INTEGER"
        else:
            fieldTypes[field] = "TEXT"
    # TODO: Currently there's no support for DATE in sqllite

if len(feildslLeft) > 0:
    raise Exception("Failed to find all the columns data types - Maybe some are empty?")

return fieldTypes


def escapingGenerator(f):
    for line in f:
        yield line.encode("ascii", "xmlcharrefreplace").decode("ascii")


def csvToDb(csvFile,dbFile,tablename, outputToFile = False):

    # TODO: implement output to file

    with open(csvFile,mode='r', encoding="ISO-8859-1") as fin:
        dt = _get_col_datatypes(fin)

        fin.seek(0)

        reader = csv.DictReader(fin)

        # Keep the order of the columns name just as in the CSV
        fields = reader.fieldnames
        cols = []

        # Set field and type
        for f in fields:
            cols.append("\"%s\" %s" % (f, dt[f]))

        # Generate create table statement:
        stmt = "create table if not exists \"" + tablename + "\" (%s)" % ",".join(cols)
        print(stmt)
        con = sqlite3.connect(dbFile)
        cur = con.cursor()
        cur.execute(stmt)

        fin.seek(0)


        reader = csv.reader(escapingGenerator(fin))

        # Generate insert statement:
        stmt = "INSERT INTO \"" + tablename + "\" VALUES(%s);" % ','.join('?' * len(cols))

        cur.executemany(stmt, reader)
        con.commit()
        con.close()

Trust Anchor not found for Android SSL Connection

I know this is a very old article, but I came across this article when trying to solve my trust anchor issues. I have posted how I fixed it. If you have pre-installed your Root CA you need to add a configuration to the manifest.

https://stackoverflow.com/a/60102517/114265

How to determine whether a year is a leap year?

From 1700 to 1917, official calendar was the Julian calendar. Since then they we use the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that 32nd day in 1918, was the February 14th.

In both calendar systems, February is the only month with a variable amount of days, it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 while in the Gregorian calendar, leap years are either of the following:

Divisible by 400.

Divisible by 4 and not divisible by 100.

So the program for leap year will be:

def leap_notleap(year):

    yr = ''
    if year <= 1917:
        if year % 4 == 0:
            yr = 'leap'
        else:
            yr = 'not leap'
    elif year >= 1919:
        if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
            yr = 'leap'
        else:
            yr = 'not leap'
    else:
        yr = 'none actually, since feb had only 14 days'

    return yr

Tar archiving that takes input from a list of files

Some versions of tar, for example, the default versions on HP-UX (I tested 11.11 and 11.31), do not include a command line option to specify a file list, so a decent work-around is to do this:

tar cvf allfiles.tar $(cat mylist.txt)

Use querystring variables in MVC controller

I figured it out...finally found another article on it.

string start = Request.QueryString["start"];

string end = Request.QueryString["end"];

Bubble Sort Homework

Your use of the Unsorted variable is wrong; you want to have a variable that tells you if you have swapped two elements; if you have done that, you can exit your loop, otherwise, you need to loop again. To fix what you've got here, just put the "unsorted = false" in the body of your if case; remove your else case; and put "unsorted = true before your for loop.

Efficient way to determine number of digits in an integer

for integer 'X' you want to know the number of digits , alright without using any loop , this solution act in one formula in one line only so this is the most optimal solution i have ever seen to this problem .

 int x = 1000 ; 
 cout<<numberOfDigits = 1+floor(log10(x))<<endl ; 

Max length for client ip address

Take it from someone who has tried it all three ways... just use a varchar(39)

The slightly less efficient storage far outweighs any benefit of having to convert it on insert/update and format it when showing it anywhere.

Python: Assign print output to a variable

To answer the question more generaly how to redirect standard output to a variable ?

do the following :

from io import StringIO
import sys

result = StringIO()
sys.stdout = result
result_string = result.getvalue()

If you need to do that only in some function do the following :

old_stdout = sys.stdout  

# your function containing the previous lines
my_function()

sys.stdout = old_stdout

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

Remove a CLASS for all child elements

You can also do like this :

  $("#table-filters li").parent().find('li').removeClass("active");

react-router - pass props to handler component

You can pass props by passing them to <RouteHandler> (in v0.13.x) or the Route component itself in v1.0;

// v0.13.x
<RouteHandler/>
<RouteHandler someExtraProp={something}/>

// v1.0
{this.props.children}
{React.cloneElement(this.props.children, {someExtraProp: something })}

(from the upgrade guide at https://github.com/rackt/react-router/releases/tag/v1.0.0)

All child handlers will receive the same set of props - this may be useful or not depending on the circumstance.

What does the fpermissive flag do?

A common case for simply setting -fpermissive and not sweating it exists: the thoroughly-tested and working third-party library that won't compile on newer compiler versions without -fpermissive. These libraries exist, and are very likely not the application developer's problem to solve, nor in the developer's schedule budget to do it.

Set -fpermissive and move on in that case.

What's is the difference between include and extend in use case diagram?

To simplify,

for include

  1. When the base use case is executed, the included use case is executed EVERYTIME.
  2. The base use case required the completion of the included use case in order to be completed.

a typical example: between login and verify password

(login) --- << include >> ---> (verify password)

for the login process to success, "verify password" must be successful as well.


for extend

  1. When the base use case is executed, the extended use case is executed only SOMETIMES
  2. The extended use case will happen only when certain criteria are met.

a typical example: between login and show error message (only happened sometimes)

(login) <--- << extend >> --- (show error message)

"show error message" only happens sometimes when the login process failed.

How I can check whether a page is loaded completely or not in web driver?

Simple ready2use snippet, working perfectly for me

static void waitForPageLoad(WebDriver wdriver) {
    WebDriverWait wait = new WebDriverWait(wdriver, 60);

    Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {

        @Override
        public boolean apply(WebDriver input) {
            return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
        }

    };
    wait.until(pageLoaded);
}

Can't connect to Postgresql on port 5432

You have to edit postgresql.conf file and change line with 'listen_addresses'.

This file you can find in the /etc/postgresql/9.3/main directory.

Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:

listen_addresses = '*'

Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:

host    all         all         192.168.1.0/24        md5

Please, read comments in this file...

EDIT:

After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.

EDIT2: Highlited configuration files.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

How to insert a file in MySQL database?

You need to use BLOB, there's TINY, MEDIUM, LONG, and just BLOB, as with other types, choose one according to your size needs.

TINYBLOB 255
BLOB 65535
MEDIUMBLOB 16777215
LONGBLOB 4294967295
(in bytes)

The insert statement would be fairly normal. You need to read the file using fread and then addslashes to it.

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

Radio buttons and label to display in same line

If you use the HTML structure I lay out in this question you can simply float your label and input to the left and adjust padding/margin until things are lined up.

And yes, you'll want to make your radio button have a class name for old IE. And to have all of them on the same line, according to the markup I linked to above, it would be like so:

_x000D_
_x000D_
fieldset {_x000D_
      overflow: hidden_x000D_
    }_x000D_
    _x000D_
    .some-class {_x000D_
      float: left;_x000D_
      clear: none;_x000D_
    }_x000D_
    _x000D_
    label {_x000D_
      float: left;_x000D_
      clear: none;_x000D_
      display: block;_x000D_
      padding: 0px 1em 0px 8px;_x000D_
    }_x000D_
    _x000D_
    input[type=radio],_x000D_
    input.radio {_x000D_
      float: left;_x000D_
      clear: none;_x000D_
      margin: 2px 0 0 2px;_x000D_
    }
_x000D_
<fieldset>_x000D_
      <div class="some-class">_x000D_
        <input type="radio" class="radio" name="x" value="y" id="y" />_x000D_
        <label for="y">Thing 1</label>_x000D_
        <input type="radio" class="radio" name="x" value="z" id="z" />_x000D_
        <label for="z">Thing 2</label>_x000D_
      </div>_x000D_
    </fieldset>
_x000D_
_x000D_
_x000D_

How to make a stable two column layout in HTML/CSS

Here you go:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Cols</title>_x000D_
  <style>_x000D_
    #left {_x000D_
      width: 200px;_x000D_
      float: left;_x000D_
    }_x000D_
    #right {_x000D_
      margin-left: 200px;_x000D_
      /* Change this to whatever the width of your left column is*/_x000D_
    }_x000D_
    .clear {_x000D_
      clear: both;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="container">_x000D_
    <div id="left">_x000D_
      Hello_x000D_
    </div>_x000D_
    <div id="right">_x000D_
      <div style="background-color: red; height: 10px;">Hello</div>_x000D_
    </div>_x000D_
    <div class="clear"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

See it in action here: http://jsfiddle.net/FVLMX/

MySQL 'Order By' - sorting alphanumeric correctly

If you need to sort an alpha-numeric column that does not have any standard format whatsoever

SELECT * FROM table ORDER BY (name = '0') DESC, (name+0 > 0) DESC, name+0 ASC, name ASC

You can adapt this solution to include support for non-alphanumeric characters if desired using additional logic.

npm install hangs

This method is working for me when npm blocks in installation Package for IONIC installation and ReactNative and another package npm.

You can change temporary:

npm config set prefix C:\Users\[username]\AppData\Roaming\npm\node_modules2

  • Change the path in environment variables. Set:

    C:\Users[username]\AppData\Roaming\npm\node_modules2

  • Run the command to install your package.

  • Open file explorer, copy the link:

    C:\Users[username]\AppData\Roaming\npm\node_modules

    ok file yourpackage.CMD created another folder Created "node_modules2" in node_modules and contain your package folder.

  • Copy your package file CMD to parent folder "npm".

  • Copy your package folder to parent folder "node_modules".

  • Now run:

    npm config set prefix C:\Users\[username]\AppData\Roaming\npm

  • Change the path in environment variables. Set:

    C:\Users[username]\AppData\Roaming\npm

Now the package is working correctly with the command line.

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

Read this:

http://www.quora.com/OAuth-2-0/How-does-OAuth-2-0-work

or an even simpler but quick explanation:

http://agileanswer.blogspot.se/2012/08/oauth-20-for-my-ninth-grader.html

The redirect URI is the callback entry point of the app. Think about how OAuth for Facebook works - after end user accepts permissions, "something" has to be called by Facebook to get back to the app, and that "something" is the redirect URI. Furthermore, the redirect URI should be different than the initial entry point of the app.

The other key point to this puzzle is that you could launch your app from a URL given to a webview. To do this, i simply followed the guide on here:

http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html

and

http://inchoo.net/mobile-development/iphone-development/launching-application-via-url-scheme/

note: on those last 2 links, "http://" works in opening mobile safari but "tel://" doesn't work in simulator

in the first app, I call

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"secondApp://"]];

In my second app, I register "secondApp" (and NOT "secondApp://") as the name of URL Scheme, with my company as the URL identifier.

How to vertically align a html radio button to it's label?

input {
    display: table-cell;
    vertical-align: middle
}

Put class for all radio. This will work for all radio button on the html page.

Fiddle

Difference between AutoPostBack=True and AutoPostBack=False?

The AutoPostBack property is used to set or return whether or not an automatic post back occurs when the user presses "ENTER" or "TAB" in the TextBox control.

If this property is set to TRUE the automatic post back is enabled, otherwise FALSE. Default is FALSE.

jQuery $.cookie is not a function

The old version of jQuery Cookie has been deprecated, so if you're getting the error:

$.cookie is not a function

you should upgrade to the new version.

The API for the new version is also different - rather than using

$.cookie("yourCookieName");

you should use

Cookies.get("yourCookieName");

Should I call Close() or Dispose() for stream objects?

This is an old question, but you can now write using statements without needing to block each one. They will be disposed of in reverse order when the containing block is finished.

using var responseStream = response.GetResponseStream();
using var reader = new StreamReader(responseStream);
using var writer = new StreamWriter(filename);

int chunkSize = 1024;
while (!reader.EndOfStream)
{
    char[] buffer = new char[chunkSize];
    int count = reader.Read(buffer, 0, chunkSize);
    if (count != 0)
    {
        writer.Write(buffer, 0, count);
    }
}

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/using

Android REST client, Sample?

Never use AsynTask to perform network request or whatever that need to be persisted. Async Task are strongly tied to your activity and if the user change the orientation of the screen since the App is re created the AsyncTask will be stopped.

I suggest you to use Service pattern with Intent Service and ResultReceiver. Take a look to RESTDroid. It's a library that allows you to perform any kind of REST request asynchronously and notify your UI with Request Listeners implementing the Virgil Dobjanschi's service pattern.

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

In Linux, how to tell how much memory processes are using?

More elegant approach:

echo "Memory usage for PID <>:"; for mem in {Private,Rss,Shared,Swap,Pss};do grep $mem /proc/<pid>/smaps | awk -v mem_type="$mem" '{i=i+$2} END {print mem_type,"memory usage:"i}' ;done

find -exec with multiple commands

One of the following:

find *.txt -exec awk 'END {print $0 "," FILENAME}' {} \;

find *.txt -exec sh -c 'echo "$(tail -n 1 "$1"),$1"' _ {} \;

find *.txt -exec sh -c 'echo "$(sed -n "\$p" "$1"),$1"' _ {} \;

How do you programmatically update query params in react-router?

Example using react-router v4, redux-thunk and react-router-redux(5.0.0-alpha.6) package.

When user uses search feature, I want him to be able to send url link for same query to a colleague.

import { push } from 'react-router-redux';
import qs from 'query-string';

export const search = () => (dispatch) => {
    const query = { firstName: 'John', lastName: 'Doe' };

    //API call to retrieve records
    //...

    const searchString = qs.stringify(query);

    dispatch(push({
        search: searchString
    }))
}

How to align a div to the top of its parent but keeping its inline-block behaviour?

Or you could just add some content to the div and use inline-table

Calling a method every x minutes

Example of using a Timer:

using System;
using System.Timers;

static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("..."); 
}

Get first day of week in SQL Server

Maybe you need this:

SELECT DATEADD(DD, 1 - DATEPART(DW, GETDATE()), GETDATE())

Or

DECLARE @MYDATE DATETIME
SET @MYDATE = '2011-08-23'
SELECT DATEADD(DD, 1 - DATEPART(DW, @MYDATE), @MYDATE)

Function

CREATE FUNCTION [dbo].[GetFirstDayOfWeek]
( @pInputDate    DATETIME )
RETURNS DATETIME
BEGIN

SET @pInputDate = CONVERT(VARCHAR(10), @pInputDate, 111)
RETURN DATEADD(DD, 1 - DATEPART(DW, @pInputDate),
               @pInputDate)

END
GO

Disable all dialog boxes in Excel while running VB script?

Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?

As so:

Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False

For Each element In sArray
    XLSMToXLSX(element)
Next element

Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub

Sub XLSMToXLSX(ByVal file As String)
    Do While WorkFile <> ""
        If Right(WorkFile, 4) <> "xlsx" Then
            Workbooks.Open Filename:=myPath & WorkFile

            Application.DisplayAlerts = False
            Application.EnableEvents = False

            ActiveWorkbook.SaveAs Filename:= _
            modifiedFileName, FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False, _
            ConflictResolution:=xlLocalSessionChanges

            Application.DisplayAlerts = True
            Application.EnableEvents = True

            ActiveWorkbook.Close
        End If
        WorkFile = Dir()
    Loop
End Sub

How do I abort/cancel TPL Tasks?

You should not try to do this directly. Design your tasks to work with a CancellationToken, and cancel them this way.

In addition, I would recommend changing your main thread to function via a CancellationToken as well. Calling Thread.Abort() is a bad idea - it can lead to various problems that are very difficult to diagnose. Instead, that thread can use the same Cancellation that your tasks use - and the same CancellationTokenSource can be used to trigger the cancellation of all of your tasks and your main thread.

This will lead to a far simpler, and safer, design.

Rails: update_attribute vs update_attributes

update_attribute simply updates only one attribute of a model, but we can pass multiple attributes in update_attributes method.

Example:

user = User.last

#update_attribute
user.update_attribute(:status, "active")

It pass the validation

#update_attributes
user.update_attributes(first_name: 'update name', status: "active")

it doesn't update if validation fails.

What is a NullPointerException, and how do I fix it?

A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:

  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Taking the length of null as if it were an array.
  4. Accessing or modifying the slots of null as if it were an array.
  5. Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html

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

this works flawlessly for me. insert any code before or after the "do until" loop. In your case, put the 5 lines (time1= & time2= & "do until" loop) at the end inside your do loop

sub whatever()
Dim time1, time2

time1 = Now
time2 = Now + TimeValue("0:00:01")
    Do Until time1 >= time2
        DoEvents
        time1 = Now()
    Loop

End sub

Could not find or load main class

Simple way to compile and execute java file.(HelloWorld.java doesn't includes any package)

set path="C:\Program Files (x86)\Java\jdk1.7.0_45\bin"
javac "HelloWorld.java"
java -cp . HelloWorld
pause

SqlServer: Login failed for user

Is your SQL Server in 'mixed mode authentication' ? This is necessary to login with a SQL server account instead of a Windows login.

You can verify this by checking the properties of the server and then SECURITY, it should be in 'SQL Server and Windows Authentication Mode'

This problem occurs if the user tries to log in with credentials that cannot be validated. This problem can occur in the following scenarios:

Scenario 1: The login may be a SQL Server login but the server only accepts Windows Authentication.

Scenario 2: You are trying to connect by using SQL Server Authentication but the login used does not exist on SQL Server.

Scenario 3: The login may use Windows Authentication but the login is an unrecognized Windows principal. An unrecognized Windows principal means that Windows can't verify the login. This might be because the Windows login is from an untrusted domain.

It's also possible the user put in incorrect information.

http://support.microsoft.com/kb/555332

How to check edittext's text is email address or not?

In Kotlin, an E-mail address you can validate by the simple method without writing a lot of code and bother yourself with a regular expression like "^[_A-Za-z0-9-\+]....".

Look how is simple:

 fun validateEmail(emailForValidation: String): Boolean{
    
            return Patterns.EMAIL_ADDRESS.matcher(emailForValidation).matches()
        }

After you write this method for e-mail validation you just need to input your e-mail which you want to validate. If validateEmail() method returns true e-mail is valid and if false then e-mail is not valid.

Here is example how you can use this method:

 val eMail: String = emailEditText.text.toString().trim()
 if (!validateEmail(eMail)){ //IF NOT TRUE
            Toast.makeText(context, "Please enter valid E-mail address", Toast.LENGTH_LONG).show()

            return //RETURNS BACK TO IF STATEMENT
        }

Where could I buy a valid SSL certificate?

The value of the certificate comes mostly from the trust of the internet users in the issuer of the certificate. To that end, Verisign is tough to beat. A certificate says to the client that you are who you say you are, and the issuer has verified that to be true.

You can get a free SSL certificate signed, for example, by StartSSL. This is an improvement on self-signed certificates, because your end-users would stop getting warning pop-ups informing them of a suspicious certificate on your end. However, the browser bar is not going to turn green when communicating with your site over https, so this solution is not ideal.

The cheapest SSL certificate that turns the bar green will cost you a few hundred dollars, and you would need to go through a process of proving the identity of your company to the issuer of the certificate by submitting relevant documents.

jQuery lose focus event

If the 'Cool Options' are hidden from the view before the field is focused then you would want to create this in JQuery instead of having it in the DOM so anyone using a screen reader wouldn't see unnecessary information. Why should they have to listen to it when we don't have to see it?

So you can setup variables like so:

var $coolOptions= $("<div id='options'></div>").text("Some cool options");

and then append (or prepend) on focus

$("input[name='input_name']").focus(function() {
    $(this).append($coolOptions);
});

and then remove when the focus ends

$("input[name='input_name']").focusout(function() {
    $('#options').remove();
});

Equivalent to AssemblyInfo in dotnet core/csproj

You can always add your own AssemblyInfo.cs, which comes in handy for InternalsVisibleToAttribute, CLSCompliantAttribute and others that are not automatically generated.

Adding AssemblyInfo.cs to a Project

  1. In Solution Explorer, right click on <project name> > Add > New Folder.

Add New Folder

  1. Name the folder "Properties".

Name folder Properties

  1. Right click on the "Properties" folder, and click Add > New Item....

Add New Item

  1. Select "Class" and name it "AssemblyInfo.cs".

Name file AssemblyInfo.cs

Suppressing Auto-Generated Attributes

If you want to move your attributes back to AssemblyInfo.cs instead of having them auto-generated, you can suppress them in MSBuild as natemcmaster pointed out in his answer.

MySQL InnoDB not releasing disk space after deleting data rows from table

If you don't use innodb_file_per_table, reclaiming disk space is possible, but quite tedious, and requires a significant amount of downtime.

The How To is pretty in-depth - but I pasted the relevant part below.

Be sure to also retain a copy of your schema in your dump.

Currently, you cannot remove a data file from the system tablespace. To decrease the system tablespace size, use this procedure:

Use mysqldump to dump all your InnoDB tables.

Stop the server.

Remove all the existing tablespace files, including the ibdata and ib_log files. If you want to keep a backup copy of the information, then copy all the ib* files to another location before the removing the files in your MySQL installation.

Remove any .frm files for InnoDB tables.

Configure a new tablespace.

Restart the server.

Import the dump files.

Laravel Eloquent: Ordering results of all()

Try this:

$categories     =   Category::all()->sortByDesc("created_at");

How to make all controls resize accordingly proportionally when window is maximized?

In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.

Here are some that do not resize their contents (I'm guessing that you are using one or more of these):

StackPanel
WrapPanel
Canvas
TabControl

Here are some that do resize their contents:

Grid
UniformGrid
DockPanel

Therefore, it is almost always preferable to use a Grid instead of a StackPanel unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid to not size its inner controls... it all depends on your Grid.RowDefinition and Grid.ColumnDefinition settings:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
        <RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
        <RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
    </Grid.RowDefinitions>
</Grid>

You can find out more about the Grid control from the Grid Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.

Further resizing can be achieved using the FrameworkElement.HorizontalAlignment and FrameworkElement.VerticalAlignment properties. The default value of these properties is Stretch which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.

UPDATE >>>

In response to the questions in your comment:

Use the Grid.RowDefinition and Grid.ColumnDefinition settings to organise a basic structure first... it is common to add Grid controls into the cells of outer Grid controls if need be. You can also use the Grid.ColumnSpan and Grid.RowSpan properties to enable controls to span multiple columns and/or rows of a Grid.

It is most common to have at least one row/column with a Height/Width of "*" which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.

There is no Auto setting that you can use on the controls in the cells, but this is just as well, because we want the Grid to size the controls for us... therefore, we don't want to set the Height or Width of these controls at all.

The point that I made about the FrameworkElement.HorizontalAlignment and FrameworkElement.VerticalAlignment properties was just to let you know of their existence... as their default value is already Stretch, you don't generally need to set them explicitly.

The Margin property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin property to suit your needs.

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

How do I enter a multi-line comment in Perl?

POD is the official way to do multi line comments in Perl,

From faq.perl.org[perlfaq7]

The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with =cut, ending the Pod section:

=pod

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=cut

The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.

The =begin directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with comment. End the comment using =end with the same label. You still need the =cut to go back to Perl code from the Pod comment:

=begin comment

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=end comment

=cut

ssh : Permission denied (publickey,gssapi-with-mic)

First a password login has to be established to remote machine

  • Firstly make a password login

you have to enable a password login by enabling the property ie) PasswordAuthentication yes in sshd_config file.Then restart the sshd service and copy the pub key to remote server (aws ec2 in my case), key will be copied without any error

  • Without password login works if and only if password login is made first
  • copy the pub key contents to authorised keys, cat xxx.pub >> ~/.ssh/authorized_keys

How to format date string in java?

If you are looking for a solution to your particular case, it would be:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);

Sticky Header after scrolling down

Here is a JS fiddle http://jsfiddle.net/ke9kW/1/

As the others say, set the header to fixed, and start it with display: none

then jQuery

$(window).scroll(function () {
  if ( $(this).scrollTop() > 200 && !$('header').hasClass('open') ) {
    $('header').addClass('open');
    $('header').slideDown();
   } else if ( $(this).scrollTop() <= 200 ) {
    $('header').removeClass('open');
    $('header').slideUp();
  }
});

where 200 is the height in pixels you'd like it to move down at. The addition of the open class is to allow us to run an elseif instead of just else, so some of the code doesn't unnecessarily run on every scrollevent, save a lil bit of memory

How to downgrade the installed version of 'pip' on windows?

pip itself is just a normal python package. Thus you can install pip with pip.

Of cource, you don't want to affect the system's pip, install it inside a virtualenv.

pip install pip==1.2.1

How to check if object has been disposed in C#

A good way is to derive from TcpClient and override the Disposing(bool) method:

class MyClient : TcpClient {
    public bool IsDead { get; set; }
    protected override void Dispose(bool disposing) {
        IsDead = true;
        base.Dispose(disposing);
    }
}

Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.

Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.

EDIT: A reflection example:

using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
   BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
   // Retrieve a FieldInfo instance corresponding to the field
   PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
   // Retrieve the value of the field, and cast as necessary
   return (bool)field.GetValue(s, null);
}

Possible heap pollution via varargs parameter

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

However, if the method actually is not safe, users will no longer be warned.

Xcode: failed to get the task for process

Just get the same problem by installing my app on iPhone 5S with Distribution Profile

-> my solution was to activate Capabilities wich are set in Distribution Profile(in my case "Keychain Sharing","In-App Purchase" and "Game Center")

Hope this helps someone...

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

Not with plain HTML I'm afraid.

You could use some jQuery to do this though:

$(function(){
    var $select = $(".1-100");
    for (i=1;i<=100;i++){
        $select.append($('<option></option>').val(i).html(i))
    }
});?

-- SEE DEMO --

You can download jQuery here

How to read from a file or STDIN in Bash?

Please try the following code:

while IFS= read -r line; do
    echo "$line"
done < file

Moving Panel in Visual Studio Code to right side

You can do the same in insider's edition, There is an option on right top corner to switch to the panel to sidebar https://code.visualstudio.com/insiders/

terminal at the bottom side terminal in the bottom side

terminal at the right side terminal in the right side

How do I change the hover over color for a hover over table in Bootstrap?

Give this a try:

.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
  background-color: #color;
}

detect back button click in browser

So as far as AJAX is concerned...

Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;   
            }
        };
    }
}

As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.

How to implement linear interpolation?

import scipy.interpolate
y_interp = scipy.interpolate.interp1d(x, y)
print y_interp(5.0)

scipy.interpolate.interp1d does linear interpolation by and can be customized to handle error conditions.

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

What is the use of a cursor in SQL Server?

Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop). To use cursors in SQL procedures, you need to do the following: 1.Declare a cursor that defines a result set. 2.Open the cursor to establish the result set. 3.Fetch the data into local variables as needed from the cursor, one row at a time. 4.Close the cursor when done.

for ex:

declare @tab table
(
Game varchar(15),
Rollno varchar(15)
)
insert into @tab values('Cricket','R11')
insert into @tab values('VollyBall','R12')

declare @game  varchar(20)
declare @Rollno varchar(20)

declare cur2 cursor for select game,rollno from @tab 

open cur2

fetch next from cur2 into @game,@rollno

WHILE   @@FETCH_STATUS = 0   
begin

print @game

print @rollno

FETCH NEXT FROM cur2 into @game,@rollno

end

close cur2

deallocate cur2

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

AppCompatActivity was only added in version 22.1.0 of the support library. Before that it was called ActionBarActivity.

You should use the same version for all of your support libraries. At the time of writing the latest version is 23.1.1 (you can find out the latest here https://developer.android.com/tools/support-library/index.html#revisions) so the dependencies section of your gradle file should look like this.

implementation "com.android.support:support-v4:23.1.1"
implementation "com.android.support:appcompat-v7:23.1.1"
implementation "com.android.support:support-annotations:23.1.1"

Unknown column in 'field list' error on MySQL Update query

A query like this will also cause the error:

SELECT table1.id FROM table2

Where the table is specified in column select and not included in the from clause.

Cookies vs. sessions

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session. save _ path location and actually "see sessions". A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.

Find and extract a number from a string

Here's how I cleanse phone numbers to get the digits only:

string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

this work for me. add configurations.all in app/build.gradle

android {
    configurations.all {
        resolutionStrategy.force 'com.android.support:support-annotations:27.1.1'
    }
}

How to search a specific value in all tables (PostgreSQL)?

to search every column of every table for a particular value

This does not define how to match exactly.
Nor does it define what to return exactly.

Assuming:

  • Find any row with any column containing the given value in its text representation - as opposed to equaling the given value.
  • Return the table name (regclass) and the tuple ID (ctid), because that's simplest.

Here is a dead simple, fast and slightly dirty way:

CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
  RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
   FOR _tbl IN
      SELECT c.oid::regclass
      FROM   pg_class c
      JOIN   pg_namespace n ON n.oid = relnamespace
      WHERE  c.relkind = 'r'                           -- only tables
      AND    n.nspname !~ '^(pg_|information_schema)'  -- exclude system schemas
      ORDER BY n.nspname, c.relname
   LOOP
      RETURN QUERY EXECUTE format(
         'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
       , _tbl, '%' || _like_pattern || '%')
      USING _tbl;
   END LOOP;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM search_whole_db('mypattern');

Provide the search pattern without enclosing %.

Why slightly dirty?

If separators and decorators for the row in text representation can be part of the search pattern, there can be false positives:

  • column separator: , by default
  • whole row is enclosed in parentheses:()
  • some values are enclosed in double quotes "
  • \ may be added as escape char

And the text representation of some columns may depend on local settings - but that ambiguity is inherent to the question, not to my solution.

Each qualifying row is returned once only, even when it matches multiple times (as opposed to other answers here).

This searches the whole DB except for system catalogs. Will typically take a long time to finish. You might want to restrict to certain schemas / tables (or even columns) like demonstrated in other answers. Or add notices and a progress indicator, also demonstrated in another answer.

The regclass object identifier type is represented as table name, schema-qualified where necessary to disambiguate according to the current search_path:

What is the ctid?

You might want to escape characters with special meaning in the search pattern. See:

See line breaks and carriage returns in editor

Try the following command.

:set binary

In VIM, this should do the same thing as using the "-b" command line option. If you put this in your startup (i.e. .vimrc) file, it will always be in place for you.

On many *nix systems, there is a "dos2unix" or "unix2dos" command that can process the file and correct any suspected line ending issues. If there is no problem with the line endings, the files will not be changed.

JavaScript - Get minutes between two dates

This problem is solved easily with moment.js, like this example:

var difference = mostDate.diff(minorDate, "minutes");

The second parameter can be changed for another parameters, see the moment.js documentation.

e.g.: "days", "hours", "minutes", etc.

http://momentjs.com/docs/

The CDN for moment.js is available here:

https://cdnjs.com/libraries/moment.js

Thanks.

EDIT:

mostDate and minorDate should be a moment type.

EDIT 2:

For those who are reading my answer in 2020+, momentjs is now a legacy project.

If you are still looking for a well-known library to do this job, I would recommend date-fns.

// How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
var result = differenceInMinutes(
  new Date(2014, 6, 2, 12, 20, 0),
  new Date(2014, 6, 2, 12, 7, 59)
)
//=> 12

Adding custom radio buttons in android

I realize this is a belated answer, but looking through developer.android.com, it seems that the Toggle button would be ideal for your situation.

Toggle button image http://developer.android.com/guide/topics/ui/controls/togglebutton.html

And of course you can still use the other suggestions for having a background drawable to get a custom look you want.

<ToggleButton 
    android:id="@+id/togglebutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button_background"
    android:textOn="On"
    android:textOff="Off"
    />

Now if you want to go with your final edit and have a "halo" effect around your buttons, you can use another custom selector to do just that.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" > <!-- selected -->
        <shape>
            <solid
                android:color="@android:color/white" />
            <stroke
                android:width="3px"
                android:color="@android:color/holo_blue_bright" />
            <corners
                android:radius="5dp" />
        </shape>
    </item>
    <item> <!-- default -->
        <shape>
            <solid
                android:color="@android:color/white" />
            <stroke
                android:width="1px"
                android:color="@android:color/darker_gray" />
            <corners
                android:radius="5dp" />
        </shape>
    </item> 
</selector>

React Native: Getting the position of an element

If you use function components and don't want to use a forwardRef to measure your component's absolute layout, you can get a reference to it from the LayoutChangeEvent in the onLayout callback.

This way, you can get the absolute position of the element:

<MyFunctionComp
  onLayout={(event) => {
    event.target.measure(
      (x, y, width, height, pageX, pageX) => {
        doSomethingWithAbsolutePosition({
          x: x + pageX, 
          y: y + pageY,
        });
      },
    );
  }}
/>

Tested with React Native 0.63.3.

How to programmatically determine the current checked out Git branch

Try with:

 git symbolic-ref --short -q HEAD

Or you try with git branch with --no-color force simple plain string the output:

 git branch  --no-color

With grep in regex mode(-E) you can check if exists the character '*':

 git branch  --no-color  | grep -E '^\*' 

The results its similar to:

* currentBranch

You can use the next options:

sed 's/\*[^a-z]*//g'
cut -d ' ' -f 2
awk '{print $2}'

for example:

 git branch  --no-color  | grep -E '^\*' | sed 's/\*[^a-z]*//g'
 git branch  --no-color  | grep -E '^\*' | sed cut -d ' ' -f 2
 git branch  --no-color  | grep -E '^\*' | awk '{print $2}'

if exists a error you cant use an default value:

  cmd || echo 'defualt value';

All into in a bash function:

function get_branch() {
      git branch --no-color | grep -E '^\*' | awk '{print $2}' \
        || echo "default_value"
      # or
      # git symbolic-ref --short -q HEAD || echo "default_value";
}

Use:

branch_name=`get_branch`;
echo $branch_name;

Displaying a message in iOS which has the same functionality as Toast in Android

Again if using IOS on Xamarin there is a new component called BTProgressHUD in the component store

How can I make XSLT work in chrome?

The problem based on Chrome is not about the xml namespace which is xmlns="http://www.w3.org/1999/xhtml". Without the namesspace attribute, it won't work with IE either.

Because of the security restriction, you have to add the --allow-file-access-from-files flag when you start the chrome. I think linux/*nix users can do that easily via the terminal but for windows users, you have to open the properties of the Chrome shortcut and add it in the target destination as below;

Right-Click -> Properties -> Target

enter image description here

Here is a sample full path with the flags which I use on my machine;

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files

I hope showing this step-by-step will help windows users for the problem, this is why I've added this post.

IntelliJ Organize Imports

Under "Settings -> Editor -> General -> Auto Import" there are several options regarding automatic imports. Only unambiguous imports may be added automatically; this is one of the options.

How can I add a PHP page to WordPress?

Try this:

/**
 * The template for displaying demo page
 *
 * template name: demo template
 *
 */

What are the most common naming conventions in C?

There could be many, mainly IDEs dictate some trends and C++ conventions are also pushing. For C commonly:

  • UNDERSCORED_UPPER_CASE (macro definitions, constants, enum members)
  • underscored_lower_case (variables, functions)
  • CamelCase (custom types: structs, enums, unions)
  • uncappedCamelCase (oppa Java style)
  • UnderScored_CamelCase (variables, functions under kind of namespaces)

Hungarian notation for globals are fine but not for types. And even for trivial names, please use at least two characters.

Select2 doesn't work when embedded in a bootstrap modal

i had this problem before , i am using yii2 and i solved it this way

$.fn.modal.Constructor.prototype.enforceFocus = $.noop;

Save file to specific folder with curl command

This option comes in curl 7.73.0:

curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg

laravel compact() and ->with()

Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});
<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

or

public function index($id)
{
    $category = Category::find($id);
    $topics = $category->getTopicPaginator();
    $message = Message::find(1);

    // here I would just use "->with([$category, $topics, $message])"
    return View::make('category.index')->with(compact('category', 'topics', 'message'));
}

Can't compile C program on a Mac after upgrade to Mojave

When you

  • updated to Mojave 10.14.6
  • your /usr/include was deleted again
  • the package mentioned in @Jonathan-lefflers answer doesn't exist anymore The file /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg does not exist. and
  • Xcode complains that command line tools are already installed xcode-select --install xcode-select: error: command line tools are already installed, use "Software Update" to install updates

Then, what helped me recover the mentioned package, was deleting the whole CommandLineTools folder (sudo) rm -rf /Library/Developer/CommandLineTools and reinstall it xcode-select --install.

Edit and Continue: "Changes are not allowed when..."

I had a database project in the solution which stopped the webforms project from being editted.

I clicked "Unload" on the database project and everything now works sweetly.

Auto-increment primary key in SQL tables

Right-click on the table in SSMS, 'Design' it, and click on the id column. In the properties, set the identity to be seeded @ e.g. 1 and to have increment of 1 - save and you're done.

What are all the possible values for HTTP "Content-Type" header?

As is defined in RFC 1341:

In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:

Content-Type := type "/" subtype *[";" parameter]

type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token

x-token := < The two characters "X-" followed, with no intervening white space, by any token >

subtype := token

parameter := attribute "=" value

attribute := token

value := token / quoted-string

token := 1*

tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values

And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).

As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).

Also note the comment above:

If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.

You'll notice that a lot of HTTP requests/responses include an X- header of some sort which are self defined, keep this in mind when validating the types.

How to get a function name as a string?

To get the current function's or method's name from inside it, consider:

import inspect

this_function_name = inspect.currentframe().f_code.co_name

sys._getframe also works instead of inspect.currentframe although the latter avoids accessing a private function.

To get the calling function's name instead, consider f_back as in inspect.currentframe().f_back.f_code.co_name.


If also using mypy, it can complain that:

error: Item "None" of "Optional[FrameType]" has no attribute "f_code"

To suppress the above error, consider:

import inspect
import types
from typing import cast

this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name

How to handle a lost KeyStore password in Android?

You can contact Google Play Console Support with this issue and they will be able to reset the keystore for you to a new keystore. Then you will be able to publish future updates without having to to change the package name, and therefore you will be able to continue to be able to update the same app.

In the play console click the help button at the top > Scroll down to heed more help and click "Contact Us" > Type in you need help with a Keystore Reset > Click "next step" > Click "Upload key reset request" > Click "Contact Google Play Developer Support" > Then choose a contact method to contact them to reset it for you.

How to grab substring before a specified character jQuery or JavaScript

You could use regex as this will give you the string if it matches the requirements. The code would be something like:

const address = "1345 albany street, Bellevue WA 42344";
const regex = /[1-9][0-9]* [a-zA-Z]+ [a-zA-Z]+/;
const matchedResult = address.match(regex);

console.log(matchedResult[0]); // This will give you 1345 albany street.

So to break the code down. [1-9][0-9]* basically means the first number cannot be a zero and has to be a number between 1-9 and the next number can be any number from 0-9 and can occur zero or more times as sometimes the number is just one digit and then it matches a space. [a-zA-Z] basically matches all capital letters to small letters and has to occur one or more times and this is repeated.

IndentationError expected an indented block

This error also occurs if you have a block with no statements in it

For example:

def my_function():
    for i in range(1,10):


def say_hello():
    return "hello"

Notice that the for block is empty. You can use the pass statement if you want to test the remaining code in the module.

Generating a Random Number between 1 and 10 Java

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min

Printing an array in C++?

Most of the libraries commonly used in C++ can't print arrays, per se. You'll have to loop through it manually and print out each value.

Printing arrays and dumping many different kinds of objects is a feature of higher level languages.

Adjust UILabel height depending on the text

Adding to the above answers:

This can be easily achieved via storyboard.

  1. Set constraint for UILabel.(In my case I did top, left and fixed width)
  2. Set Number of line to 0 in Attribute Inspector
  3. Set Line Break to WordWrap in Attribute Inspector.

UILabel Height Adjust

No provider for Router?

Please use this module

RouterModule.forRoot(
  [
    { path: "", component: LoginComponent}
  ]
)

now just replace your <login></login> with <router-outlet></router-outlet> thats it

Using setattr() in python

I'm here in general only to find out that through dict it is necessary to work inside setattr XD

Cross field validation with Hibernate Validator (JSR 303)

Each field constraint should be handled by a distinct validator annotation, or in other words it's not suggested practice to have one field's validation annotation checking against other fields; cross-field validation should be done at the class level. Additionally, the JSR-303 Section 2.2 preferred way to express multiple validations of the same type is via a list of annotations. This allows the error message to be specified per match.

For example, validating a common form:

@FieldMatch.List({
        @FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match"),
        @FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")
})
public class UserRegistrationForm  {
    @NotNull
    @Size(min=8, max=25)
    private String password;

    @NotNull
    @Size(min=8, max=25)
    private String confirmPassword;

    @NotNull
    @Email
    private String email;

    @NotNull
    @Email
    private String confirmEmail;
}

The Annotation:

package constraints;

import constraints.impl.FieldMatchValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;

/**
 * Validation annotation to validate that 2 fields have the same value.
 * An array of fields and their matching confirmation fields can be supplied.
 *
 * Example, compare 1 pair of fields:
 * @FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match")
 * 
 * Example, compare more than 1 pair of fields:
 * @FieldMatch.List({
 *   @FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match"),
 *   @FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")})
 */
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface FieldMatch
{
    String message() default "{constraints.fieldmatch}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * @return The first field
     */
    String first();

    /**
     * @return The second field
     */
    String second();

    /**
     * Defines several <code>@FieldMatch</code> annotations on the same element
     *
     * @see FieldMatch
     */
    @Target({TYPE, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
            @interface List
    {
        FieldMatch[] value();
    }
}

The Validator:

package constraints.impl;

import constraints.FieldMatch;
import org.apache.commons.beanutils.BeanUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(final FieldMatch constraintAnnotation)
    {
        firstFieldName = constraintAnnotation.first();
        secondFieldName = constraintAnnotation.second();
    }

    @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context)
    {
        try
        {
            final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
            final Object secondObj = BeanUtils.getProperty(value, secondFieldName);

            return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
        }
        catch (final Exception ignore)
        {
            // ignore
        }
        return true;
    }
}

How to find if a file contains a given string using Windows command line

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

c++ compile error: ISO C++ forbids comparison between pointer and integer

You need the change those double quotation marks into singles. ie. if (answer == 'y') returns true;

Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx

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

' Single quoted

The simplest way to specify a string is to enclose it in single quotes. Single quote is generally faster, and everything quoted inside treated as plain string.

Example:

echo 'Start with a simple string';
echo 'String\'s apostrophe';
echo 'String with a php variable'.$name;

" Double quoted

Use double quotes in PHP to avoid having to use the period to separate code (Note: Use curly braces {} to include variables if you do not want to use concatenation (.) operator) in string.

Example:

echo "Start with a simple string";
echo "String's apostrophe";
echo "String with a php variable {$name}";

Is there a performance benefit single quote vs double quote in PHP?

Yes. It is slightly faster to use single quotes.

PHP won't use additional processing to interpret what is inside the single quote. when you use double quotes PHP has to parse to check if there are any variables within the string.

What size do you use for varchar(MAX) in your parameter declaration?

You do not need to pass the size parameter, just declare Varchar already understands that it is MAX like:

cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

Using local makefile for CLion instead of CMake

While this is one of the most voted feature requests, there is one plugin available, by Victor Kropp, that adds support to makefiles:

Makefile support plugin for IntelliJ IDEA

Install

You can install directly from the official repository:

Settings > Plugins > search for makefile > Search in repositories > Install > Restart

Use

There are at least three different ways to run:

  1. Right click on a makefile and select Run
  2. Have the makefile open in the editor, put the cursor over one target (anywhere on the line), hit alt + enter, then select make target
  3. Hit ctrl/cmd + shift + F10 on a target (although this one didn't work for me on a mac).

It opens a pane named Run target with the output.

Difference between require, include, require_once and include_once?

require has greater overhead than include, since it has to parse the file first. Replacing requires with includes is often a good optimization technique.

Converting NSData to NSString in Objective c

Objective C:

[[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

Swift:

let str = String(data: data, encoding: .ascii)

How can I insert vertical blank space into an html document?

Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html

<style>
  .bottom-three {
     margin-bottom: 3cm;
  }
</style>


<p class="bottom-three">
   This is the first question?
</p>
<p class="bottom-three">
   This is the second question?
</p>

Can I check if Bootstrap Modal Shown / Hidden?

With Bootstrap 4:

if ($('#myModal').hasClass('show')) {
    alert("Modal is visible")
}

How to compare two date values with jQuery

var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;

if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
    ----------------------------------
}

how to make a whole row in a table clickable as a link?

You can't do that. It is invalid HTML. You can't put a <a> in between a <tbody> and a <tr>. Try this instead:

<tr onclick="window.location='#';">
        ...
     </tr>

add style for pointer view

[data-href] { cursor: pointer; }

When you work up to it, you'd want to use JavaScript to assign the click handler outside of the HTML.

Regex for not empty and not whitespace

Most regular expression engines support "counter part" escape sequences. That is, for \s (white-space) there's its counter part \S (non-white-space).

Using this, you can check, if there is at least one non-white-space character with ^\S+$.

PCRE for PHP has several of these escape sequences.

Remove all the children DOM elements in div

while(node.firstChild) {
    node.removeChild(node.firstChild);
}

Convert DataTable to IEnumerable<T>

If you are producing the DataTable from an SQL query, have you considered simply using Dapper instead?

Then, instead of making a SqlCommand with SqlParameters and a DataTable and a DataAdapter and on and on, which you then have to laboriously convert to a class, you just define the class, make the query column names match the field names, and the parameters are bound easily by name. You already have the TankReading class defined, so it will be really simple!

using Dapper;

// Below can be SqlConnection cast to DatabaseConnection, too.
DatabaseConnection connection = // whatever
IEnumerable<TankReading> tankReadings = connection.Query<TankReading>(
   "SELECT * from TankReading WHERE Value = @value",
   new { value = "tank1" } // note how `value` maps to `@value`
);
return tankReadings;

Now isn't that awesome? Dapper is very optimized and will give you darn near equivalent performance as reading directly with a DataAdapter.

If your class has any logic in it at all or is immutable or has no parameterless constructor, then you probably do need to have a DbTankReading class (as a pure POCO/Plain Old Class Object):

// internal because it should only be used in the data source project and not elsewhere
internal sealed class DbTankReading {
   int TankReadingsID { get; set; }
   DateTime? ReadingDateTime { get; set; }
   int ReadingFeet { get; set; }
   int ReadingInches { get; set; }
   string MaterialNumber { get; set; }
   string EnteredBy { get; set; }
   decimal ReadingPounds { get; set; }
   int MaterialID { get; set; }
   bool Submitted { get; set; }
}

You'd use that like this:

IEnumerable<TankReading> tankReadings = connection
   .Query<DbTankReading>(
      "SELECT * from TankReading WHERE Value = @value",
      new { value = "tank1" } // note how `value` maps to `@value`
   )
   .Select(tr => new TankReading(
      tr.TankReadingsID,
      tr.ReadingDateTime,
      tr.ReadingFeet,
      tr.ReadingInches,
      tr.MaterialNumber,
      tr.EnteredBy,
      tr.ReadingPounds,
      tr.MaterialID,
      tr.Submitted
   });

Despite the mapping work, this is still less painful than the data table method. This also lets you perform some kind of logic, though if the logic is any more than very simple straight-across mapping, I'd put the logic into a separate TankReadingMapper class.

MySQL: @variable vs. variable. What's the difference?

MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.

While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.

I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.

MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.

Find the closest ancestor element that has a specific class

This does the trick:

function findAncestor (el, cls) {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
}

The while loop waits until el has the desired class, and it sets el to el's parent every iteration so in the end, you have the ancestor with that class or null.

Here's a fiddle, if anyone wants to improve it. It won't work on old browsers (i.e. IE); see this compatibility table for classList. parentElement is used here because parentNode would involve more work to make sure that the node is an element.

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

You'll need to run this command from the MySQL prompt:

REPAIR TABLE tbl_name USE_FRM;

From MySQL's documentation on the Repair command:

The USE_FRM option is available for use if the .MYI index file is missing or if its header is corrupted. This option tells MySQL not to trust the information in the .MYI file header and to re-create it using information from the .frm file. This kind of repair cannot be done with myisamchk.

How do I create HTML table using jQuery dynamically?

You may use two options:

  1. createElement
  2. InnerHTML

Create Element is the fastest way (check here.):

$(document.createElement('table'));

InnerHTML is another popular approach:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

Edit:

Check Dynamic creation of table with DOM

Edit 2:

IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

function createProviderFormFields(id, labelText, tooltip, regex) {
    var tr = '<tr>' ;
         // create a new textInputBox  
           var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
        // create a new Label Text
            tr += '<td>' + labelText  + '</td>';
            tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;
}

Counter in foreach loop in C#

Without Custom Foreach Version:

datas.Where((data, index) =>
{
    //Your Logic
    return false;
}).Any();

In some simple case,my way is using where + false + any.
It is fater a little than foreach + select((data,index)=>new{data,index}),and without custom Foreach method.

MyLogic:

  • use statement body run your logic.
  • because return false,new Enumrable data count is zero.
  • use Any() let yeild run.

Benchmark Test Code

[RPlotExporter, RankColumn]
public class BenchmarkTest
{
    public static IEnumerable<dynamic> TestDatas = Enumerable.Range(1, 10).Select((data, index) => $"item_no_{index}");

    [Benchmark]
    public static void ToArrayAndFor()
    {
        var datats = TestDatas.ToArray();
        for (int index = 0; index < datats.Length; index++)
        {
            var result = $"{datats[index]}{index}";
        }
    }

    [Benchmark]
    public static void IEnumrableAndForach()
    {
        var index = 0;
        foreach (var item in TestDatas)
        {
            index++;
            var result = $"{item}{index}";
        }
    }

    [Benchmark]
    public static void LinqSelectForach()
    {
        foreach (var item in TestDatas.Select((data, index) => new { index, data }))
        {
            var result = $"{item.data}{item.index}";
        }
    }

    [Benchmark]
    public static void LinqSelectStatementBodyToList()
    {
        TestDatas.Select((data, index) =>
        {
            var result = $"{data}{index}";
            return true;
        }).ToList();
    }

    [Benchmark]
    public static void LinqSelectStatementBodyToArray()
    {
        TestDatas.Select((data, index) =>
        {
            var result = $"{data}{index}";
            return true;
        }).ToArray();
    }

    [Benchmark]
    public static void LinqWhereStatementBodyAny()
    {
        TestDatas.Where((data, index) =>
        {
            var result = $"{data}{index}";
            return false;
        }).Any();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var summary = BenchmarkRunner.Run<BenchmarkTest>();

        System.Console.Read();
    }
}

Benchmark Result :

                         Method |     Mean |     Error |    StdDev | Rank |
------------------------------- |---------:|----------:|----------:|-----:|
                  ToArrayAndFor | 4.027 us | 0.0797 us | 0.1241 us |    4 |
            IEnumrableAndForach | 3.494 us | 0.0321 us | 0.0285 us |    1 |
               LinqSelectForach | 3.842 us | 0.0503 us | 0.0471 us |    3 |
  LinqSelectStatementBodyToList | 3.822 us | 0.0416 us | 0.0389 us |    3 |
 LinqSelectStatementBodyToArray | 3.857 us | 0.0764 us | 0.0785 us |    3 |
      LinqWhereStatementBodyAny | 3.643 us | 0.0693 us | 0.0712 us |    2 |

jquery find class and get the value

You can also get the value by the following way

$(document).ready(function(){
  $("#start").click(function(){
    alert($(this).find("input[class='myClass']").val());
  });
});

repaint() in Java

Simply write :

frame.validate();
frame.repaint();

That will do .

Regards

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

Linq to SQL .Sum() without group ... into

you can:

itemsCart.Select(c=>c.Price).Sum();

To hit the db only once do:

var itemsInCart = (from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
                  ).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();

The extra round-trip saved is worth it :)

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

I had to do 'setValue' and 'update' in order to get it to work completely

$('#datepicker').datepicker('setValue', '2014-01-29').datepicker('update');

Round a floating-point number down to the nearest integer?

Just make round(x-0.5) this will always return the next rounded down Integer value of your Float. You can also easily round up by do round(x+0.5)

Check if a row exists using old mysql_* API

This ought to do the trick: just limit the result to 1 row; if a row comes back the $lectureName is Assigned, otherwise it's Available.

function checkLectureStatus($lectureName)
{
    $con = connectvar();
    mysql_select_db("mydatabase", $con);
    $result = mysql_query(
        "SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");

    if(mysql_fetch_array($result) !== false)
        return 'Assigned';
    return 'Available';
}

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

jQuery count child elements

$('#selected ul').children().length;

or even better

 $('#selected li').length;

Why should I use a container div in HTML?

THis method allows you to have more flexibility of styling your entire content. Effectivly creating two containers that you can style. THe HTML Body tag which serves as your background, and the div with an id of container which contains your content.

This then allows you to position your content within the page, while styling a background or other effects without issue. THink of it as a "Frame" for the content.

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

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

read_csv(..., nrows=999999)

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

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

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

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

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

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Fastest way of finding differences between two files in unix?

You could try..

comm -13 <(sort file1) <(sort file2) > file3

or

grep -Fxvf file1 file2 > file3

or

diff file1 file2 | grep "<" | sed 's/^<//g'  > file3

or

join -v 2 <(sort file1) <(sort file2) > file3

Scroll event listener javascript

Is there a js listener for when a user scrolls in a certain textbox that can be used?

DOM L3 UI Events spec gave the initial definition but is considered obsolete.

To add a single handler you can do:

  let isTicking;
  const debounce = (callback, evt) => {
    if (isTicking) return;
    requestAnimationFrame(() => {
      callback(evt);
      isTicking = false;
    });
    isTicking = true;
  };
  const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
  document.defaultView.onscroll = evt => debounce(handleScroll, evt);

For multiple handlers or, if preferable for style reasons, you may use addEventListener as opposed to assigning your handler to onscroll as shown above.

If using something like _.debounce from lodash you could probably get away with:

const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => _.debounce(() => handleScroll(evt));

Review browser compatibility and be sure to test on some actual devices before calling it done.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Uninstall / remove a Homebrew package including all its dependencies

Based on @jfmercer answer (corrections needed more than a comment).

Remove package's dependencies (does not remove package):

brew deps [FORMULA] | xargs brew remove --ignore-dependencies

Remove package:

brew remove [FORMULA]

Reinstall missing libraries:

brew missing | cut -d: -f2 | sort | uniq | xargs brew install

Tested uninstalling meld after discovering MeldMerge releases.

Check if a user has scrolled to the bottom

Try this for match condition if scroll to bottom end

if ($(this)[0].scrollHeight - $(this).scrollTop() == 
    $(this).outerHeight()) {

    //code for your custom logic

}

How do I clone a single branch in Git?

git clone --branch {branch-name} {repo-URI}

Example:

git clone --branch dev https://github.com/ann/cleaningmachine.git

What is the difference between 'my' and 'our' in Perl?

my is used for local variables, whereas our is used for global variables.

More reading over at Variable Scoping in Perl: the basics.

SQLite UPSERT / UPDATE OR INSERT

To have a pure UPSERT with no holes (for programmers) that don't relay on unique and other keys:

UPDATE players SET user_name="gil", age=32 WHERE user_name='george'; 
SELECT changes();

SELECT changes() will return the number of updates done in the last inquire. Then check if return value from changes() is 0, if so execute:

INSERT INTO players (user_name, age) VALUES ('gil', 32);