Programs & Examples On #Corpus

A corpus most commonly refers to a collection of structured text. Please consider asking your question on https://opendata.stackexchange.com, if your question is not closely related to prorgamming or you are just looking for a freely available corpus for any purpose.

How can I change the default Mysql connection timeout when connecting through python?

Do:

con.query('SET GLOBAL connect_timeout=28800')
con.query('SET GLOBAL interactive_timeout=28800')
con.query('SET GLOBAL wait_timeout=28800')

Parameter meaning (taken from MySQL Workbench in Navigator: Instance > Options File > Tab "Networking" > Section "Timeout Settings")

  • connect_timeout: Number of seconds the mysqld server waits for a connect packet before responding with 'Bad handshake'
  • interactive_timeout Number of seconds the server waits for activity on an interactive connection before closing it
  • wait_timeout Number of seconds the server waits for activity on a connection before closing it

BTW: 28800 seconds are 8 hours, so for a 10 hour execution time these values should be actually higher.

What's the main difference between int.Parse() and Convert.ToInt32

for clarification open console application, just copy below code and paste it in static void Main(string[] args) method, I hope you can understand

public  class Program
    {
        static void Main(string[] args)
        { 
            int result;
            bool status;
            string s1 = "12345";
            Console.WriteLine("input1:12345");
            string s2 = "1234.45";
            Console.WriteLine("input2:1234.45");
            string s3 = null;
            Console.WriteLine("input3:null");
            string s4 = "1234567899012345677890123456789012345667890";
            Console.WriteLine("input4:1234567899012345677890123456789012345667890");
            string s5 = string.Empty;
            Console.WriteLine("input5:String.Empty");
            Console.WriteLine();
            Console.WriteLine("--------Int.Parse Methods Outputs-------------");
            try
            {
               result = int.Parse(s1);

               Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:"+ee.Message);
            }
            try
            {
              result = int.Parse(s2);

              Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {
               result = int.Parse(s3);

               Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {
                result = int.Parse(s4);

                Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {
                 result = int.Parse(s5);

                 Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }
            Console.WriteLine();
            Console.WriteLine("--------Convert.To.Int32 Method Outputs-------------");
            try
            {

                result=  Convert.ToInt32(s1);

                Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:" + ee.Message);
            }
            try
            {

                result = Convert.ToInt32(s2);

                Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {

         result = Convert.ToInt32(s3);

         Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {

                  result = Convert.ToInt32(s4);

                  Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {

                 result = Convert.ToInt32(s5);

                 Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }

            Console.WriteLine();
            Console.WriteLine("--------TryParse Methods Outputs-------------");
            try
            {

                status = int.TryParse(s1, out result);
                Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s2, out result);
                Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s3, out result);
                Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s4, out result);
                Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {

                status = int.TryParse(s5, out result);
                Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }


            Console.Read();
        }
    }

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Go to

C:\ drive

or that drive where xampp is installed click on xampp find php and open it , there you find php.ini folder open php.ini file with notepad and find upload_max_filesize and post_max_size in both "up and down find option",change both values to 1000M

How to store token in Local or Session Storage in Angular 2?

Adding onto Bojan Kogoj's answer:

In your app.module.ts, add a new provider for storage.

@NgModule({
   providers: [
      { provide: Storage, useValue: localStorage }
   ],
   imports:[],
   declarations:[]
})

And then you can use DI to get it wherever you need it.

 @Injectable({
    providedIn:'root'
 })
 export class StateService {
    constructor(private storage: Storage) { }
 }

Get output parameter value in ADO.NET

Not my code, but a good example i think

source: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624

using System; 
using System.Data; 
using System.Data.SqlClient; 


class OutputParams 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 

    using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;")) 
    { 
        SqlCommand cmd = new SqlCommand("CustOrderOne", cn); 
        cmd.CommandType=CommandType.StoredProcedure ; 

        SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ; 
        parm.Value="ALFKI"; 
        parm.Direction =ParameterDirection.Input ; 
        cmd.Parameters.Add(parm); 

        SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar); 
        parm2.Size=50; 
        parm2.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm2); 

        SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int); 
        parm3.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm3);

        cn.Open(); 
        cmd.ExecuteNonQuery(); 
        cn.Close(); 

        Console.WriteLine(cmd.Parameters["@ProductName"].Value); 
        Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
        Console.ReadLine(); 
    } 
} 

Spring Boot Configure and Use Two DataSources

I also had to setup connection to 2 datasources from Spring Boot application, and it was not easy - the solution mentioned in the Spring Boot documentation didn't work. After a long digging through the internet I made it work and the main idea was taken from this article and bunch of other places.

The following solution is written in Kotlin and works with Spring Boot 2.1.3 and Hibernate Core 5.3.7. Main issue was that it was not enough just to setup different DataSource configs, but it was also necessary to configure EntityManagerFactory and TransactionManager for both databases.

Here is config for the first (Primary) database:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "firstDbEntityManagerFactory",
    transactionManagerRef = "firstDbTransactionManager",
    basePackages = ["org.path.to.firstDb.domain"]
)
@EnableTransactionManagement
class FirstDbConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.firstDb")
    fun firstDbDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Primary
    @Bean(name = ["firstDbEntityManagerFactory"])
    fun firstDbEntityManagerFactory(
        builder: EntityManagerFactoryBuilder,
        @Qualifier("firstDbDataSource") dataSource: DataSource
    ): LocalContainerEntityManagerFactoryBean {
        return builder
            .dataSource(dataSource)
            .packages(SomeEntity::class.java)
            .persistenceUnit("firstDb")
            // Following is the optional configuration for naming strategy
            .properties(
                singletonMap(
                    "hibernate.naming.physical-strategy",
                    "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"
                )
            )
            .build()
    }

    @Primary
    @Bean(name = ["firstDbTransactionManager"])
    fun firstDbTransactionManager(
        @Qualifier("firstDbEntityManagerFactory") firstDbEntityManagerFactory: EntityManagerFactory
    ): PlatformTransactionManager {
        return JpaTransactionManager(firstDbEntityManagerFactory)
    }
}

And this is config for second database:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "secondDbEntityManagerFactory",
    transactionManagerRef = "secondDbTransactionManager",
    basePackages = ["org.path.to.secondDb.domain"]
)
@EnableTransactionManagement
class SecondDbConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.secondDb")
    fun secondDbDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Bean(name = ["secondDbEntityManagerFactory"])
    fun secondDbEntityManagerFactory(
        builder: EntityManagerFactoryBuilder,
        @Qualifier("secondDbDataSource") dataSource: DataSource
    ): LocalContainerEntityManagerFactoryBean {
        return builder
            .dataSource(dataSource)
            .packages(EntityFromSecondDb::class.java)
            .persistenceUnit("secondDb")
            .build()
    }

    @Bean(name = ["secondDbTransactionManager"])
    fun secondDbTransactionManager(
        @Qualifier("secondDbEntityManagerFactory") secondDbEntityManagerFactory: EntityManagerFactory
    ): PlatformTransactionManager {
        return JpaTransactionManager(secondDbEntityManagerFactory)
    }
}

The properties for datasources are like this:

spring.datasource.firstDb.jdbc-url=
spring.datasource.firstDb.username=
spring.datasource.firstDb.password=

spring.datasource.secondDb.jdbc-url=
spring.datasource.secondDb.username=
spring.datasource.secondDb.password=

Issue with properties was that I had to define jdbc-url instead of url because otherwise I had an exception.

p.s. Also you might have different naming schemes in your databases, which was the case for me. Since Hibernate 5 does not support all previous naming schemes, I had to use solution from this answer - maybe it will also help someone as well.

Custom Python list sorting

This does not work in Python 3.

You can use functools cmp_to_key to have old-style comparison functions work though.

from functools import cmp_to_key

def cmp_items(a, b):
    if a.foo > b.foo:
        return 1
    elif a.foo == b.foo:
        return 0
    else:
        return -1

cmp_items_py3 = cmp_to_key(cmp_items)

alist.sort(cmp_items_py3)

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Aha! I beat this problem! My god, it was a beast for someone like me with limited IIS experience. I really thought I was going to be spending all weekend fixing it.

Here's the solution for anyone else who ever comes this evil problem.

First thing to be aware of: If you're hoping this is your solution, make sure that you have the same Error Code (0x8007000d) and Config Source (-1: 0:). If not, this isn't your solution.

Next thing to be aware of: AJAX is not properly installed in your web.config!

Fix that by following this guide:
http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx

Then, install the AJAX 1.0 extensions on your production server, from this link:

http://www.asp.net/ajax/downloads/archive/
Update: Microsoft seems to have removed the above page :(

That's it!

What's the difference between compiled and interpreted language?

Java and JavaScript are a fairly bad example to demonstrate this difference, because both are interpreted languages. Java (interpreted) and C (or C++) (compiled) might have been a better example.

Why the striked-through text? As this answer correctly points out, interpreted/compiled is about a concrete implementation of a language, not about the language per se. While statements like "C is a compiled language" are generally true, there's nothing to stop someone from writing a C language interpreter. In fact, interpreters for C do exist.

Basically, compiled code can be executed directly by the computer's CPU. That is, the executable code is specified in the CPU's "native" language (assembly language).

The code of interpreted languages however must be translated at run-time from any format to CPU machine instructions. This translation is done by an interpreter.

Another way of putting it is that interpreted languages are code is translated to machine instructions step-by-step while the program is being executed, while compiled languages have code has been translated before program execution.

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

What is the best open source help ticket system?

There is good information on Wikipedia at

Comparison of Issue Tracking Systems

Personally, I'm fond of Trac, which has the capability of integrating with subversion, so when you check in a file, if you say something like...

$ svn ci -m "automatically fix any broken dates in the input.  fixes #87"

....then Trac will automatically add this comment and close bug #87 for you.

how to check the version of jar file?

If you have winrar, open the jar with winrar, double-click to open folder META-INF. Extract MANIFEST.MF and CHANGES files to any location (say desktop).

Open the extracted files in a text editor: You will see Implementation-Version or release version.

How do I increase the RAM and set up host-only networking in Vagrant?

Since Vagrant 1.1 customize option is getting VirtualBox-specific.

The modern way to do it is:

config.vm.provider :virtualbox do |vb|
  vb.customize ["modifyvm", :id, "--memory", "256"]
end

Disable future dates after today in Jquery Ui Datepicker

datepicker doesnot have a maxDate as an option.I used this endDate option.It worked well.

> $('.demo-calendar-default').datepicker({
>                 autoHide: true,
>                 zIndex: 2048,
>                 format: 'dd/mm/yyyy',
>                 endDate: new Date()
>             });

Scrollview vertical and horizontal in android

Mixing some of the suggestions above, and was able to get a good solution:

Custom ScrollView:

package com.scrollable.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

public class VScroll extends ScrollView {

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

    public VScroll(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VScroll(Context context) {
        super(context);
    }

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

Custom HorizontalScrollView:

package com.scrollable.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;

public class HScroll extends HorizontalScrollView {

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

    public HScroll(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HScroll(Context context) {
        super(context);
    }

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

the ScrollableImageActivity:

package com.scrollable.view;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;

public class ScrollableImageActivity extends Activity {

    private float mx, my;
    private float curX, curY;

    private ScrollView vScroll;
    private HorizontalScrollView hScroll;

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

        vScroll = (ScrollView) findViewById(R.id.vScroll);
        hScroll = (HorizontalScrollView) findViewById(R.id.hScroll);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float curX, curY;

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                mx = event.getX();
                my = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                curX = event.getX();
                curY = event.getY();
                vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                mx = curX;
                my = curY;
                break;
            case MotionEvent.ACTION_UP:
                curX = event.getX();
                curY = event.getY();
                vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
                break;
        }

        return true;
    }

}

the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <com.scrollable.view.VScroll android:layout_height="fill_parent"
        android:layout_width="fill_parent" android:id="@+id/vScroll">
        <com.scrollable.view.HScroll android:id="@+id/hScroll"
            android:layout_width="fill_parent" android:layout_height="fill_parent">
            <ImageView android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/bg"></ImageView>
        </com.scrollable.view.HScroll>
    </com.scrollable.view.VScroll>

</LinearLayout>

How do I read any request header in PHP

Pass a header name to this function to get its value without using for loop. Returns null if header not found.

/**
 * @var string $headerName case insensitive header name
 *
 * @return string|null header value or null if not found
 */
function get_header($headerName)
{
    $headers = getallheaders();
    return isset($headerName) ? $headers[$headerName] : null;
}

Note: this works only with Apache server, see: http://php.net/manual/en/function.getallheaders.php

Note: this function will process and load all of the headers to the memory and it's less performant than a for loop.

How to hide a navigation bar from first ViewController in Swift?

You can unhide navigationController in viewWillDisappear

override func viewWillDisappear(animated: Bool)
{
    super.viewWillDisappear(animated)
    self.navigationController?.isNavigationBarHidden = false
}

Swift 3

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    self.navigationController?.setNavigationBarHidden(false, animated: animated)
}

Declaring static constants in ES6 classes?

I did this.

class Circle
{
    constuctor(radius)
    {
        this.radius = radius;
    }
    static get PI()
    {
        return 3.14159;
    }
}

The value of PI is protected from being changed since it is a value being returned from a function. You can access it via Circle.PI. Any attempt to assign to it is simply dropped on the floor in a manner similar to an attempt to assign to a string character via [].

How to find the kafka version in linux

Kafka 2.0 have the fix(KIP-278) for it:

kafka-topics.sh --version

Using confluent utility:

Kakfa version check can be done with confluent utility which comes by default with Confluent platform(confluent utility can be added to cluster separately as well - credits cricket_007).

${confluent.home}/bin/confluent version kafka

Checking the version of other Confluent platform components like ksql schema-registry and connect

[confluent-4.1.0]$ ./bin/confluent version kafka
1.1.0-cp1

[confluent-4.1.0]$ ./bin/confluent version connect
4.1.0

[confluent-4.1.0]$ ./bin/confluent version schema-registry
4.1.0

[confluent-4.1.0]$ ./bin/confluent version ksql-server
4.1.0

How do you append an int to a string in C++?

There are a few options, and which one you want depends on the context.

The simplest way is

std::cout << text << i;

or if you want this on a single line

std::cout << text << i << endl;

If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done.

If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following:

Player 1
Player 2

If you are unlucky you might get something like the following

Player Player 2
1

The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:

std::cout << text;
std::cout << i;
std::cout << endl;

If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:

printf("Player %d\n", i);

Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.

For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

How to integrate SAP Crystal Reports in Visual Studio 2017

I had exactly the same problem with my VS 2013 solutions when I install VS 2017 and Crystal Reports SP21. In fact it's because VS does not necessarily convert the solution in the first launch.

Once you have installed Crystal Report SP 21, make sure that VS 2017 upgrade your solution : a window must appear "SAP Crystal Reports, version for Visual" with a radio button "Convert the solution".

Screenshot in french :

enter image description here

When I used the menu "File / Open / Project/Solution", the conversion was not done.

I have to do that :

  1. Add VS 2017 on the tasks bar
  2. Run VS 2017 and Open the solution with File menu
  3. Try to build the project, errors appear with Crystal Reports
  4. Close VS 2017
  5. Right click on VS 2017 shortcur in then tasks bar and open the solution directly
  6. The conversion run this time, you can open .rpt and the solution build without error.

get data from mysql database to use in javascript

You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

How to compare timestamp dates with date-only parameter in MySQL?

When I read your question, I thought your were on Oracle DB until I saw the tag 'MySQL'. Anyway, for people working with Oracle here is the way:

SELECT *
FROM table
where timestamp = to_timestamp('21.08.2017 09:31:57', 'dd-mm-yyyy hh24:mi:ss');

How to check if the docker engine and a docker container are running?

You can also check if a particular docker container is running or not using following command:

docker inspect postgres | grep "Running"

This command will check if for example my postgres container is running or not and will return output as "Running": true

Hope this helps.

Resizing image in Java

We're doing this to create thumbnails of images:

  BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
  Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
  tGraphics2D.setBackground( Color.WHITE );
  tGraphics2D.setPaint( Color.WHITE );
  tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
  tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
  tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled

  ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file

getApplication() vs. getApplicationContext()

Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.

Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).

So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).

Why does getApplicationContext() exist in the first place ?

getApplication() is only available in the Activity class and the Service class, whereas getApplicationContext() is declared in the Context class.

That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext(). Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.

When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext() delegates it's call to baseContext.getApplicationContext().

One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

I know this is not an exact and precise answer, but still, does that answer your question?

Convert varchar to float IF ISNUMERIC

I found this very annoying bug while converting EmployeeID values with ISNUMERIC:

SELECT DISTINCT [EmployeeID],
ISNUMERIC(ISNULL([EmployeeID], '')) AS [IsNumericResult],

CASE WHEN COALESCE(NULLIF(tmpImport.[EmployeeID], ''), 'Z')
    LIKE '%[^0-9]%' THEN 'NonNumeric' ELSE 'Numeric'
END AS [IsDigitsResult]
FROM [MyTable]

This returns:

EmployeeID IsNumericResult MyCustomResult
---------- --------------- --------------
           0               NonNumeric
00000000c  0               NonNumeric
00D026858  1               NonNumeric

(3 row(s) affected)

Hope this helps!

error: command 'gcc' failed with exit status 1 while installing eventlet

On MacOS I also had problems trying to install fbprophet which had gcc as one of its dependencies.

After trying several steps as recommended by @Boris the command below from the Facebook Prophet project page worked for me in the end.

conda install -c conda-forge fbprophet

It installed all the needed dependencies for fbprophet. Make sure you have anaconda installed.

Update Eclipse with Android development tools v. 23

I found these instructions in a comment.

Download the newest version of ADT and use your existing workspace. This is actually the least pain-full upgrade you'll ever do. It didn't mess with the .android folder so I still had my original debug key. Only things missing were a couple of add ons I hardly ever use and they are easily installed into the new version.

Note don't install into your existing adt folder create a new folder so you can still fall back if the new install doesn't work.

Object Dump JavaScript

Just use:

console.dir(object);

you will get a nice clickable object representation. Works in Chrome and Firefox

How to read a text file from server using JavaScript?

Just a small point, I see some of the answers using innerhtml. I have toyed with a similar idea but decided not too, In the latest version react version the same process is now called dangerouslyinnerhtml, as you are giving your client a way into your OS by presenting html in the app. This could lead to various attacks as well as SQL injection attempts

SQL Server convert string to datetime

UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)

For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

Getting session value in javascript

You can access your session variable like '<%= Session["VariableName"]%>'

the text in single quotes will give session value. 1)

<script>
var session ='<%= Session["VariableName"]%>'
</script>

2) you can take a hidden field and assign value at server;

hiddenfield.value= session["xyz"].tostring();

//and in script you access the hiddenfield  like

alert(document.getElementbyId("hiddenfield").value);

How to convert list to string

>>> L = [1,2,3]       
>>> " ".join(str(x) for x in L)
'1 2 3'

What is a semaphore?

I've created the visualization which should help to understand the idea. Semaphore controls access to a common resource in a multithreading environment. enter image description here

ExecutorService executor = Executors.newFixedThreadPool(7);

Semaphore semaphore = new Semaphore(4);

Runnable longRunningTask = () -> {
    boolean permit = false;
    try {
        permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
        if (permit) {
            System.out.println("Semaphore acquired");
            Thread.sleep(5);
        } else {
            System.out.println("Could not acquire semaphore");
        }
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    } finally {
        if (permit) {
            semaphore.release();
        }
    }
};

// execute tasks
for (int j = 0; j < 10; j++) {
    executor.submit(longRunningTask);
}
executor.shutdown();

Output

Semaphore acquired
Semaphore acquired
Semaphore acquired
Semaphore acquired
Could not acquire semaphore
Could not acquire semaphore
Could not acquire semaphore

Sample code from the article

Merge or combine by rownames

cbind.fill <- function(x, y){
  xrn <- rownames(x)
  yrn <- rownames(y)
  rn <- union(xrn, yrn)
  xcn <- colnames(x)
  ycn <- colnames(y)
  if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn)) 
    stop("NULL rownames or colnames")
  z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
  rownames(z) <- rn
  colnames(z) <- c(xcn, ycn)
  idx <- match(rn, xrn)
  z[!is.na(idx), 1:length(xcn)] <- x[na.omit(idx),]
  idy <- match(rn, yrn)
  z[!is.na(idy), length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]
  return(z)
}

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

If you use the credential file at ~/.aws/credentials and use the default profile as below:

[default]
aws_access_key_id=<your access key>
aws_secret_access_key=<your secret access key>

You do not need to use BasicAWSCredential or AWSCredentialsProvider. The SDK can pick up the credentials from the default profile, just by initializing the client object with the default constructor. Example below:

AmazonEC2Client ec2Client = new AmazonEC2Client();

In addition sometime you would need to initialize the client with the ClientConfiguration to provide proxy settings etc. Example below.

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("proxyhost");
clientConfiguration.setProxyPort(proxyport);
AmazonEC2Client ec2Client = new AmazonEC2Client(clientConfiguration);

Force sidebar height 100% using CSS (with a sticky bottom image)?

I have run into this issue several times on different projects, but I have found a solution that works for me. You have to use four div tags - one that contains the sidebar, the main content, and a footer.

First, style the elements in your stylesheet:

#container {
width: 100%;
background: #FFFAF0;
}

.content {
width: 950px;
float: right;
padding: 10px;
height: 100%;
background: #FFFAF0;
}

.sidebar {
width: 220px;
float: left;
height: 100%;
padding: 5px;
background: #FFFAF0;
}

#footer {
clear:both;
background:#FFFAF0;
}

You can edit the different elements however you want to, just be sure you dont change the footer property "clear:both" - this is very important to leave in.

Then, simply set up your web page like this:

<div id=”container”>
<div class=”sidebar”></div>
<div class=”content”></div>
<div id=”footer”></div>
</div>

I wrote a more in-depth blog post about this at http://blog.thelibzter.com/how-to-make-a-sidebar-extend-the-entire-height-of-its-container. Please let me know if you have any questions. Hope this helps!

Adding Multiple Values in ArrayList at a single index

@Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:

ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();

for(int i = 0; i < first.size(); i++) {
      third.add(first.get(i));
      third.add(second.get(i));
}

Edit: If you have those values on your list that below:

List<double[]> values = new ArrayList<double[]>(2);

what you want to do is combine them, right? You can try something like this: (I assume that both array are same sized, otherwise you need to use two for statement)

ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
    yourArray.add(values.get(0)[i]);
    yourArray.add(values.get(1)[i]);
}

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

In my case, it was related to the node version.

My project was using 12.18.3 but I was on 14.5.0

So npm rebuild node-sass didn't solve the issue on the wrong node version(14.5.0).

I switched to the correct version(12.18.3) so it worked.

Ruby array to string conversion

> puts "'"+['12','34','35','231']*"','"+"'"
'12','34','35','231'

> puts ['12','34','35','231'].inspect[1...-1].gsub('"',"'")
'12', '34', '35', '231'

NoSQL Use Case Scenarios or WHEN to use NoSQL

I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)

  1. Easy to scale horizontally by just adding more nodes.

  2. Query on large data set

    Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.

  3. Disk I/O bottleneck

    If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.

How do I make the first letter of a string uppercase in JavaScript?

It's always better to handle these kinds of stuff using CSS first, in general, if you can solve something using CSS, go for that first, then try JavaScript to solve your problems, so in this case try using :first-letter in CSS and apply text-transform:capitalize;

So try creating a class for that, so you can use it globally, for example: .first-letter-uppercase and add something like below in your CSS:

.first-letter-uppercase:first-letter {
    text-transform:capitalize;
}

Also the alternative option is JavaScript, so the best gonna be something like this:

function capitalizeTxt(txt) {
  return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}

and call it like:

capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html');  // return '/index.html'
capitalizeTxt('alireza');  // return 'Alireza'

If you want to reuse it over and over, it's better attach it to javascript native String, so something like below:

String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

and call it as below:

'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt();  // return '/index.html'
'alireza'.capitalizeTxt();  // return 'Alireza'

Getting each individual digit from a whole integer

//this can be easily understandable for beginners     
int score=12344534;
int div;
for (div = 1; div <= score; div *= 10)
{

}
/*for (div = 1; div <= score; div *= 10); for loop with semicolon or empty body is same*/
while(score>0)
{
    div /= 10;
    printf("%d\n`enter code here`", score / div);
    score %= div;
}

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

If you use this syntax:

<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>

Angular will render something like:

 <div ng-id="object-1"></div>

However this syntax:

<div id="{{ 'object-' + $index }}"></div>

will generate something like:

<div id="object-1"></div>

Creating a select box with a search option

This simple code worked for me

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<input list="brow">_x000D_
<datalist id="brow">_x000D_
  <option value="Internet Explorer">_x000D_
  <option value="Firefox">_x000D_
  <option value="Chrome">_x000D_
  <option value="Opera">_x000D_
  <option value="Safari">_x000D_
</datalist>  _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Incase you need to use only select tag use Selectize Js. It has all options we require .Please Try It Demo using Selectize Js

Unable to load DLL 'SQLite.Interop.dll'

I don't know if it's a good answer, but I was able to solve this problem by running my application under an AppDomain with an identity of "Local System".

Centering a canvas

This will center the canvas horizontally:

#canvas-container {
   width: 100%;
   text-align:center;
}

canvas {
   display: inline;
}

HTML:

<div id="canvas-container">
   <canvas>Your browser doesn't support canvas</canvas>
</div>

Converting HTML to Excel?

We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Your import has a subtle error:

import java.awt.List;

It should be:

import java.util.List;

The problem is that both awt and Java's util package provide a class called List. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList extends java.util.List, not java.awt.List so if it wasn't for the generics, it would have still been a problem.

Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.

import org.omg.DynamicAny.NameValuePair;

should be

import org.apache.http.NameValuePair

nameValuePairs now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity, which is List<? extends NameValuePair>, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair did not extend org.apache.http.NameValuePair and the shortened type name NameValuePair evaluated to org.omg... in your file, but org.apache... in their code.

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

By mistake I added the compile com.google.android.gms:play-services:5.+ in dependencies in build script block. You should add it in the second dependency block. make changes->synch project with gradle.

What does "Error: object '<myvariable>' not found" mean?

While executing multiple lines of code in R, you need to first select all the lines of code and then click on "Run". This error usually comes up when we don't select our statements and click on "Run".

Display an image with Python

Your first suggestion works for me

from IPython.display import display, Image
display(Image(filename='path/to/image.jpg'))

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

I just had the same problem in asp.net core VS2019

This solved it:

Install-Package Microsoft.EntityFrameworkCoreInstall-Package
Install-Package Microsoft.EntityFrameworkCore.Tools

Don't forget to set default project in Package Manager Console to your database project in case it differs.

While executing the migrations the default project also seems to play a role. At a later step it helped to install this to my main startup project (not the EF database project):

Install-Package Microsoft.EntityFrameworkCore.Design

Refresh Page C# ASP.NET

Depending on what exactly you require, a Server.Transfer might be a resource-cheaper alternative to Response.Redirect. More information is in Server.Transfer Vs. Response.Redirect.

Full Page <iframe>

Put this in your CSS.

iframe {
  width: 100%;
  height: 100vh;
}

How to pass a value from one jsp to another jsp page?

Use sessions

On your search.jsp

Put your scard in sessions using session.setAttribute("scard","scard")

//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.

And in your next page you retrieve it using session.getAttribute("scard")

UPDATE

<input type="text" value="<%=session.getAttribute("scard")%>"/>

How to add a footer in ListView?

If the ListView is a child of the ListActivity:

getListView().addFooterView(
    getLayoutInflater().inflate(R.layout.footer_view, null)
);

(inside onCreate())

Differences between fork and exec

enter image description herefork():

It creates a copy of running process. The running process is called parent process & newly created process is called child process. The way to differentiate the two is by looking at the returned value:

  1. fork() returns the process identifier (pid) of the child process in the parent

  2. fork() returns 0 in the child.

exec():

It initiates a new process within a process. It loads a new program into the current process, replacing the existing one.

fork() + exec():

When launching a new program is to firstly fork(), creating a new process, and then exec() (i.e. load into memory and execute) the program binary it is supposed to run.

int main( void ) 
{
    int pid = fork();
    if ( pid == 0 ) 
    {
        execvp( "find", argv );
    }

    //Put the parent to sleep for 2 sec,let the child finished executing 
    wait( 2 );

    return 0;
}

Visual Studio Code Search and Replace with Regular Expressions

Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.

How to get progress from XMLHttpRequest

One of the most promising approaches seems to be opening a second communication channel back to the server to ask it how much of the transfer has been completed.

Rendering React Components from Array of Objects

You can map the list of stations to ReactElements.

With React >= 16, it is possible to return multiple elements from the same component without needing an extra html element wrapper. Since 16.2, there is a new syntax <> to create fragments. If this does not work or is not supported by your IDE, you can use <React.Fragment> instead. Between 16.0 and 16.2, you can use a very simple polyfill for fragments.

Try the following

// Modern syntax >= React 16.2.0
const Test = ({stations}) => (
  <>
    {stations.map(station => (
      <div className="station" key={station.call}>{station.call}</div>
    ))}
  </>
); 

// Modern syntax < React 16.2.0
// You need to wrap in an extra element like div here

const Test = ({stations}) => (
  <div>
    {stations.map(station => (
      <div className="station" key={station.call}>{station.call}</div>
    ))}
  </div>
); 

// old syntax
var Test = React.createClass({
    render: function() {
        var stationComponents = this.props.stations.map(function(station) {
            return <div className="station" key={station.call}>{station.call}</div>;
        });
        return <div>{stationComponents}</div>;
    }
});

var stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
]; 

ReactDOM.render(
  <div>
    <Test stations={stations} />
  </div>,
  document.getElementById('container')
);

Don't forget the key attribute!

https://jsfiddle.net/69z2wepo/14377/

HTML tag <a> want to add both href and onclick working

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

Calling Scalar-valued Functions in SQL

That syntax works fine for me:

CREATE FUNCTION dbo.test_func
(@in varchar(20))
RETURNS INT
AS
BEGIN
    RETURN 1
END
GO

SELECT dbo.test_func('blah')

Are you sure that the function exists as a function and under the dbo schema?

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

?: operator (the 'Elvis operator') in PHP

It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.

In pseudocode,

foo = bar ?: baz;

roughly resolves to

foo = bar ? bar : baz;

or

if (bar) {
    foo = bar;
} else {
    foo = baz;
}

with the difference that bar will only be evaluated once.

You can also use this to do a "self-check" of foo as demonstrated in the code example you posted:

foo = foo ?: bar;

This will assign bar to foo if foo is null or falsey, else it will leave foo unchanged.

Some more examples:

<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>

By the way, it's called the Elvis operator.

Elvis operator

How to resize JLabel ImageIcon?

One (quick & dirty) way to resize images it to use HTML & specify the new size in the image element. This even works for animated images with transparency.

Row Offset in SQL Server

SELECT TOP 75 * FROM MyTable
EXCEPT 
SELECT TOP 50 * FROM MyTable

Update multiple rows using select statement

Run a select to make sure it is what you want

SELECT t1.value AS NEWVALUEFROMTABLE1,t2.value AS OLDVALUETABLE2,*
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Update

UPDATE Table2
SET Value = t1.Value
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Also, consider using BEGIN TRAN so you can roll it back if needed, but make sure you COMMIT it when you are satisfied.

How do I edit $PATH (.bash_profile) on OSX?

If you are using MAC Catalina you need to update the .zshrc file instead of .bash_profile or .profile

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

Your not applying Date formator. rather you are just parsing the date. to get output in this format

yyyy-MM-dd HH:mm:ss.SSSSSS

we have to use format() method here is full example:- Here is full example:- it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {

public static void main(String args[]) throws ParseException {

    SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
     Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");  
    System.out.println(thisDate);
    System.out.println("----------------------------"); 
    System.out.println("After applying formating :");
    String strDateOutput = changeFormat.format(temp);
    System.out.println(strDateOutput);

}

}

Working example screen

Retrieve column values of the selected row of a multicolumn Access listbox

Use listboxControl.Column(intColumn,intRow). Both Column and Row are zero-based.

Better/Faster to Loop through set or list?

set is what you want, so you should use set. Trying to be clever introduces subtle bugs like forgetting to add one tomax(mylist)! Code defensively. Worry about what's faster when you determine that it is too slow.

range(min(mylist), max(mylist) + 1)  # <-- don't forget to add 1

Executing <script> elements inserted with .innerHTML

It's easier to use jquery $(parent).html(code) instead of parent.innerHTML = code:

var oldDocumentWrite = document.write;
var oldDocumentWriteln = document.writeln;
try {
    document.write = function(code) {
        $(parent).append(code);
    }
    document.writeln = function(code) {
        document.write(code + "<br/>");
    }
    $(parent).html(html); 
} finally {
    $(window).load(function() {
        document.write = oldDocumentWrite
        document.writeln = oldDocumentWriteln
    })
}

This also works with scripts that use document.write and scripts loaded via src attribute. Unfortunately even this doesn't work with Google AdSense scripts.

How should I declare default values for instance variables in Python?

Using class members for default values of instance variables is not a good idea, and it's the first time I've seen this idea mentioned at all. It works in your example, but it may fail in a lot of cases. E.g., if the value is mutable, mutating it on an unmodified instance will alter the default:

>>> class c:
...     l = []
... 
>>> x = c()
>>> y = c()
>>> x.l
[]
>>> y.l
[]
>>> x.l.append(10)
>>> y.l
[10]
>>> c.l
[10]

Python Socket Multiple Clients

This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.

#!usr/bin/python
from thread import *
import socket
import sys

def clientthread(conn):
    buffer=""
    while True:
        data = conn.recv(8192)
        buffer+=data
        print buffer
    #conn.sendall(reply)
    conn.close()

def main():
    try:
        host = '192.168.1.3'
        port = 6666
        tot_socket = 26
        list_sock = []
        for i in range(tot_socket):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            s.bind((host, port+i))
            s.listen(10)
            list_sock.append(s)
            print "[*] Server listening on %s %d" %(host, (port+i))

        while 1:
            for j in range(len(list_sock)):
                conn, addr = list_sock[j].accept()
                print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
                start_new_thread(clientthread ,(conn,))
        s.close()

    except KeyboardInterrupt as msg:
        sys.exit(0)


if __name__ == "__main__":
    main()

Align an element to bottom with flexbox

When setting your display to flex, you could simply use the flex property to mark which content can grow and which content cannot.

Flex property

_x000D_
_x000D_
div.content {_x000D_
 height: 300px;_x000D_
 display: flex;_x000D_
 flex-direction: column;_x000D_
}_x000D_
_x000D_
div.up {_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
div.down {_x000D_
  flex: none;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="up">_x000D_
    <h1>heading 1</h1>_x000D_
    <h2>heading 2</h2>_x000D_
    <p>Some more or less text</p>_x000D_
  </div>_x000D_
_x000D_
  <div class="down">_x000D_
    <a href="/" class="button">Click me</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Unloading classes in java?

The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.

One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server.

This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it.

If you don't want to use OSGI, one possible implementation could be to use one instance of JarClassloader class for every JAR file.

And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own.

If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class.

I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well.

Android 6.0 multiple permissions

Use helper like this (permissions names do not matter).

public class MyPermission {

private static final int PERMISSION_REQUEST_ALL = 127;
private MainActivity mMainActivity;

MyPermission(MainActivity mainActivity) {
    mMainActivity = mainActivity;
}

public static boolean hasPermission(String permission, Context context) {
    if (isNewPermissionModel()) {
        return (ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED);
    }
    return true;
}

private static boolean hasPermissions(Context context, String... permissions) {
    if (isNewPermissionModel() && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

private static boolean shouldShowRationale(Activity activity, String permission) {
    return isNewPermissionModel() && ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
}

private static boolean isNewPermissionModel() {
    return VERSION.SDK_INT > VERSION_CODES.LOLLIPOP_MR1;
}


/**
 * check all permissions
 */
void checkAll() {
    //check dangerous permissions, make request if need (Android will ask only for the ones it needs)
    String[] PERMISSIONS = {
            permission.READ_CALENDAR,           
            permission.ACCESS_COARSE_LOCATION   
    };

    if (!hasPermissions(mMainActivity, PERMISSIONS)) {
        ActivityCompat.requestPermissions(mMainActivity, PERMISSIONS, PERMISSION_REQUEST_ALL);
    }
}

void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == PERMISSION_REQUEST_ALL) {
        if (grantResults.length > 0) {
            //for not granted
            for (int i = 0; i < permissions.length; i++) {

                if (permissions[i].equals(permission.READ_CALENDAR)) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        smartRequestPermissions(permission.READ_CALENDAR, R.string.permission_required_dialog_read_calendar);
                    }
                } else if (permissions[i].equals(permission.ACCESS_COARSE_LOCATION)) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        smartRequestPermissions(permission.ACCESS_COARSE_LOCATION, R.string.permission_required_dialog_access_coarse_location);
                    }
                }

            }
        }
    }
}

private void smartRequestPermissions(final String permissionName, int permissionRequiredDialog) {
    if (shouldShowRationale(mMainActivity, permissionName)) {// If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false.

        //Show an explanation to the user with action
        mMainActivity.mSnackProgressBarManager.show(
                new SnackProgressBar(
                        SnackProgressBar.TYPE_ACTION, mMainActivity.getString(permissionRequiredDialog)
                )
                        .setAction("OK", new OnActionClickListener() {
                            @Override
                            public void onActionClick() {
                                checkAll();
                            }
                        })
                        .setSwipeToDismiss(true).setAllowUserInput(true)
                , MainActivity.SNACKBAR_WARNING_DURATION
        );

    } // else do nothing
}

}

How to access to a child method from the parent in vue.js

Ref and event bus both has issues when your control render is affected by v-if. So, I decided to go with a simpler method.

The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.

(Borrowing some code from Desmond Lua's answer)

Parent component code:

import ChildComponent from './components/ChildComponent'

new Vue({
  el: '#app',
  data: {
    item: {},
    childMethodsQueue: [],
  },
  template: `
  <div>
     <ChildComponent :item="item" :methods-queue="childMethodsQueue" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
    }
  },
  components: { ChildComponent },
})

This is code for ChildComponent

<template>
 ...
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    methodsQueue: { type: Array },
  },
  watch: {
    methodsQueue: function () {
      this.processMethodsQueue()
    },
  },
  mounted() {
    this.processMethodsQueue()
  },
  methods: {
    save() {
        console.log("Child saved...")
    },
    processMethodsQueue() {
      if (!this.methodsQueue) return
      let len = this.methodsQueue.length
      for (let i = 0; i < len; i++) {
        let method = this.methodsQueue.shift()
        this[method.name](method.params)
      }
    },
  },
}
</script>

And there is a lot of room for improvement like moving processMethodsQueue to a mixin...

Hashset vs Treeset

The reason why most use HashSet is that the operations are (on average) O(1) instead of O(log n). If the set contains standard items you will not be "messing around with hash functions" as that has been done for you. If the set contains custom classes, you have to implement hashCode to use HashSet (although Effective Java shows how), but if you use a TreeSet you have to make it Comparable or supply a Comparator. This can be a problem if the class does not have a particular order.

I have sometimes used TreeSet (or actually TreeMap) for very small sets/maps (< 10 items) although I have not checked to see if there is any real gain in doing so. For large sets the difference can be considerable.

Now if you need the sorted, then TreeSet is appropriate, although even then if updates are frequent and the need for a sorted result is infrequent, sometimes copying the contents to a list or an array and sorting them can be faster.

Why does python use 'else' after for and while loops?

A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.

For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.

Using the Python for...else construct you have

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")

Compare this to a method that does not use this syntactic sugar:

flagfound = False
for i in mylist:
    if i == theflag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.")

In the first case the raise is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.

Ruby function to remove all white spaces?

To remove whitespace on both sides:

Kind of like php's trim()

"   Hello  ".strip

To remove all spaces:

"   He    llo  ".gsub(/ /, "")

To remove all whitespace:

"   He\tllo  ".gsub(/\s/, "")

expected constructor, destructor, or type conversion before ‘(’ token

You are missing the std namespace reference in the cc file. You should also call nom.c_str() because there is no implicit conversion from std::string to const char * expected by ifstream's constructor.

Polygone::Polygone(std::string nom) {
    std::ifstream fichier (nom.c_str(), std::ifstream::in);
    // ...
}

How do I disable a Button in Flutter?

According to the docs:

"If the onPressed callback is null, then the button will be disabled and by default will resemble a flat button in the disabledColor."

https://docs.flutter.io/flutter/material/RaisedButton-class.html

So, you might do something like this:

    RaisedButton(
      onPressed: calculateWhetherDisabledReturnsBool() ? null : () => whatToDoOnPressed,
      child: Text('Button text')
    );

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

std::string formatting like sprintf

If you are on a system that has asprintf(3), you can easily wrap it:

#include <iostream>
#include <cstdarg>
#include <cstdio>

std::string format(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));

std::string format(const char *fmt, ...)
{
    std::string result;

    va_list ap;
    va_start(ap, fmt);

    char *tmp = 0;
    int res = vasprintf(&tmp, fmt, ap);
    va_end(ap);

    if (res != -1) {
        result = tmp;
        free(tmp);
    } else {
        // The vasprintf call failed, either do nothing and
        // fall through (will return empty string) or
        // throw an exception, if your code uses those
    }

    return result;
}

int main(int argc, char *argv[]) {
    std::string username = "you";
    std::cout << format("Hello %s! %d", username.c_str(), 123) << std::endl;
    return 0;
}

How do include paths work in Visual Studio?

To use Windows SDK successfully you need not only make include files available to your projects but also library files and executables (tools). To set all these directories you should use WinSDK Configuration Tool.

How to export SQL Server database to MySQL?

You can do this easily by using Data Loader tool. I have already done this before using this tool and found it good.

Eclipse: The declared package does not match the expected package

The build path should contain the path 'till before' that of the package name.

For eg, if the folder structure is: src/main/java/com/example/dao If the class containing the import statement'package com.example.dao' complains of the incorrect package error, then, the build path should include:src/main/java This should solve the issue.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

After installing with pip, "jupyter: command not found"

Try "pip3 install jupyter", instead of pip. It worked for me.

htaccess Access-Control-Allow-Origin

If your host not at pvn or dedicated, it's dificult to restart server.

Better solution from me, just edit your CSS file (at another domain or your subdomain) that call font eot, woff etc to your origin (your-domain or www yourdomain). it will solve your problem.

I mean, edit relative url on css to absolute url origin domain

how to get date of yesterday using php?

try this

<?php
$yesterday = date(“d.m.Y”, time()-86400);
echo $yesterday;

error: unknown type name ‘bool’

C90 does not support the boolean data type.

C99 does include it with this include:

#include <stdbool.h>

How to debug Lock wait timeout exceeded on MySQL?

Take a look at the man page of the pt-deadlock-logger utility:

brew install percona-toolkit
pt-deadlock-logger --ask-pass server_name

It extracts information from the engine innodb status mentioned above and also it can be used to create a daemon which runs every 30 seconds.

How to get current class name including package name in Java?

Use this.getClass().getCanonicalName() to get the full class name.

Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.

Should a RESTful 'PUT' operation return something

The HTTP specification (RFC 2616) has a number of recommendations that are applicable. Here is my interpretation:

  • HTTP status code 200 OK for a successful PUT of an update to an existing resource. No response body needed. (Per Section 9.6, 204 No Content is even more appropriate.)
  • HTTP status code 201 Created for a successful PUT of a new resource, with the most specific URI for the new resource returned in the Location header field and any other relevant URIs and metadata of the resource echoed in the response body. (RFC 2616 Section 10.2.2)
  • HTTP status code 409 Conflict for a PUT that is unsuccessful due to a 3rd-party modification, with a list of differences between the attempted update and the current resource in the response body. (RFC 2616 Section 10.4.10)
  • HTTP status code 400 Bad Request for an unsuccessful PUT, with natural-language text (such as English) in the response body that explains why the PUT failed. (RFC 2616 Section 10.4)

How should I store GUID in MySQL tables?

Adding to the answer by ThaBadDawg, use these handy functions (thanks to a wiser collegue of mine) to get from 36 length string back to a byte array of 16.

DELIMITER $$

CREATE FUNCTION `GuidToBinary`(
    $Data VARCHAR(36)
) RETURNS binary(16)
DETERMINISTIC
NO SQL
BEGIN
    DECLARE $Result BINARY(16) DEFAULT NULL;
    IF $Data IS NOT NULL THEN
        SET $Data = REPLACE($Data,'-','');
        SET $Result =
            CONCAT( UNHEX(SUBSTRING($Data,7,2)), UNHEX(SUBSTRING($Data,5,2)),
                    UNHEX(SUBSTRING($Data,3,2)), UNHEX(SUBSTRING($Data,1,2)),
                    UNHEX(SUBSTRING($Data,11,2)),UNHEX(SUBSTRING($Data,9,2)),
                    UNHEX(SUBSTRING($Data,15,2)),UNHEX(SUBSTRING($Data,13,2)),
                    UNHEX(SUBSTRING($Data,17,16)));
    END IF;
    RETURN $Result;
END

$$

CREATE FUNCTION `ToGuid`(
    $Data BINARY(16)
) RETURNS char(36) CHARSET utf8
DETERMINISTIC
NO SQL
BEGIN
    DECLARE $Result CHAR(36) DEFAULT NULL;
    IF $Data IS NOT NULL THEN
        SET $Result =
            CONCAT(
                HEX(SUBSTRING($Data,4,1)), HEX(SUBSTRING($Data,3,1)),
                HEX(SUBSTRING($Data,2,1)), HEX(SUBSTRING($Data,1,1)), '-', 
                HEX(SUBSTRING($Data,6,1)), HEX(SUBSTRING($Data,5,1)), '-',
                HEX(SUBSTRING($Data,8,1)), HEX(SUBSTRING($Data,7,1)), '-',
                HEX(SUBSTRING($Data,9,2)), '-', HEX(SUBSTRING($Data,11,6)));
    END IF;
    RETURN $Result;
END
$$

CHAR(16) is actually a BINARY(16), choose your preferred flavour

To follow the code better, take the example given the digit-ordered GUID below. (Illegal characters are used for illustrative purposes - each place a unique character.) The functions will transform the byte ordering to achieve a bit order for superior index clustering. The reordered guid is shown below the example.

12345678-9ABC-DEFG-HIJK-LMNOPQRSTUVW
78563412-BC9A-FGDE-HIJK-LMNOPQRSTUVW

Dashes removed:

123456789ABCDEFGHIJKLMNOPQRSTUVW
78563412BC9AFGDEHIJKLMNOPQRSTUVW

Any way to write a Windows .bat file to kill processes?

Download PSKill. Write a batch file that calls it for each process you want dead, passing in the name of the process for each.

jquery dialog save cancel button styling

check out jquery ui 1.8.5 it's available here http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js and it has the new button for dialog ui implementation

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

How to define constants in Visual C# like #define in C?

static class Constants
{
    public const int MIN_LENGTH = 5;
    public const int MIN_WIDTH  = 5; 
    public const int MIN_HEIGHT = 6;
}

// elsewhere
public CBox()
{
    length = Constants.MIN_LENGTH; 
    width  = Constants.MIN_WIDTH; 
    height = Constants.MIN_HEIGHT;  
}

Convert HTML + CSS to PDF

Perhaps you might try and use Tidy before handing the file to the converter. If one of the renderer chokes on some HTML problem (like unclosed tag), it might help it.

How to remove foreign key constraint in sql server?

ALTER TABLE [TableName] DROP CONSTRAINT [CONSTRAINT_NAME]

But, be careful man, once you do that, you may never get a chance back, and you should read some basic database book see why we need foreign key

$.focus() not working

Had this issue again just now, and believe it or not, all I had to do was close the developer tools. Apparently the Console tab has the focus priority over the page content.

LINQ with groupby and count

After calling GroupBy, you get a series of groups IEnumerable<Grouping>, where each Grouping itself exposes the Key used to create the group and also is an IEnumerable<T> of whatever items are in your original data set. You just have to call Count() on that Grouping to get the subtotal.

foreach(var line in data.GroupBy(info => info.metric)
                        .Select(group => new { 
                             Metric = group.Key, 
                             Count = group.Count() 
                        })
                        .OrderBy(x => x.Metric))
{
     Console.WriteLine("{0} {1}", line.Metric, line.Count);
}

> This was a brilliantly quick reply but I'm having a bit of an issue with the first line, specifically "data.groupby(info=>info.metric)"

I'm assuming you already have a list/array of some class that looks like

class UserInfo {
    string name;
    int metric;
    ..etc..
} 
...
List<UserInfo> data = ..... ;

When you do data.GroupBy(x => x.metric), it means "for each element x in the IEnumerable defined by data, calculate it's .metric, then group all the elements with the same metric into a Grouping and return an IEnumerable of all the resulting groups. Given your example data set of

    <DATA>           | Grouping Key (x=>x.metric) |
joe  1 01/01/2011 5  | 1
jane 0 01/02/2011 9  | 0
john 2 01/03/2011 0  | 2
jim  3 01/04/2011 1  | 3
jean 1 01/05/2011 3  | 1
jill 2 01/06/2011 5  | 2
jeb  0 01/07/2011 3  | 0
jenn 0 01/08/2011 7  | 0

it would result in the following result after the groupby:

(Group 1): [joe  1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb  0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim  3 01/04/2011 1]

Send a SMS via intent

Create the Intent like this:

   Uri uriSms = Uri.parse("smsto:1234567899");   
   Intent intentSMS = new Intent(Intent.ACTION_SENDTO, uriSms);   
   intentSMS.putExtra("sms_body", "The SMS text");   
   startActivity(intentSMS); 

Disable the postback on an <ASP:LinkButton>

Just been through this, the correct way to do it is to use:

  1. OnClientClick
  2. return false

as in the following example line of code:

<asp:LinkButton ID="lbtnNext" runat="server" OnClientClick="findAllOccurences(); return false;" />

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

Messages Using Command prompt in Windows 7

Type "msg /?" in the command prompt to get various ways of sending meessages to a user.

Type "net send /?" in the command prompt to get another variation of sending messages across.

Integrate ZXing in Android Studio

I was integrating ZXING into an Android application and there were no good sources for the input all over, I will give you a hint on what worked for me - because it turned out to be very easy.

There is a real handy git repository that provides the zxing android library project as an AAR archive.

All you have to do is add this to your build.gradle

repositories {
    jcenter()
}

dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    implementation 'com.google.zxing:core:3.2.0'
}

and Gradle does all the magic to compile the code and makes it accessible in your app.

To start the Scanner afterwards, use this class/method: From the Activity:

new IntentIntegrator(this).initiateScan(); // `this` is the current Activity

From a Fragment:

IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment
// If you're using the support library, use IntentIntegrator.forSupportFragment(this) instead.

There are several customizing options:

IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0);  // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();

They have a sample-project and are providing several integration examples:

If you already visited the link you going to see that I just copy&pasted the code from the git README. If not, go there to get some more insight and code examples.

Can't change table design in SQL Server 2008

Prevent saving changes that require table re-creation

Five swift clicks

Prevent saving changes that require table re-creation in five clicks

  1. Tools
  2. Options
  3. Designers
  4. Prevent saving changes that require table re-creation
  5. OK.

After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

Further explanation

  • By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

  • When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.

Check if string ends with one of the strings from a list

There is two ways: regular expressions and string (str) methods.

String methods are usually faster ( ~2x ).

import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)

792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)

274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

JSON parsing using Gson for Java

One way would be created a JsonObject and iterating through the parameters. For example

JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);

Then you can extract bean values like:

String fieldValue = jobj.get(fieldName).getAsString();
boolean fieldValue = jobj.get(fieldName).getAsBoolean();
int fieldValue = jobj.get(fieldName).getAsInt();

Hope this helps.

Getting the last argument passed to a shell script

#! /bin/sh

next=$1
while [ -n "${next}" ] ; do
  last=$next
  shift
  next=$1
done

echo $last

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Sort a Custom Class List<T>

look at overloaded Sort method of the List class. there are some ways to to it. one of them: your custom class has to implement IComparable interface then you cam use Sort method of the List class.

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

How can I tell what edition of SQL Server runs on the machine?

SELECT  CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
         WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
         WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
         WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
         WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
         WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
         WHEN SERVERPROPERTY('EditionID') = -2117995310  THEN 'Developer'
         WHEN SERVERPROPERTY('EditionID') = 610778273  THEN 'Windows Embedded SQL'
         WHEN SERVERPROPERTY('EditionID') = 4161255391   THEN 'Express with Advanced Services'
    END AS 'Edition'; 

How to check if a string contains a substring in Bash

The accepted answer is best, but since there's more than one way to do it, here's another solution:

if [ "$string" != "${string/foo/}" ]; then
    echo "It's there!"
fi

${var/search/replace} is $var with the first instance of search replaced by replace, if it is found (it doesn't change $var). If you try to replace foo by nothing, and the string has changed, then obviously foo was found.

How to present a simple alert message in java?

Call "setWarningMsg()" Method and pass the text that you want to show.

exm:- setWarningMsg("thank you for using java");


public static void setWarningMsg(String text){
    Toolkit.getDefaultToolkit().beep();
    JOptionPane optionPane = new JOptionPane(text,JOptionPane.WARNING_MESSAGE);
    JDialog dialog = optionPane.createDialog("Warning!");
    dialog.setAlwaysOnTop(true);
    dialog.setVisible(true);
}

Or Just use

JOptionPane optionPane = new JOptionPane("thank you for using java",JOptionPane.WARNING_MESSAGE);
JDialog dialog = optionPane.createDialog("Warning!");
dialog.setAlwaysOnTop(true); // to show top of all other application
dialog.setVisible(true); // to visible the dialog

You can use JOptionPane. (WARNING_MESSAGE or INFORMATION_MESSAGE or ERROR_MESSAGE)

How to convert a pymongo.cursor.Cursor into a dict?

The MongoDB find method does not return a single result, but a list of results in the form of a Cursor. This latter is an iterator, so you can go through it with a for loop.

For your case, just use the findOne method instead of find. This will returns you a single document as a dictionary.

How to show live preview in a small popup of linked page on mouse over on link?

HTML structure

<div id="app">
<div class="box">
    <div class="title">How to preview link with iframe and javascript?</div>
    <div class="note"><small>Note: Click to every link on content below to preview</small></div>
    <div id="content">
        We'll first attach all the events to all the links for which we want to <a href="https://htmlcssdownload.com/">preview</a> with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
    </div>
    <h3>Preview the link</h3>
    <div id="result"></div>
</div>

We'll first attach all the events to all the links for which we want to preview with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.

<script type="text/javascript">
(()=>{
    let content = document.getElementById('content');
    let links = content.getElementsByTagName('a');
    for (let index = 0; index < links.length; index++) {
        const element = links[index];
        element.addEventListener('click',(e)=>{
            e.preventDefault();
            openDemoLink(e.target.href);
        })
    }

    function openDemoLink(link){

        let div = document.createElement('div');
        div.classList.add('preview_frame');
        
        let frame = document.createElement('iframe');
        frame.src = link;
        
        let close = document.createElement('a');
        close.classList.add('close-btn');
        close.innerHTML = "Click here to close the example";
        close.addEventListener('click', function(e){
            div.remove();
        })
        
        div.appendChild(frame);
        div.appendChild(close);
        
        document.getElementById('result').appendChild(div);
    }
})()

To see detail at How to live preview link

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

ASP.NET set hiddenfield a value in Javascript

document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value

The id you set in server is the server id which is different from client id.

Pass user defined environment variable to tomcat

Environment variables can be set, by creating a setenv.bat (windows) or setenv.sh (unix) file in the bin folder of your tomcat installation directory. However, environment variables will not be accessabile from within your code.

System properties are set by -D arguments of the java process. You can define java starting arguments in the environment variable JAVA_OPTS.

My suggestions is the combination of these two mechanisms. In your apache-tomcat-0.0.0\bin\setenv.bat write:

set JAVA_OPTS=-DAPP_MASTER_PASSWORD=password1

and in your Java code write:

System.getProperty("APP_MASTER_PASSWORD")

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Use DateTime.ParseExact.

this.Text="22/11/2009";

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);

How to test if a file is a directory in a batch script?

Here's a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.

@echo off
if [%1]==[] goto usage

for /f "delims=" %%i in ("%~1") do set MYPATH="%%~fi"
pushd %MYPATH% 2>nul
if errorlevel 1 goto notdir
goto isdir

:notdir
echo not a directory
goto exit

:isdir
popd
echo is a directory
goto exit

:usage
echo Usage:  %0 DIRECTORY_TO_TEST

:exit

Sample output with the above saved as "isdir.bat":

C:\>isdir c:\Windows\system32
is a directory

C:\>isdir c:\Windows\system32\wow32.dll
not a directory

C:\>isdir c:\notadir
not a directory

C:\>isdir "C:\Documents and Settings"
is a directory

C:\>isdir \
is a directory

C:\>isdir \\ninja\SharedDocs\cpu-z
is a directory

C:\>isdir \\ninja\SharedDocs\cpu-z\cpuz.ini
not a directory

How can I remove a style added with .css() function?

Use my Plugin :

$.fn.removeCss=function(all){
        if(all===true){
            $(this).removeAttr('class');
        }
        return $(this).removeAttr('style')
    }

For your case ,Use it as following :

$(<mySelector>).removeCss();

or

$(<mySelector>).removeCss(false);

if you want to remove also CSS defined in its classes :

$(<mySelector>).removeCss(true);

Javascript: Setting location.href versus location

Just to clarify, you can't do location.split('#'), location is an object, not a string. But you can do location.href.split('#'); because location.href is a string.

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

You can add function to:

c:\Users\David\Documents\WindowsPowerShell\profile.ps1

An the function will be available.

How to parse SOAP XML?

In your code you are querying for the payment element in default namespace, but in the XML response it is declared as in http://apilistener.envoyservices.com namespace.

So, you are missing a namespace declaration:

$xml->registerXPathNamespace('envoy', 'http://apilistener.envoyservices.com');

Now you can use the envoy namespace prefix in your xpath query:

xpath('//envoy:payment')

The full code would be:

$xml = simplexml_load_string($soap_response);
$xml->registerXPathNamespace('envoy', 'http://apilistener.envoyservices.com');
foreach ($xml->xpath('//envoy:payment') as $item)
{
    print_r($item);
}

Note: I removed the soap namespace declaration as you do not seem to be using it (it is only useful if you would use the namespace prefix in you xpath queries).

How to update record using Entity Framework Core?

According to Microsoft docs:

the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflict

However, you should know that using Update method on DbContext will mark all the fields as modified and will include all of them in the query. If you want to update a subset of fields you should use the Attach method and then mark the desired field as modified manually.

context.Attach(person);
context.Entry(person).Property(p => p.Name).IsModified = true;
context.SaveChanges();

How can I convert an HTML table to CSV?

I'm not sure if there is pre-made library for this, but if you're willing to get your hands dirty with a little Perl, you could likely do something with Text::CSV and HTML::Parser.

https connection using CURL from command line

you could use this

curl_setopt($curl->curl, CURLOPT_SSL_VERIFYPEER, false);

How to achieve function overloading in C?

There are few possibilities:

  1. printf style functions (type as an argument)
  2. opengl style functions (type in function name)
  3. c subset of c++ (if You can use a c++ compiler)

Increase bootstrap dropdown menu width

Text will never wrap to the next line. The text continues on the same line until a
tag is encountered.

.dropdown-menu {
    white-space: nowrap;
}

Typescript: difference between String and string

The two types are distinct in JavaScript as well as TypeScript - TypeScript just gives us syntax to annotate and check types as we go along.

String refers to an object instance that has String.prototype in its prototype chain. You can get such an instance in various ways e.g. new String('foo') and Object('foo'). You can test for an instance of the String type with the instanceof operator, e.g. myString instanceof String.

string is one of JavaScript's primitive types, and string values are primarily created with literals e.g. 'foo' and "bar", and as the result type of various functions and operators. You can test for string type using typeof myString === 'string'.

The vast majority of the time, string is the type you should be using - almost all API interfaces that take or return strings will use it. All JS primitive types will be wrapped (boxed) with their corresponding object types when using them as objects, e.g. accessing properties or calling methods. Since String is currently declared as an interface rather than a class in TypeScript's core library, structural typing means that string is considered a subtype of String which is why your first line passes compilation type checks.

How do you check in python whether a string contains only numbers?

As every time I encounter an issue with the check is because the str can be None sometimes, and if the str can be None, only use str.isdigit() is not enough as you will get an error

AttributeError: 'NoneType' object has no attribute 'isdigit'

and then you need to first validate the str is None or not. To avoid a multi-if branch, a clear way to do this is:

if str and str.isdigit():

Hope this helps for people have the same issue like me.

When does socket.recv(recv_size) return?

It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).

MySql : Grant read only options?

Even user has got answer and @Michael - sqlbot has covered mostly points very well in his post but one point is missing, so just trying to cover it.

If you want to provide read permission to a simple user (Not admin kind of)-

GRANT SELECT, EXECUTE ON DB_NAME.* TO 'user'@'localhost' IDENTIFIED BY 'PASSWORD';

Note: EXECUTE is required here, so that user can read data if there is a stored procedure which produce a report (have few select statements).

Replace localhost with specific IP from which user will connect to DB.

Additional Read Permissions are-

  • SHOW VIEW : If you want to show view schema.
  • REPLICATION CLIENT : If user need to check replication/slave status. But need to give permission on all DB.
  • PROCESS : If user need to check running process. Will work with all DB only.

First letter capitalization for EditText

if you are writing styles in styles.xml then

remove android:inputType property and add below lines

<item name="android:capitalize">words</item>

Inject service in app.config

Using $injector to call service methods in config

I had a similar issue and resolved it by using the $injector service as shown above. I tried injecting the service directly but ended up with a circular dependency on $http. The service displays a modal with the error and I am using ui-bootstrap modal which also has a dependency on $https.

    $httpProvider.interceptors.push(function($injector) {
    return {
        "responseError": function(response) {

            console.log("Error Response status: " + response.status);

            if (response.status === 0) {
                var myService= $injector.get("myService");
                myService.showError("An unexpected error occurred. Please refresh the page.")
            }
        }
    }

Convert Swift string to array

You can also create an extension:

var strArray = "Hello, playground".Letterize()

extension String {
    func Letterize() -> [String] {
        return map(self) { String($0) }
    }
}

How can I scroll a web page using selenium webdriver in python?

You can use send_keys to simulate an END (or PAGE_DOWN) key press (which normally scroll the page):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.END)

How to update /etc/hosts file in Docker image during "docker build"

Complete Answer

  1. Prepare your own hosts file you wish to add to docker container;
1.2.3.4 abc.tv
5.6.7.8 domain.xyz
1.3.5.7 odd.org
2.4.6.8 even.net
  1. COPY your hosts file into the container by adding the following line in the Dockerfile
COPY hosts /etc/hosts_extra
  1. If you know how to use ENTRYPOINT or CMD or CRON job then incorporate the following command line into it or at least run this inside the running container:
cat /etc/hosts_extra >> etc/hosts;
  1. You cannot add the following in the Dockerfile because the modification will be lost:
RUN cat /etc/hosts_extra >> etc/hosts;

Convert a RGB Color Value to a Hexadecimal String

You can use

String hex = String.format("#%02x%02x%02x", r, g, b);  

Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF vs. #ffffff).

How do I list all tables in a schema in Oracle SQL?

You can query USER_TABLES

select TABLE_NAME from user_tables

How to remove padding around buttons in Android?

You can use Borderless style in AppCompatButton like below. and use android:background with it.

style="@style/Widget.AppCompat.Button.Borderless.Colored"

Button code

<androidx.appcompat.widget.AppCompatButton
        android:id="@+id/button_visa_next"
        android:background="@color/colorPrimary"
        style="@style/Widget.AppCompat.Button.Borderless.Colored"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/spacing_normal"
        android:text="@string/next"
        android:textColor="@color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Output:

enter image description here

Display help message with python argparse when script is called without any arguments

If you associate default functions for (sub)parsers, as is mentioned under add_subparsers, you can simply add it as the default action:

parser = argparse.ArgumentParser()
parser.set_defaults(func=lambda x: parser.print_usage())
args = parser.parse_args()
args.func(args)

Add the try-except if you raise exceptions due to missing positional arguments.

Select single item from a list

There are two easy ways, depending on if you want to deal with exceptions or get a default value.

You can use the First<T>() or the FirstOrDefault<T>() extension method to get the first result or default(T).

var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0

Get a Div Value in JQuery

myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
   alert ( myDivObj.innerHTML ); 
}else{
   alert ( "Alien Found" );
}

Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]

function showDivText(){
            divObj = document.getElementById("myDiv");
            if ( divObj ){
                if ( divObj.textContent ){ // FF
                    alert ( divObj.textContent );
                }else{  // IE           
                    alert ( divObj.innerText );  //alert ( divObj.innerHTML );
                } 
            }  
        }

Maintain model of scope when changing between views in AngularJS

A bit late for an answer but just updated fiddle with some best practice

jsfiddle

var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
    var userService = {};

    userService.name = "HI Atul";

    userService.ChangeName = function (value) {

       userService.name = value;
    };

    return userService;
});

function MyCtrl($scope, UserService) {
    $scope.name = UserService.name;
    $scope.updatedname="";
    $scope.changeName=function(data){
        $scope.updateServiceName(data);
    }
    $scope.updateServiceName = function(name){
        UserService.ChangeName(name);
        $scope.name = UserService.name;
    }
}

How to print from Flask @app.route to python console

We can also use logging to print data on the console.

Example:

import logging
from flask import Flask

app = Flask(__name__)

@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"

if __name__ == '__main__':
    app.run(debug=True)

jQuery if statement to check visibility

 $('#column-left form').hide();
 $('.show-search').click(function() {
    $('#column-left form').stop(true, true).slideToggle(300); //this will slide but not hide that's why
    $('#column-left form').hide(); 
    if(!($('#column-left form').is(":visible"))) {
        $("#offers").show();
    } else {
        $('#offers').hide();
    }
  });

What's the best UI for entering date of birth?

Put both and make each update the other. If the user chooses the date from the datepicker, it is easy to fix a minor misclick in the text field or visualize the choise you typed into text field in the datepicker.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

Simple excel find and replace for formulas

It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way

=((E9-E8)/E8) 

became

=((R[-1]C-R[-2]C)/R[-2]C)

and

(EXP((LN(E9/E8)/14.32))-1)

became

=(EXP((LN(R[-1]C/R[-2]C)/14.32))-1)

In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!

Index (zero based) must be greater than or equal to zero

Your second String.Format uses {2} as a placeholder but you're only passing in one argument, so you should use {0} instead.

Change this:

String.Format("{2}", reader.GetString(0));

To this:

String.Format("{0}", reader.GetString(2));

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

How to check if input file is empty in jQuery

To check whether the input file is empty or not by using the file length property, index should be specified like the following:

var vidFileLength = $("#videoUploadFile")[0].files.length;
if(vidFileLength === 0){
    alert("No file selected.");
}

Regex Until But Not Including

The explicit way of saying "search until X but not including X" is:

(?:(?!X).)*

where X can be any regular expression.

In your case, though, this might be overkill - here the easiest way would be

[^z]*

This will match anything except z and therefore stop right before the next z.

So .*?quick[^z]* will match The quick fox jumps over the la.

However, as soon as you have more than one simple letter to look out for, (?:(?!X).)* comes into play, for example

(?:(?!lazy).)* - match anything until the start of the word lazy.

This is using a lookahead assertion, more specifically a negative lookahead.

.*?quick(?:(?!lazy).)* will match The quick fox jumps over the.

Explanation:

(?:        # Match the following but do not capture it:
 (?!lazy)  # (first assert that it's not possible to match "lazy" here
 .         # then match any character
)*         # end of group, zero or more repetitions.

Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b will only match the complete word fox but not the fox in foxy.

Note

If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s) to the regex, but that doesn't work in all regex engines (notably JavaScript).

Alternative solution:

In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ? to the * quantifier, it will try to match as few characters as possible from the current position:

.*?(?=(?:X)|$)

will match any number of characters, stopping right before X (which can be any regex) or the end of the string (if X doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X in order to reliably isolate it from the alternation)

Warn user before leaving web page with unsaved changes

The solution by Eerik Sven Puudist ...

var isSubmitting = false;

$(document).ready(function () {
    $('form').submit(function(){
        isSubmitting = true
    })

    $('form').data('initial-state', $('form').serialize());

    $(window).on('beforeunload', function() {
        if (!isSubmitting && $('form').serialize() != $('form').data('initial-state')){
            return 'You have unsaved changes which will not be saved.'
        }
    });
})

... spontaneously did the job for me in a complex object-oriented setting without any changes necessary.

The only change I applied was to refer to the concrete form (only one form per file) called "formForm" ('form' -> '#formForm'):

<form ... id="formForm" name="formForm" ...>

Especially well done is the fact that the submit button is being "left alone".

Additionally, it works for me also with the lastest version of Firefox (as of February 7th, 2019).

How to run a function in jquery

Is this the most obfuscated solution possible? I don't believe the idea of jQuery was to create code like this.There's also the presumption that we don't want to bubble events, which is probably wrong.

Simple moving doosomething() outside of $(function(){} will cause it to have global scope and keep the code simple/readable.

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

How to convert enum value to int?

A somewhat different approach (at least on Android) is to use the IntDef annotation to combine a set of int constants

@IntDef({NOTAX, SALESTAX, IMPORTEDTAX})
@interface TAX {}
int NOTAX = 0;
int SALESTAX = 10;
int IMPORTEDTAX = 5;

Use as function parameter:

void computeTax(@TAX int taxPercentage){...} 

or in a variable declaration:

@TAX int currentTax = IMPORTEDTAX;

How to filter rows in pandas by regex

Using str slice

foo[foo.b.str[0]=='f']
Out[18]: 
   a    b
1  2  foo
2  3  fat

How do I use a PriorityQueue?

Java 8 solution

We can use lambda expression or method reference introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :

Using lambda expression

PriorityQueue<String> pq=
                    new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

Using Method reference

PriorityQueue<String> pq=
                new PriorityQueue<String>(5, Comparator.comparing(String::length));

Then we can use any of them as:

public static void main(String[] args) {
        PriorityQueue<String> pq=
                new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
       // or pq = new PriorityQueue<String>(5, Comparator.comparing(String::length));
        pq.add("Apple");
        pq.add("PineApple");
        pq.add("Custard Apple");
        while (pq.size() != 0)
        {
            System.out.println(pq.remove());
        }
    }

This will print:

Apple
PineApple
Custard Apple

To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use reversed as:

PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                             Comparator.comparing(String::length).reversed());

We can also use Collections.reverseOrder:

PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                Collections.reverseOrder(Comparator.comparing(String::length))

So we can see that Collections.reverseOrder is overloaded to take comparator which can be useful for custom objects. The reversed actually uses Collections.reverseOrder:

default Comparator<T> reversed() {
    return Collections.reverseOrder(this);
}

offer() vs add()

As per the doc

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap.

linking jquery in html

<script
 src="CDN">
</script>

for change the CDN check this website.

the first one is JQuery

How to parse a string in JavaScript?

Use split on string:

var array = coolVar.split(/-/);

How to replace a char in string with an Empty character in C#.NET

If you are in a loop, let's say that you loop through a list of punctuation characters that you want to remove, you can do something like this:

      private const string PunctuationChars = ".,!?$";
          foreach (var word in words)
                {
                    var word_modified = word;

                    var modified = false;

                    foreach (var punctuationChar in PunctuationChars)
                    {
                        if (word.IndexOf(punctuationChar) > 0)
                        {
                            modified = true;
                            word_modified = word_modified.Replace("" + punctuationChar, "");


                        }
                    }
               //////////MORE CODE
               }

The trick being the following:

word_modified.Replace("" + punctuationChar, "");

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Since you say that any language is acceptable, the natural choice is PostGIS:

SELECT * FROM places
WHERE ST_DistanceSpheroid(geom, $location, $spheroid) < $max_metres;

If you want to use WGS datum, you should set $spheroid to 'SPHEROID["WGS 84",6378137,298.257223563]'

Assuming that you have indexed places by the geom column, this should be reasonably efficient.

javascript clear field value input

 var input= $(this);    
 input.innerHTML = '';

How do you determine the size of a file in C?

Based on NilObject's code:

#include <sys/stat.h>
#include <sys/types.h>

off_t fsize(const char *filename) {
    struct stat st; 

    if (stat(filename, &st) == 0)
        return st.st_size;

    return -1; 
}

Changes:

  • Made the filename argument a const char.
  • Corrected the struct stat definition, which was missing the variable name.
  • Returns -1 on error instead of 0, which would be ambiguous for an empty file. off_t is a signed type so this is possible.

If you want fsize() to print a message on error, you can use this:

#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

off_t fsize(const char *filename) {
    struct stat st;

    if (stat(filename, &st) == 0)
        return st.st_size;

    fprintf(stderr, "Cannot determine size of %s: %s\n",
            filename, strerror(errno));

    return -1;
}

On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.

TortoiseSVN icons not showing up under Windows 7

I suggest complaining to Microsoft regarding the ridiculously low icon overlay limit. If enough of us complain, perhaps they'll fix the true root cause of this problem:

See comments at bottom of page: http://msdn.microsoft.com/en-us/library/cc144123(VS.85).aspx

Give Microsoft Windows 7 team feedback on this issue: http://mymfe.microsoft.com/Windows%207/Feedback.aspx?formID=195

Test if a string contains any of the strings from an array

A more groovyesque approach would be to use inject in combination with metaClass:

I would to love to say:

String myInput="This string is FORBIDDEN"
myInput.containsAny(["FORBIDDEN","NOT_ALLOWED"]) //=>true

And the method would be:

myInput.metaClass.containsAny={List<String> notAllowedTerms->
   notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}

If you need containsAny to be present for any future String variable then add the method to the class instead of the object:

String.metaClass.containsAny={notAllowedTerms->
   notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}

Get the distance between two geo points

There are a couple of methods you could use, but to determine which one is best we first need to know if you are aware of the user's altitude, as well as the altitude of the other points?

Depending on the level of accuracy you are after, you could look into either the Haversine or Vincenty formulae...

These pages detail the formulae, and, for the less mathematically inclined also provide an explanation of how to implement them in script!

Haversine Formula: http://www.movable-type.co.uk/scripts/latlong.html

Vincenty Formula: http://www.movable-type.co.uk/scripts/latlong-vincenty.html

If you have any problems with any of the meanings in the formulae, just comment and I'll do my best to answer them :)

Controlling fps with requestAnimationFrame?

I suggest wrapping your call to requestAnimationFrame in a setTimeout:

const fps = 25;
function animate() {
  // perform some animation task here

  setTimeout(() => {
    requestAnimationFrame(animate);
  }, 1000 / fps);
}
animate();

You need to call requestAnimationFrame from within setTimeout, rather than the other way around, because requestAnimationFrame schedules your function to run right before the next repaint, and if you delay your update further using setTimeout you will have missed that time window. However, doing the reverse is sound, since you’re simply waiting a period of time before making the request.

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

JavaScript to scroll long page to DIV

This worked for me

document.getElementById('divElem').scrollIntoView();

Vue js error: Component template should contain exactly one root element

Just make sure that you have one root div and put everything inside this root

  <div class="root">
    <!--and put all child here --!>
   <div class='child1'></div>
   <div class='child2'></div>
  </div>

and so on

Reverse a string in Python

def reverse(input):
    return reduce(lambda x,y : y+x, input)

Why does my Eclipse keep not responding?

for me, it was because of all the outgoing files, i.e workspace is not in sync with SVN, due to the 'target' folders (maven project, or when building web project), add them to svn:ignore.

jQuery: read text file from file system

Something like this is what I use all the time. No need for any base64 decoding.

<html>
<head>
<script>
      window.onload = function(event) {
        document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
      }

      function handleFileSelect(event) {
        var fileReader = new FileReader();
        fileReader.onload = function(event) {
          $('#accessKeyField').val(event.target.result);
        }
        var file = event.target.files[0];
        fileReader.readAsText(file);
        document.getElementById('fileInput').value = null;
      }
</script>
</head>
<body>
<input type="file" id="fileInput" style="height: 20px; width: 100px;">
</body>
</html>

scrollbars in JTextArea

As Fredrik mentions in his answer, the simple way to achieve this is to place the JTextArea in a JScrollPane. This will allow scrolling of the view area of the JTextArea.

Just for the sake of completeness, the following is how it could be achieved:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);   // JTextArea is placed in a JScrollPane.

Once the JTextArea is included in the JScrollPane, the JScrollPane should be added to where the text area should be. In the following example, the text area with the scroll bars is added to a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(sp);

Thank you kd304 for mentioning in the comments that one should add the JScrollPane to the container rather than the JTextArea -- I feel it's a common error to add the text area itself to the destination container rather than the scroll pane with text area.

The following articles from The Java Tutorials has more details:

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Parsing a JSON array using Json.Net

Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage

And you can convert the entire object to a string, filename.json is expected to be located in documents folder.

        var text = File.ReadAllText("filename.json");
        var json = JsonValue.Parse(text);

        while (JsonValue.Null != null)
        {
            Console.WriteLine(json.ToString());

        }
        Console.ReadLine();

Find max and second max salary for a employee table MySQL

Try like this

SELECT (select max(Salary) from Employee) as MAXinmum),(max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary)) FROM Employee);

(Or)

Try this, n would be the nth item you would want to return

 SELECT DISTINCT(Salary) FROM table ORDER BY Salary DESC LIMIT n,1

In your case

 SELECT DISTINCT(column_name) FROM table_name ORDER BY column_name DESC limit 2,1;

Problems installing the devtools package

I hit this issue with Ubuntu 18.04 and none of the previous answers solved it. Eventually I succeeded by installing devtools with the package manager itself:

sudo apt install r-cran-devtools

Print a div content using Jquery

If you want to do this without an extra plugin (like printThis), I think this should work. The idea is to have a special div that will be printed, while everything else is hidden using CSS. This is easier to do if the div is a direct child of the body tag, so you will have to move whatever you want to print to a div like that. S So begin with creating a div with id print-me as a direct child to your body tag. Then use this code to print the div:

$("#btn").click(function () {
    //Copy the element you want to print to the print-me div.
    $("#printarea").clone().appendTo("#print-me");
    //Apply some styles to hide everything else while printing.
    $("body").addClass("printing");
    //Print the window.
    window.print();
    //Restore the styles.
    $("body").removeClass("printing");
    //Clear up the div.
    $("#print-me").empty();
});

The styles you need are these:

@media print {
    /* Hide everything in the body when printing... */
    body.printing * { display: none; }
    /* ...except our special div. */
    body.printing #print-me { display: block; }
}

@media screen {
    /* Hide the special layer from the screen. */
    #print-me { display: none; }
}

The reason why we should only apply the @print styles when the printing class is present is that the page should be printed as normally if the user prints the page by selecting File -> Print.

Permission denied on CopyFile in VBS

You can do this:

fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\options.txt"

Include the filename in the folder that you copy to.

Create a circular button in BS3

I had the same problem and came up with a very simple solution working for all (xs, sm, normal and lg) buttons more or less:

.btn-circle {
    border-radius: 50%;
    padding: 0.1em;
    width:1.8em;
}

The difference between the btn-xs and -sm are only their padding. And this is not covered with this snippet. This snippet calculates the sizes based on the font-size only.

Set Focus on EditText

This works from me:

public void showKeyboard(final EditText ettext){
    ettext.requestFocus();
    ettext.postDelayed(new Runnable(){
            @Override public void run(){
                InputMethodManager keyboard=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.showSoftInput(ettext,0);
            }
        }
        ,200);
}

To hide:

private void hideSoftKeyboard(EditText ettext){
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(ettext.getWindowToken(), 0);
}