Programs & Examples On #Fips

The term "fips" commonly refers to the Federal Information Processing Standards Publication 140 (FIPS 140), a document published by the National Institute of Standards and Technology (NIST), a U.S. government agency. Cryptographic software and hardware that complies with the standard must use only cryptographic algorithms specified in FIPS 140-2, the latest published revision.

How to install OpenSSL in windows 10?

Necroposting, but might be useful for others.

There's always the official page: [OpenSSL.Wiki]: Binaries which contains useful URLs.

I also want to mention: [GitHub]: CristiFati/Prebuilt-Binaries - Prebuilt-Binaries/OpenSSL

  • v1.0.2u is built with OpenSSL-FIPS 2.0.16
  • Artefacts are .zips that should be unpacked in "C:\Program Files" (please take a look at the Readme.md file, and also at the one at the repository root)

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

If you want to avoid using an extra Class and List<Object> genomes you could simply use a Map.

The data structure translates into Map<String, List<Country>>

String resourceEndpoint = "http://api.geonames.org/countryInfoJSON?username=volodiaL";

Map<String, List<Country>> geonames = restTemplate.getForObject(resourceEndpoint, Map.class);

List<Country> countries = geonames.get("geonames");

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Type

netsh wlan set hostednetwork mode=allow ssid=hotspotname key=123456789

perform all steps in proper order.. for more detail with image ,have a look..this might help to setup hotspot correctly.

http://www.infogeekers.com/turn-windows-8-into-wifi-hotspot/

" netsh wlan start hostednetwork " command not working no matter what I try

At first simply uninstall wifi drivers and softwares just keep wifi drivers + from device manager....network adapters...remove all virtual connections

then

Press the Windows + R key combination to bring up a run box, type ncpa.cpl and hit enter.

netsh wlan set hostednetwork mode=allow ssid=”How-To Geek” key=”Pa$$w0rd”

netsh wlan start hostednetwork

netsh wlan show hostednetwork

its working for me and on others PC.

connect to host localhost port 22: Connection refused

Check file /etc/ssh/sshd_config for Port number. Make sure it is 22.

unable to set private key file: './cert.pem' type PEM

I faced this issue when I had used Open SSL and the solution was to split the cert in 3 files and use all of them doing the call with Curl:

openssl pkcs12 -in mycert.p12 -out ca.pem -cacerts -nokeys
openssl pkcs12 -in mycert.p12 -out client.pem -clcerts -nokeys 
openssl pkcs12 -in mycert.p12 -out key.pem -nocerts

curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

How to split a dataframe string column into two columns?

Use df.assign to create a new df. See http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

split = df_selected['name'].str.split(',', 1, expand=True)
df_split = df_selected.assign(first_name=split[0], last_name=split[1])
df_split.drop('name', 1, inplace=True)

Mismatch Detected for 'RuntimeLibrary'

I had this problem along with mismatch in ITERATOR_DEBUG_LEVEL. As a sunday-evening problem after all seemed ok and good to go, I was put out for some time. Working in de VS2017 IDE (Solution Explorer) I had recently added/copied a sourcefile reference to my project (ctrl-drag) from another project. Looking into properties->C/C++/Preprocessor - at source file level, not project level - I noticed that in a Release configuration _DEBUG was specified instead of NDEBUG for this source file. Which was all the change needed to get rid of the problem.

Enabling/Disabling Microsoft Virtual WiFi Miniport

You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it. After that, you start your cmd with admin privileges, then try:

netsh wlan start hostednetwork

Getting RSA private key from PEM BASE64 Encoded private key file

This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
        // PKCS#8 format
        final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
        final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";

        // PKCS#1 format
        final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
        final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";

        Path path = Paths.get(pemFileName.getAbsolutePath());

        String privateKeyPem = new String(Files.readAllBytes(path));

        if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
            privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);

            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

        } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) {  // PKCS#1 format

            privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));

            DerValue[] seq = derReader.getSequence(0);

            if (seq.length < 9) {
                throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
            }

            // skip version seq[0];
            BigInteger modulus = seq[1].getBigInteger();
            BigInteger publicExp = seq[2].getBigInteger();
            BigInteger privateExp = seq[3].getBigInteger();
            BigInteger prime1 = seq[4].getBigInteger();
            BigInteger prime2 = seq[5].getBigInteger();
            BigInteger exp1 = seq[6].getBigInteger();
            BigInteger exp2 = seq[7].getBigInteger();
            BigInteger crtCoef = seq[8].getBigInteger();

            RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);

            KeyFactory factory = KeyFactory.getInstance("RSA");

            return factory.generatePrivate(keySpec);
        }

        throw new GeneralSecurityException("Not supported format of a private key");
    }

SQL Server: Best way to concatenate multiple columns?

Try using below:

SELECT 
    (RTRIM(LTRIM(col_1))) + (RTRIM(LTRIM(col_2))) AS Col_newname,
    col_1,
    col_2 
FROM 
    s_cols 
WHERE
    col_any_condition = ''
;

How to dynamically insert a <script> tag via jQuery after page load?

Here is a much clearer way — no need for jQuery — which adds a script as the last child of <body>:

document.body.innerHTML +='<script src="mycdn.js"><\/script>'

But if you want to add and load scripts use Rocket Hazmat's method.

How to show disable HTML select option in by default?

Use hidden.

_x000D_
_x000D_
<select>_x000D_
   <option hidden>Choose</option>_x000D_
   <option>Item 1</option>_x000D_
   <option>Item 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

This doesn't unset it but you can however hide it in the options while it's displayed by default.

Uninstall all installed gems, in OSX?

A slighest different version, skipping the cut step, taking advantage of the '--no-version' option:

gem list --no-version |xargs gem uninstall -ax

Since you are removing everything, I don't see the need for the 'I' option. Whenever the gem is removed, it's fine.

How to make an inline element appear on new line, or block element not occupy the whole line?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.feature_wrapper span {
    float: left;
    clear: left;
    display:inline
}

EDIT: now browsers have better support you can make use of the do inline-block.

.feature_wrapper span {
    display:inline-block;
    *display:inline; *zoom:1;
}

Depending on the text-align this will appear as through its inline while also acting like a block element.

javascript set cookie with expire time

I use a function to store cookies with a custom expire time in days:

// use it like: writeCookie("mycookie", "1", 30)
// this will set a cookie for 30 days since now
function writeCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

Opening a folder in explorer and selecting a file

Using Process.Start on explorer.exe with the /select argument oddly only works for paths less than 120 characters long.

I had to use a native windows method to get it to work in all cases:

[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);

[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);

public static void OpenFolderAndSelectItem(string folderPath, string file)
{
    IntPtr nativeFolder;
    uint psfgaoOut;
    SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);

    if (nativeFolder == IntPtr.Zero)
    {
        // Log error, can't find folder
        return;
    }

    IntPtr nativeFile;
    SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);

    IntPtr[] fileArray;
    if (nativeFile == IntPtr.Zero)
    {
        // Open the folder without the file selected if we can't find the file
        fileArray = new IntPtr[0];
    }
    else
    {
        fileArray = new IntPtr[] { nativeFile };
    }

    SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);

    Marshal.FreeCoTaskMem(nativeFolder);
    if (nativeFile != IntPtr.Zero)
    {
        Marshal.FreeCoTaskMem(nativeFile);
    }
}

Gmail: 530 5.5.1 Authentication Required. Learn more at

You need to go here https://security.google.com/settings/security/apppasswords

then select Gmail and then select device. then click on Generate. Simply Copy & Paste password which is generated by Google.

Using arrays or std::vectors in C++, what's the performance gap?

You have even fewer reasons to use plain arrays in C++11.

There are 3 kind of arrays in nature from fastest to slowest, depending on the features they have (of course the quality of implementation can make things really fast even for case 3 in the list):

  1. Static with size known at compile time. --- std::array<T, N>
  2. Dynamic with size known at runtime and never resized. The typical optimization here is, that if the array can be allocated in the stack directly. -- Not available. Maybe dynarray in C++ TS after C++14. In C there are VLAs
  3. Dynamic and resizable at runtime. --- std::vector<T>

For 1. plain static arrays with fixed number of elements, use std::array<T, N> in C++11.

For 2. fixed size arrays specified at runtime, but that won't change their size, there is discussion in C++14 but it has been moved to a technical specification and made out of C++14 finally.

For 3. std::vector<T> will usually ask for memory in the heap. This could have performance consequences, though you could use std::vector<T, MyAlloc<T>> to improve the situation with a custom allocator. The advantage compared to T mytype[] = new MyType[n]; is that you can resize it and that it will not decay to a pointer, as plain arrays do.

Use the standard library types mentioned to avoid arrays decaying to pointers. You will save debugging time and the performance is exactly the same as with plain arrays if you use the same set of features.

Python check if website exists

code:

a="http://www.example.com"
try:    
    print urllib.urlopen(a)
except:
    print a+"  site does not exist"

How to check if user input is not an int value

Maybe you can try this:

int function(){
Scanner input = new Scanner(System.in);   
System.out.print("Enter an integer between 1-100: ");   
int range;
while(true){   
    if(input.hasNextInt()){   
    range = input.nextInt();
    if(0<=range && range <= 100)
        break;
    else
        continue;
    }
    input.nextLine();  //Comsume the garbage value
    System.out.println("Enter an integer between 1-100:");
}
return range;
}

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

first you have to give echo to display base url. Then change below value in your autoload.php which will be inside your application/config/ folder. $autoload['helper'] = array('url'); then your issue will be resolved.

Catching multiple exception types in one catch block

As of PHP 7.1,

catch( AError | BError $e )
{
    handler1( $e )
}

interestingly, you can also:

catch( AError | BError $e )
{
    handler1( $e )
} catch (CError $e){
    handler2($e);
} catch(Exception $e){
    handler3($e);
}

and in earlier versions of PHP:

catch(Exception $ex){
    if($ex instanceof AError){
        //handle a AError
    } elseif($ex instanceof BError){
        //handle a BError
    } else {
       throw $ex;//an unknown exception occured, throw it further
    }
}

C++ Dynamic Shared Library on Linux

On top of previous answers, I'd like to raise awareness about the fact that you should use the RAII (Resource Acquisition Is Initialisation) idiom to be safe about handler destruction.

Here is a complete working example:

Interface declaration: Interface.hpp:

class Base {
public:
    virtual ~Base() {}
    virtual void foo() const = 0;
};

using Base_creator_t = Base *(*)();

Shared library content:

#include "Interface.hpp"

class Derived: public Base {
public:
    void foo() const override {}
};

extern "C" {
Base * create() {
    return new Derived;
}
}

Dynamic shared library handler: Derived_factory.hpp:

#include "Interface.hpp"
#include <dlfcn.h>

class Derived_factory {
public:
    Derived_factory() {
        handler = dlopen("libderived.so", RTLD_NOW);
        if (! handler) {
            throw std::runtime_error(dlerror());
        }
        Reset_dlerror();
        creator = reinterpret_cast<Base_creator_t>(dlsym(handler, "create"));
        Check_dlerror();
    }

    std::unique_ptr<Base> create() const {
        return std::unique_ptr<Base>(creator());
    }

    ~Derived_factory() {
        if (handler) {
            dlclose(handler);
        }
    }

private:
    void * handler = nullptr;
    Base_creator_t creator = nullptr;

    static void Reset_dlerror() {
        dlerror();
    }

    static void Check_dlerror() {
        const char * dlsym_error = dlerror();
        if (dlsym_error) {
            throw std::runtime_error(dlsym_error);
        }
    }
};

Client code:

#include "Derived_factory.hpp"

{
    Derived_factory factory;
    std::unique_ptr<Base> base = factory.create();
    base->foo();
}

Note:

  • I put everything in header files for conciseness. In real life you should of course split your code between .hpp and .cpp files.
  • To simplify, I ignored the case where you want to handle a new/delete overload.

Two clear articles to get more details:

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

I see in the documentation page an example like this:

<source src="foo.ogg" type="video/ogg; codecs=&quot;dirac, speex&quot;">

Maybe you should enclose the codec information with &quot; entities instead of actual quotes and the type attribute with quotes instead of apostrophes.

You can also try removing the codec info altogether.

WordPress: get author info from post id

<?php
  $field = 'display_name';
  the_author_meta($field);
?>

Valid values for the $field parameter include:

  • admin_color
  • aim
  • comment_shortcuts
  • description
  • display_name
  • first_name
  • ID
  • jabber
  • last_name
  • nickname
  • plugins_last_view
  • plugins_per_page
  • rich_editing
  • syntax_highlighting
  • user_activation_key
  • user_description
  • user_email
  • user_firstname
  • user_lastname
  • user_level
  • user_login
  • user_nicename
  • user_pass
  • user_registered
  • user_status
  • user_url
  • yim

Call async/await functions in parallel

In my case, I have several tasks I want to execute in parallel, but I need to do something different with the result of those tasks.

function wait(ms, data) {
    console.log('Starting task:', data, ms);
    return new Promise(resolve => setTimeout(resolve, ms, data));
}

var tasks = [
    async () => {
        var result = await wait(1000, 'moose');
        // do something with result
        console.log(result);
    },
    async () => {
        var result = await wait(500, 'taco');
        // do something with result
        console.log(result);
    },
    async () => {
        var result = await wait(5000, 'burp');
        // do something with result
        console.log(result);
    }
]

await Promise.all(tasks.map(p => p()));
console.log('done');

And the output:

Starting task: moose 1000
Starting task: taco 500
Starting task: burp 5000
taco
moose
burp
done

The controller for path was not found or does not implement IController

Somebody added this to a View.

@Scripts.Render("~/bundles/jqueryval")

Then they added the BundleConfig.cs file in the App_Start Folder.
In the RegisterBundles Method they had:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));

However, they forgot to finish wiring this up in the Global.asax.cs File.
To Fix, all I had to do was add this to the Application_Start Method in Global.asax.cs:

RouteConfig.RegisterRoutes(RouteTable.Routes);

Note: I think the ordering/placement of this Line in the Application_Start Method matters,
so please keep that in mind.
I placed mine immediately after ViewEngines.

CSS: background-color only inside the margin

That is not possible du to the Box Model. However you could use a workaround with css3's border-image, or border-color in general css.

However im unsure whether you may have a problem with resetting. Some browsers do set a margin to html as well. See Eric Meyers Reset CSS for more!

html{margin:0;padding:0;}

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Python script to convert from UTF-8 to ASCII

UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.

How can I read a text file from the SD card in Android?

BufferedReader br = null;
try {
        String fpath = Environment.getExternalStorageDirectory() + <your file name>;
        try {
            br = new BufferedReader(new FileReader(fpath));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        String line = "";
        while ((line = br.readLine()) != null) {
         //Do something here 
        }

"error: assignment to expression with array type error" when I assign a struct field (C)

Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);

C# Parsing JSON array of objects

Use newtonsoft like so:

using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main()
    {
        string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche    Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891    Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";

        var resultObjects = AllChildren(JObject.Parse(json))
            .First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
            .Children<JObject>();

        foreach (JObject result in resultObjects) {
            foreach (JProperty property in result.Properties()) {
                // do something with the property belonging to result
            }
        }
    }

    // recursively yield all children of json
    private static IEnumerable<JToken> AllChildren(JToken json)
    {
        foreach (var c in json.Children()) {
            yield return c;
            foreach (var cc in AllChildren(c)) {
                yield return cc;
            }
        }
    }
}

Inner join with 3 tables in mysql

Almost correctly.. Look at the joins, you are referring the wrong fields

SELECT student.firstname,
       student.lastname,
       exam.name,
       exam.date,
       grade.grade
  FROM grade
 INNER JOIN student ON student.studentId = grade.fk_studentId
 INNER JOIN exam ON exam.examId = grade.fk_examId
 ORDER BY exam.date

How do I convert a TimeSpan to a formatted string?

I also had a similar issue and came up with my own extension but it seems to be a bit different than everything else.

    public static string TimeSpanToString(this TimeSpan timeSpan)
    {
        //if it's negative
        if (timeSpan.Ticks < 0)
        {
            timeSpan = timeSpan - timeSpan - timeSpan;
            if (timeSpan.Days != 0)
                return string.Format("-{0}:{1}", timeSpan.Days.ToString("d"), new DateTime(timeSpan.Ticks).ToString("HH:mm:ss"));
            else
                return new DateTime(timeSpan.Ticks).ToString("-HH:mm:ss");
        }

        //if it has days
        else if (timeSpan.Days != 0)
            return string.Format("{0}:{1}", timeSpan.Days.ToString("d"), new DateTime(timeSpan.Ticks).ToString("HH:mm:ss"));

        //otherwise return the time
        else
            return new DateTime(timeSpan.Ticks).ToString("HH:mm:ss");
    }

How to get the <html> tag HTML with JavaScript / jQuery?

In addition to some of the other answers, you could also access the HTML element via:

var htmlEl = document.body.parentNode;

Then you could get the inner HTML content:

var inner = htmlEl.innerHTML;

Doing so this way seems to be marginally faster. If you are just obtaining the HTML element, however, document.body.parentNode seems to be quite a bit faster.

After you have the HTML element, you can mess with the attributes with the getAttribute and setAttribute methods.

For the DOCTYPE, you could use document.doctype, which was elaborated upon in this question.

How to refresh activity after changing language (Locale) inside application

This approach will work on all API level device.

  1. Use Base Activity for attachBaseContext to set the locale language and extend this activity for all activities

    open class  BaseAppCompactActivity() : AppCompatActivity() {
    
        override fun attachBaseContext(newBase: Context) {
            super.attachBaseContext(LocaleHelper.onAttach(newBase))    
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)           
        }
    }
    
  2. Use Application attachBaseContext and onConfigurationChanged to set the locale language

    public class MyApplication extends Application {
        private static MyApplication application;
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        public static MyApplication getApplication() {
            return application;
        }
    
        /**
         * overide to change local sothat language can be chnaged from android device  nogaut and above
         */
        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(LocaleHelper.INSTANCE.onAttach(base));
        }
    
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            setLanguageFromNewConfig(newConfig);
            super.onConfigurationChanged(newConfig);
        }
    
        /*** also handle chnage  language if  device language chnaged **/
        private void setLanguageFromNewConfig(Configuration newConfig){
            Prefs.putSaveLocaleLanguage(this,  selectedLocaleLanguage );
            LocaleHelper.INSTANCE.onAttach(this);
        }
    
  3. Use Locale Helper for handling language changes, this approach work on all device

    object LocaleHelper {
        private var defaultLanguage  :String = KycUtility.KYC_LANGUAGE.ENGLISH.languageCode
    
        fun onAttach(context: Context, defaultLanguage: String): Context {
            return setLocale(context, defaultLanguage)
        }
    
    
    
        fun setLocale(context: Context, language: String): Context {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                updateResources(context, language)
            } else updateResourcesLegacy(context, language)
    
        }
    
    
        @TargetApi(Build.VERSION_CODES.N)
        private fun updateResources(context: Context, language: String): Context {
            val locale = Locale(language)
            Locale.setDefault(locale)
    
            val configuration = context.getResources().getConfiguration()
            configuration.setLocale(locale)
            configuration.setLayoutDirection(locale)
    
            return context.createConfigurationContext(configuration)
        }
    
        private fun updateResourcesLegacy(context: Context, language: String): Context {
            val locale = Locale(language)
            Locale.setDefault(locale)
    
            val resources = context.getResources()
    
            val configuration = resources.getConfiguration()
            configuration.locale = locale
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLayoutDirection(locale)
            }
            resources.updateConfiguration(configuration, resources.getDisplayMetrics())
            return context
        }
    }
    

Dockerfile copy keep subdirectory structure

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

How to call webmethod in Asp.net C#

I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.

Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.

jQuery

jQuery.ajax({
    url: 'AddToCart.aspx',
    type: "POST",
    data: {
        method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
    },
    dataType: "json",
    beforeSend: function () {
        alert("Start!!! ");
    },
    success: function (data) {
        alert("a");
    },
    failure: function (msg) { alert("Sorry!!! "); }
});

C# Page Load:

if (!Page.IsPostBack)
{
    if (Request.Form["method"] == "AddTo_Cart")
    {
        int q, id;
        int.TryParse(Request.Form["quantity"], out q);
        int.TryParse(Request.Form["itemId"], out id);
        AddTo_Cart(q,id);
    }
}

number_format() with MySQL

http://blogs.mysql.com/peterg/2009/04/

In Mysql 6.1 you will be able to do FORMAT(X,D [,locale_name] )

As in

 SELECT format(1234567,2,’de_DE’);

For now this ability does not exist, though you MAY be able to set your locale in your database my.ini check it out.

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Adding this to build.gradle (Module app) worked for me:
compile 'com.android.support:support-annotations:27.1.1'

What's the fastest way to convert String to Number in JavaScript?

A fast way to convert strings to an integer is to use a bitwise or, like so:

x | 0

While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x) since it will first cast x to a number and then perform a very efficient or.

Fastest way to get the first object from a queryset in django?

Use the convenience methods .first() and .last():

MyModel.objects.filter(blah=blah).first()

They both swallow the resulting exception and return None if the queryset returns no objects.

These were added in Django 1.6, which was released in Nov 2013.

Adobe Reader Command Line Reference

Having /A without additional parameters other than the filename didn't work for me, but the following code worked fine with /n

string sfile = @".\help\delta-pqca-400-100-300-fc4-user-manual.pdf";
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AcroRd32.exe"; 
myProcess.StartInfo.Arguments = " /n " + "\"" + sfile + "\"";
myProcess.Start();

How to check if another instance of my shell script is running

pidof wasn't working for me so I searched some more and came across pgrep

for pid in $(pgrep -f my_script.sh); do
    if [ $pid != $$ ]; then
        echo "[$(date)] : my_script.sh : Process is already running with PID $pid"
        exit 1
    else
      echo "Running with PID $pid"
    fi  
done

Taken in part from answers above and https://askubuntu.com/a/803106/802276

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are talking about Datepicker for bootstrap, you set the start date (the min date) by using the following:

$('#datepicker').datepicker('setStartDate', <DATETIME STRING HERE>);

Python style - line continuation with strings?

This is a pretty clean way to do it:

myStr = ("firstPartOfMyString"+
         "secondPartOfMyString"+
         "thirdPartOfMyString")

Bootstrap: adding gaps between divs

I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>

Navigation Controller Push View Controller

Use this code in your button action (Swift 3.0.1):

let vc = self.storyboard?.instantiateViewController(
    withIdentifier: "YourSecondVCIdentifier") as! SecondVC

navigationController?.pushViewController(vc, animated: true)

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

Please note that if you want to use IPv6, you probably want to use HTTP_HOST rather than SERVER_NAME . If you enter http://[::1]/ the environment variables will be the following:

HTTP_HOST = [::1]
SERVER_NAME = ::1

This means, that if you do a mod_rewrite for example, you might get a nasty result. Example for a SSL redirect:

# SERVER_NAME will NOT work - Redirection to https://::1/
RewriteRule .* https://%{SERVER_NAME}/

# HTTP_HOST will work - Redirection to https://[::1]/
RewriteRule .* https://%{HTTP_HOST}/

This applies ONLY if you access the server without an hostname.

IOError: [Errno 32] Broken pipe: Python

I feel obliged to point out that the method using

signal(SIGPIPE, SIG_DFL) 

is indeed dangerous (as already suggested by David Bennet in the comments) and in my case led to platform-dependent funny business when combined with multiprocessing.Manager (because the standard library relies on BrokenPipeError being raised in several places). To make a long and painful story short, this is how I fixed it:

First, you need to catch the IOError (Python 2) or BrokenPipeError (Python 3). Depending on your program you can try to exit early at that point or just ignore the exception:

from errno import EPIPE

try:
    broken_pipe_exception = BrokenPipeError
except NameError:  # Python 2
    broken_pipe_exception = IOError

try:
    YOUR CODE GOES HERE
except broken_pipe_exception as exc:
    if broken_pipe_exception == IOError:
        if exc.errno != EPIPE:
            raise

However, this isn't enough. Python 3 may still print a message like this:

Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

Unfortunately getting rid of that message is not straightforward, but I finally found http://bugs.python.org/issue11380 where Robert Collins suggests this workaround that I turned into a decorator you can wrap your main function with (yes, that's some crazy indentation):

from functools import wraps
from sys import exit, stderr, stdout
from traceback import print_exc


def suppress_broken_pipe_msg(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except SystemExit:
            raise
        except:
            print_exc()
            exit(1)
        finally:
            try:
                stdout.flush()
            finally:
                try:
                    stdout.close()
                finally:
                    try:
                        stderr.flush()
                    finally:
                        stderr.close()
    return wrapper


@suppress_broken_pipe_msg
def main():
    YOUR CODE GOES HERE

How to copy a file to another path?

Yes. It will work: FileInfo.CopyTo Method

Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.

All other responses are correct, but since you asked for FileInfo, here's a sample:

FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten

Basic authentication for REST API using spring restTemplate

You may use spring-boot RestTemplateBuilder

@Bean
RestOperations rest(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("user", "password").build();
}

See documentation

(before SB 2.1.0 it was #basicAuthorization)

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

This worked perfectly for me without css. I think css would put some icing on the cake though.

    <form>
        <label for="First Name" >First Name:</label>
            <input type="text" name="username" size="15" maxlength="30" />
        <label for="Last Name" >Last Name:</label>
            <input type="text" name="username" size="15" maxlength="30" />
    </form>

Difference between 'cls' and 'self' in Python classes?

cls implies that method belongs to the class while self implies that the method is related to instance of the class,therefore member with cls is accessed by class name where as the one with self is accessed by instance of the class...it is the same concept as static member and non-static members in java if you are from java background.

Java, Shifting Elements in an Array

Try this:

Object temp = pool[position];

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

Look here to see it working: http://www.ideone.com/5JfAg

How to import an existing directory into Eclipse?

These days, there's a better solution for importing an existing PHP project. The PDT plugin now has an option on the New PHP Project dialog just for this. So:

From File->New->PHP Project:

New PHP Project Dialog with "Create project at existing location" options badly circled

.NET unique object identifier

If you are writing a module in your own code for a specific usage, majkinetor's method MIGHT have worked. But there are some problems.

First, the official document does NOT guarantee that the GetHashCode() returns an unique identifier (see Object.GetHashCode Method ()):

You should not assume that equal hash codes imply object equality.

Second, assume you have a very small amount of objects so that GetHashCode() will work in most cases, this method can be overridden by some types.
For example, you are using some class C and it overrides GetHashCode() to always return 0. Then every object of C will get the same hash code. Unfortunately, Dictionary, HashTable and some other associative containers will make use this method:

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

So, this approach has great limitations.

And even more, what if you want to build a general purpose library? Not only are you not able to modify the source code of the used classes, but their behavior is also unpredictable.

I appreciate that Jon and Simon have posted their answers, and I will post a code example and a suggestion on performance below.

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Collections.Generic;


namespace ObjectSet
{
    public interface IObjectSet
    {
        /// <summary> check the existence of an object. </summary>
        /// <returns> true if object is exist, false otherwise. </returns>
        bool IsExist(object obj);

        /// <summary> if the object is not in the set, add it in. else do nothing. </summary>
        /// <returns> true if successfully added, false otherwise. </returns>
        bool Add(object obj);
    }

    public sealed class ObjectSetUsingConditionalWeakTable : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingConditionalWeakTable objSet = new ObjectSetUsingConditionalWeakTable();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            return objectSet.TryGetValue(obj, out tryGetValue_out0);
        }

        public bool Add(object obj) {
            if (IsExist(obj)) {
                return false;
            } else {
                objectSet.Add(obj, null);
                return true;
            }
        }

        /// <summary> internal representation of the set. (only use the key) </summary>
        private ConditionalWeakTable<object, object> objectSet = new ConditionalWeakTable<object, object>();

        /// <summary> used to fill the out parameter of ConditionalWeakTable.TryGetValue(). </summary>
        private static object tryGetValue_out0 = null;
    }

    [Obsolete("It will crash if there are too many objects and ObjectSetUsingConditionalWeakTable get a better performance.")]
    public sealed class ObjectSetUsingObjectIDGenerator : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingObjectIDGenerator objSet = new ObjectSetUsingObjectIDGenerator();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            bool firstTime;
            idGenerator.HasId(obj, out firstTime);
            return !firstTime;
        }

        public bool Add(object obj) {
            bool firstTime;
            idGenerator.GetId(obj, out firstTime);
            return firstTime;
        }


        /// <summary> internal representation of the set. </summary>
        private ObjectIDGenerator idGenerator = new ObjectIDGenerator();
    }
}

In my test, the ObjectIDGenerator will throw an exception to complain that there are too many objects when creating 10,000,000 objects (10x than in the code above) in the for loop.

Also, the benchmark result is that the ConditionalWeakTable implementation is 1.8x faster than the ObjectIDGenerator implementation.

ASP.Net which user account running Web Service on IIS 7?

Server 2008

Start Task Manager Find w3wp.exe process (description IIS Worker Process) Check User Name column to find who you're IIS process is running as.

In the IIS GUI you can configure your application pool to run as a specific user: Application Pool default Advanced Settings Identity

Here's the info from Microsoft on setting up Application Pool Identites:

http://learn.iis.net/page.aspx/624/application-pool-identities/

application/x-www-form-urlencoded or multipart/form-data?

Just a little hint from my side for uploading HTML5 canvas image data:

I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling for at least an hour and I did not get it to save the image correctly on my server.

Once I set the contentType option of my jQuery ajax call to application/x-www-form-urlencoded everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.


Maybe that helps someone!

TypeScript error TS1005: ';' expected (II)

I had today a similar error message. What was peculiar is that it did not break the Application. It was running smoothly but the command prompt (Windows machine) indicated there was an error. I did not update the Typescript version but found another culprit. It turned there was a tiny omission of symbol - closing ")", which I believe The Typescript is compensating for. Just for reference the code is the following:

[new Object('First Characteristic','Second Characteristic',
'Third Characteristic'*] 

* notice here the ending ")" is missing.

Once brought back no more issues on the command prompt!

Get the POST request body from HttpServletRequest

If the request body is empty, then it simply means that it's already been consumed beforehand. For example, by a request.getParameter(), getParameterValues() or getParameterMap() call. Just remove the lines doing those calls from your code.

Scala: write string to file in one statement

import sys.process._
"echo hello world" #> new java.io.File("/tmp/example.txt") !

Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

    <form id="formAddName">
      <fieldset>
        <legend>Add Name </legend>
            <label for="firstName">First Name</label>
            <input type="text" id="firstName" name="firstName" />

        <button>Add</button>
      </fieldset>
    </form>

      <ol id="demo"></ol>

<script>
    var list = document.getElementById('demo');
    var entry = document.getElementById('formAddName');
    entry.onsubmit = function(evt) {
    evt.preventDefault();
    var firstName = document.getElementById('firstName').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstName));
    list.appendChild(entry);
  }
</script>

In WPF, what are the differences between the x:Name and Name attributes?

There really is only one name in XAML, the x:Name. A framework, such as WPF, can optionally map one of its properties to XAML's x:Name by using the RuntimeNamePropertyAttribute on the class that designates one of the classes properties as mapping to the x:Name attribute of XAML.

The reason this was done was to allow for frameworks that already have a concept of "Name" at runtime, such as WPF. In WPF, for example, FrameworkElement introduces a Name property.

In general, a class does not need to store the name for x:Name to be useable. All x:Name means to XAML is generate a field to store the value in the code behind class. What the runtime does with that mapping is framework dependent.

So, why are there two ways to do the same thing? The simple answer is because there are two concepts mapped onto one property. WPF wants the name of an element preserved at runtime (which is usable through Bind, among other things) and XAML needs to know what elements you want to be accessible by fields in the code behind class. WPF ties these two together by marking the Name property as an alias of x:Name.

In the future, XAML will have more uses for x:Name, such as allowing you to set properties by referring to other objects by name, but in 3.5 and prior, it is only used to create fields.

Whether you should use one or the other is really a style question, not a technical one. I will leave that to others for a recommendation.

See also AutomationProperties.Name VS x:Name, AutomationProperties.Name is used by accessibility tools and some testing tools.

How can I export a GridView.DataSource to a datatable or dataset?

Assuming your DataSource is of type DataTable, you can just do this:

myGridView.DataSource as DataTable

Can I apply a CSS style to an element name?

have you explored the possibility of using jQuery? It has a very reach selector model (similar in syntax to CSS) and even if your elements don't have IDs, you should be able to select them using parent --> child --> grandchild relationship. Once you have them selected, there's a very simple method call (I forget the exact name) that allows you to apply CSS style to the element(s).

It should be simple to use and as a bonus, you'll most likely be very cross-platform compatible.

How do I convert a double into a string in C++?

Normaly for this operations you have to use the ecvt, fcvt or gcvt Functions:

/* gcvt example */
#include <stdio.h>
#include <stdlib.h>

main ()
{
  char buffer [20];
  gcvt (1365.249,6,buffer);
  puts (buffer);
  gcvt (1365.249,3,buffer);
  puts (buffer);
  return 0;
}

Output:
1365.25
1.37e+003   

As a Function:

void double_to_char(double f,char * buffer){
  gcvt(f,10,buffer);
}

Node.js: get path from the request

Based on @epegzz suggestion for the regex.

( url ) => {
  return url.match('^[^?]*')[0].split('/').slice(1)
}

returns an array with paths.

How to import module when module name has a '-' dash or hyphen in it?

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

Possible to access MVC ViewBag object from Javascript file?

Create a view and return it as a partial view:

public class AssetsController : Controller
{
    protected void SetMIME(string mimeType)
    {
        this.Response.AddHeader("Content-Type", mimeType);
        this.Response.ContentType = mimeType;
    }

    // this will render a view as a Javascript file
    public ActionResult GlobalJS()
    {
        this.SetMIME("text/javascript");
        return PartialView();
    }
}

Then in the GlobalJS view add the javascript code like (adding the // will make visual studio intellisense read it as java-script)

//<script>

    $(document).ready(function () {
       alert('@ViewBag.PropertyName');
    }); 

//</script>

Then in your final view you can add a reference to the javascript just like this.

<script src="@Url.Action("GlobalJS", "Assets")"></script> 

Then in your final view controller you can create/pass your ViewBags and it will be rendered in your javascript.

public class MyFinalViewController : Controller
{
    public ActionResult Index()
    {
        ViewBag.PropertyName = "My ViewBag value!";
        return View();
    }
}

Hope it helps.

How to add a default include path for GCC in Linux?

just a note: CPLUS_INCLUDE_PATH and C_INCLUDE_PATH are not the equivalent of LD_LIBRARY_PATH. LD_LIBRARY_PATH serves the ld (the dynamic linker at runtime) whereas the equivalent of the former two that serves your C/C++ compiler with the location of libraries is LIBRARY_PATH.

Detect & Record Audio in Python

As a follow up to Nick Fortescue's answer, here's a more complete example of how to record from the microphone and process the resulting data:

from sys import byteorder
from array import array
from struct import pack

import pyaudio
import wave

THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100

def is_silent(snd_data):
    "Returns 'True' if below the 'silent' threshold"
    return max(snd_data) < THRESHOLD

def normalize(snd_data):
    "Average the volume out"
    MAXIMUM = 16384
    times = float(MAXIMUM)/max(abs(i) for i in snd_data)

    r = array('h')
    for i in snd_data:
        r.append(int(i*times))
    return r

def trim(snd_data):
    "Trim the blank spots at the start and end"
    def _trim(snd_data):
        snd_started = False
        r = array('h')

        for i in snd_data:
            if not snd_started and abs(i)>THRESHOLD:
                snd_started = True
                r.append(i)

            elif snd_started:
                r.append(i)
        return r

    # Trim to the left
    snd_data = _trim(snd_data)

    # Trim to the right
    snd_data.reverse()
    snd_data = _trim(snd_data)
    snd_data.reverse()
    return snd_data

def add_silence(snd_data, seconds):
    "Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
    silence = [0] * int(seconds * RATE)
    r = array('h', silence)
    r.extend(snd_data)
    r.extend(silence)
    return r

def record():
    """
    Record a word or words from the microphone and 
    return the data as an array of signed shorts.

    Normalizes the audio, trims silence from the 
    start and end, and pads with 0.5 seconds of 
    blank sound to make sure VLC et al can play 
    it without getting chopped off.
    """
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=1, rate=RATE,
        input=True, output=True,
        frames_per_buffer=CHUNK_SIZE)

    num_silent = 0
    snd_started = False

    r = array('h')

    while 1:
        # little endian, signed short
        snd_data = array('h', stream.read(CHUNK_SIZE))
        if byteorder == 'big':
            snd_data.byteswap()
        r.extend(snd_data)

        silent = is_silent(snd_data)

        if silent and snd_started:
            num_silent += 1
        elif not silent and not snd_started:
            snd_started = True

        if snd_started and num_silent > 30:
            break

    sample_width = p.get_sample_size(FORMAT)
    stream.stop_stream()
    stream.close()
    p.terminate()

    r = normalize(r)
    r = trim(r)
    r = add_silence(r, 0.5)
    return sample_width, r

def record_to_file(path):
    "Records from the microphone and outputs the resulting data to 'path'"
    sample_width, data = record()
    data = pack('<' + ('h'*len(data)), *data)

    wf = wave.open(path, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(sample_width)
    wf.setframerate(RATE)
    wf.writeframes(data)
    wf.close()

if __name__ == '__main__':
    print("please speak a word into the microphone")
    record_to_file('demo.wav')
    print("done - result written to demo.wav")

How to compare two dates in Objective-C

In Cocoa, to compare dates, use one of isEqualToDate, compare, laterDate, and earlierDate methods on NSDate objects, instantiated with the dates you need.

Documentation:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/isEqualToDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/earlierDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/laterDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/compare:

How to search text using php if ($text contains "World")

If you are looking an algorithm to rank search results based on relevance of multiple words here comes a quick and easy way of generating search results with PHP only.

Implementation of the vector space model in PHP

function get_corpus_index($corpus = array(), $separator=' ') {

    $dictionary = array();
    $doc_count = array();

    foreach($corpus as $doc_id => $doc) {
        $terms = explode($separator, $doc);
        $doc_count[$doc_id] = count($terms);

        // tf–idf, short for term frequency–inverse document frequency, 
        // according to wikipedia is a numerical statistic that is intended to reflect 
        // how important a word is to a document in a corpus

        foreach($terms as $term) {
            if(!isset($dictionary[$term])) {
                $dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
            }
            if(!isset($dictionary[$term]['postings'][$doc_id])) {
                $dictionary[$term]['document_frequency']++;
                $dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
            }

            $dictionary[$term]['postings'][$doc_id]['term_frequency']++;
        }

        //from http://phpir.com/simple-search-the-vector-space-model/

    }

    return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}

function get_similar_documents($query='', $corpus=array(), $separator=' '){

    $similar_documents=array();

    if($query!=''&&!empty($corpus)){

        $words=explode($separator,$query);
        $corpus=get_corpus_index($corpus);
        $doc_count=count($corpus['doc_count']);

        foreach($words as $word) {
            $entry = $corpus['dictionary'][$word];
            foreach($entry['postings'] as $doc_id => $posting) {

                //get term frequency–inverse document frequency
                $score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);

                if(isset($similar_documents[$doc_id])){
                    $similar_documents[$doc_id]+=$score;
                }
                else{
                    $similar_documents[$doc_id]=$score;
                }

            }
        }

        // length normalise
        foreach($similar_documents as $doc_id => $score) {
            $similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
        }

        // sort fro  high to low
        arsort($similar_documents);
    }   
    return $similar_documents;
}

IN YOUR CASE

$query = 'world';

$corpus = array(
    1 => 'hello world',
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

RESULTS

Array
(
    [1] => 0.79248125036058
)

MATCHING MULTIPLE WORDS AGAINST MULTIPLE PHRASES

$query = 'hello world';

$corpus = array(
    1 => 'hello world how are you today?',
    2 => 'how do you do world',
    3 => 'hello, here you are! how are you? Are we done yet?'
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

RESULTS

Array
(
    [1] => 0.74864218272161
    [2] => 0.43398500028846
)

from How do I check if a string contains a specific word in PHP?

Convert JSON string to array of JSON objects in Javascript

Using jQuery:

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');

jsonObj is your JSON object.

Replace Fragment inside a ViewPager

I followed the answers by @wize and @mdelolmo and I got the solution. Thanks Tons. But, I tuned these solutions a little bit to improve the memory consumption.

Problems I observed:

They save the instance of Fragment which is replaced. In my case, it is a Fragment which holds MapView and I thought its costly. So, I am maintaining the FragmentPagerPositionChanged (POSITION_NONE or POSITION_UNCHANGED) instead of Fragment itself.

Here is my implementation.

  public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {

    private SwitchFragListener mSwitchFragListener;
    private Switch mToggle;
    private int pagerAdapterPosChanged = POSITION_UNCHANGED;
    private static final int TOGGLE_ENABLE_POS = 2;


    public DemoCollectionPagerAdapter(FragmentManager fm, Switch toggle) {
        super(fm);
        mToggle = toggle;

        mSwitchFragListener = new SwitchFragListener();
        mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mSwitchFragListener.onSwitchToNextFragment();
            }
        });
    }

    @Override
    public Fragment getItem(int i) {
        switch (i)
        {
            case TOGGLE_ENABLE_POS:
                if(mToggle.isChecked())
                {
                    return TabReplaceFragment.getInstance();
                }else
                {
                    return DemoTab2Fragment.getInstance(i);
                }

            default:
                return DemoTabFragment.getInstance(i);
        }
    }

    @Override
    public int getCount() {
        return 5;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Tab " + (position + 1);
    }

    @Override
    public int getItemPosition(Object object) {

        //  This check make sures getItem() is called only for the required Fragment
        if (object instanceof TabReplaceFragment
                ||  object instanceof DemoTab2Fragment)
            return pagerAdapterPosChanged;

        return POSITION_UNCHANGED;
    }

    /**
     * Switch fragments Interface implementation
     */
    private final class SwitchFragListener implements
            SwitchFragInterface {

        SwitchFragListener() {}

        public void onSwitchToNextFragment() {

            pagerAdapterPosChanged = POSITION_NONE;
            notifyDataSetChanged();
        }
    }

    /**
     * Interface to switch frags
     */
    private interface SwitchFragInterface{
        void onSwitchToNextFragment();
    }
}

Demo link here.. https://youtu.be/l_62uhKkLyM

For demo purpose, used 2 fragments TabReplaceFragment and DemoTab2Fragment at position two. In all the other cases I'm using DemoTabFragment instances.

Explanation:

I'm passing Switch from Activity to the DemoCollectionPagerAdapter. Based on the state of this switch we will display correct fragment. When the switch check is changed, I'm calling the SwitchFragListener's onSwitchToNextFragment method, where I'm changing the value of pagerAdapterPosChanged variable to POSITION_NONE. Check out more about POSITION_NONE. This will invalidate the getItem and I have logics to instantiate the right fragment over there. Sorry, if the explanation is a bit messy.

Once again big thanks to @wize and @mdelolmo for the original idea.

Hope this is helpful. :)

Let me know if this implementation has any flaws. That will be greatly helpful for my project.

Why is my CSS bundling not working with a bin deployed MVC4 app?

As an addendum to the existing answers, none of which worked for me I found my solution HERE:

https://bundletransformer.codeplex.com/discussions/429707

The solution was to

  1. right click the .less files in visual studio
  2. Select properties
  3. Mark the Build Action as Content
  4. Redeploy

I did NOT need to remove extensionless handlers (as can be found in other solutions on the internet)

I did NOT have to add the <add name="BundleModule" type="System.Web.Optimization.BundleModule" /> web.config setting.

Hope this helps!

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

For me the issue is resolved by adding domain name in user name as follow:

string userName="yourUserName";
string password="passowrd";
string hostName="LdapServerHostName";
string domain="yourDomain";
System.DirectoryServices.AuthenticationTypes option = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer; 
string userNameWithDomain = string.Format("{0}@{1}",userName , domain);
DirectoryEntry directoryOU = new DirectoryEntry("LDAP://" + hostName, userNameWithDomain, password, option);

How to raise a ValueError?

>>> response='bababa'
...  if "K" in response.text:
...     raise ValueError("Not found")

Responsive image map

http://home.comcast.net/~urbanjost/semaphore.html is the top page for the discussion, and actually has links to a JavaScript-based solution to the problem. I have received a notice that HTML will support percent units in the future but I haven't seen any progress on this in quite some time (it has probably been over a year since I heard support would be forthcoming) so the work-around is probably worth looking at if you are comfortable with JavaScript/ECMAScript.

Where are SQL Server connection attempts logged?

If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.

Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.

If you want to audit a client application name along with each failed login, you can use an Extended Events session.

To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/

Dynamically update values of a chartjs chart

You can check instance of Chart by using Chart.instances. This will give you all the charts instances. Now you can iterate on that instances and and change the data, which is present inside config. suppose you have only one chart in your page.

for (var _chartjsindex in Chart.instances) {
/* 
 * Here in the config your actual data and options which you have given at the 
   time of creating chart so no need for changing option only you can change data
*/
 Chart.instances[_chartjsindex].config.data = [];
 // here you can give add your data
 Chart.instances[_chartjsindex].update();
 // update will rewrite your whole chart with new value
 }

Error: «Could not load type MvcApplication»

I had this error again and none of the above worked for me. I had to remove the following node in .csproj file: <VisualStudio>....</VisualStudio>. Reloaded VS and it worked.

FYI, VS was able to recreate the node and then I recreated the website in IIS (through VS) and it worked perfectly.

Hopefully this will help someone.

Java Process with Input/Output Stream

I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:

Thread T=new Thread(new Runnable() {

    @Override
    public void run() {
        while(true)
        {
            String input = scan.nextLine();
            input += "\n";
            try {
                writer.write(input);
                writer.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
} );
T.start();

and you can reader will be same as above i.e.

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);
}

make your writer as final otherwise it wont be able to accessible by inner class.

Ignore duplicates when producing map using streams

For grouping by Objects

Map<Integer, Data> dataMap = dataList.stream().collect(Collectors.toMap(Data::getId, data-> data, (data1, data2)-> {LOG.info("Duplicate Group For :" + data2.getId());return data1;}));

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

Change user-agent for Selenium web-driver

To build on JJC's helpful answer that builds on Louis's helpful answer...

With PhantomJS 2.1.1-windows this line works:

driver.execute_script("return navigator.userAgent")

If it doesn't work, you can still get the user agent via the log (to build on Mma's answer):

from selenium import webdriver
import json
from fake_useragent import UserAgent

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])

How to return a string value from a Bash function

All answers above ignore what has been stated in the man page of bash.

  • All variables declared inside a function will be shared with the calling environment.
  • All variables declared local will not be shared.

Example code

#!/bin/bash

f()
{
    echo function starts
    local WillNotExists="It still does!"
    DoesNotExists="It still does!"
    echo function ends
}

echo $DoesNotExists #Should print empty line
echo $WillNotExists #Should print empty line
f                   #Call the function
echo $DoesNotExists #Should print It still does!
echo $WillNotExists #Should print empty line

And output

$ sh -x ./x.sh
+ echo

+ echo

+ f
+ echo function starts 
function starts
+ local 'WillNotExists=It still does!'
+ DoesNotExists='It still does!'
+ echo function ends 
function ends
+ echo It still 'does!' 
It still does!
+ echo

Also under pdksh and ksh this script does the same!

What are the undocumented features and limitations of the Windows FINDSTR command?

When several commands are enclosed in parentheses and there are redirected files to the whole block:

< input.txt (
   command1
   command2
   . . .
) > output.txt

... then the files remains open as long as the commands in the block be active, so the commands may move the file pointer of the redirected files. Both MORE and FIND commands move the Stdin file pointer to the beginning of the file before process it, so the same file may be processed several times inside the block. For example, this code:

more < input.txt >  output.txt
more < input.txt >> output.txt

... produce the same result than this one:

< input.txt (
   more
   more
) > output.txt

This code:

find    "search string" < input.txt > matchedLines.txt
find /V "search string" < input.txt > unmatchedLines.txt

... produce the same result than this one:

< input.txt (
   find    "search string" > matchedLines.txt
   find /V "search string" > unmatchedLines.txt
)

FINDSTR is different; it does not move the Stdin file pointer from its current position. For example, this code insert a new line after a search line:

call :ProcessFile < input.txt
goto :EOF

:ProcessFile
   rem Read the next line from Stdin and copy it
   set /P line=
   echo %line%
   rem Test if it is the search line
   if "%line%" neq "search line" goto ProcessFile
rem Insert the new line at this point
echo New line
rem And copy the rest of lines
findstr "^"
exit /B

We may make good use of this feature with the aid of an auxiliary program that allow us to move the file pointer of a redirected file, as shown in this example.

This behavior was first reported by jeb at this post.


EDIT 2018-08-18: New FINDSTR bug reported

The FINDSTR command have a strange bug that happen when this command is used to show characters in color AND the output of such a command is redirected to CON device. For details on how use FINDSTR command to show text in color, see this topic.

When the output of this form of FINDSTR command is redirected to CON, something strange happens after the text is output in the desired color: all the text after it is output as "invisible" characters, although a more precise description is that the text is output as black text over black background. The original text will appear if you use COLOR command to reset the foreground and background colors of the entire screen. However, when the text is "invisible" we could execute a SET /P command, so all characters entered will not appear on the screen. This behavior may be used to enter passwords.

@echo off
setlocal

set /P "=_" < NUL > "Enter password"
findstr /A:1E /V "^$" "Enter password" NUL > CON
del "Enter password"
set /P "password="
cls
color 07
echo The password read is: "%password%"

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

Might help some else - I came here because I missed putting two // after http:. This is what I had:

http:/abc.my.domain.com:55555/update

Creating a list of pairs in java

Use a List of custom class instances. The custom class is some sort of Pair or Coordinate or whatever. Then just

List<Coordinate> = new YourFavoriteListImplHere<Coordinate>()

This approach has the advantage that it makes satisfying this requirement "perform simple math (like multiplying the pair together to return a single float, etc)" clean, because your custom class can have methods for whatever maths you need to do...

Comparison of C++ unit test frameworks

API Sanity Checker — test framework for C/C++ libraries:

An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files.

The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.

Unique features in comparison with CppUnit, Boost and Google Test:

  • Automatic generation of test data and input arguments (even for complex data types)
  • Modern and highly reusable specialized types instead of fixtures and templates

What's the meaning of exception code "EXC_I386_GPFLT"?

EXC_I386_GPFLT is surely referring to "General Protection fault", which is the x86's way to tell you that "you did something that you are not allowed to do". It typically DOESN'T mean that you access out of memory bounds, but it could be that your code is going out of bounds and causing bad code/data to be used in a way that makes for an protection violation of some sort.

Unfortunately it can be hard to figure out exactly what the problem is without more context, there are 27 different causes listed in my AMD64 Programmer's Manual, Vol 2 from 2005 - by all accounts, it is likely that 8 years later would have added a few more.

If it is a 64-bit system, a plausible scenario is that your code is using a "non-canonical pointer" - meaning that a 64-bit address is formed in such a way that the upper 16 bits of the address aren't all copies of the top of the lower 48 bits (in other words, the top 16 bits of an address should all be 0 or all 1, based on the bit just below 16 bits). This rule is in place to guarantee that the architecture can "safely expand the number of valid bits in the address range". This would indicate that the code is either overwriting some pointer data with other stuff, or going out of bounds when reading some pointer value.

Another likely causes is unaligned access with an SSE register - in other word, reading a 16-byte SSE register from an address that isn't 16-byte aligned.

There are, as I said, many other possible reasons, but most of those involve things that "normal" code wouldn't be doing in a 32- or 64-bit OS (such as loading segment registers with invalid selector index or writing to MSR's (model specific registers)).

Using CSS td width absolute, position

If table width is for example 100%, try using a percentage width on td such as 20%.

How to deal with a slow SecureRandom generator?

I had a similar problem with calls to SecureRandom blocking for about 25 seconds at a time on a headless Debian server. I installed the haveged daemon to ensure /dev/random is kept topped up, on headless servers you need something like this to generate the required entropy. My calls to SecureRandom now perhaps take milliseconds.

Selecting specific rows and columns from NumPy array

Using np.ix_ is the most convenient way to do it (as answered by others), but here is another interesting way to do it:

>>> rows = [0, 1, 3]
>>> cols = [0, 2]

>>> a[rows].T[cols].T

array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

Passing a String by Reference in Java?

In Java nothing is passed by reference. Everything is passed by value. Object references are passed by value. Additionally Strings are immutable. So when you append to the passed String you just get a new String. You could use a return value, or pass a StringBuffer instead.

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

I have same issue, I found a working solution as below:

The reason is

    if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN

never use number type like id as

      if (id) {}

for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.

So for id type, we must use following:

   if ((Id !== undefined) && (Id !== null) && (Id !== "")){
                                                                                
                                                                            } else {

                                                                            }
                                                                            

for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.

       if (string_type_variable) { }

How to build a JSON array from mysql database

Use this

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

Javascript/Jquery Convert string to array

check this out :)

var traingIds = "[1,2]";  // ${triningIdArray} this value getting from server 
alert(traingIds);  // alerts [1,2]
var type = typeof(traingIds);
alert(type);   // // alerts String

//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds);  // alerts 1,2        
var trainindIdArray = traingIds.split(',');

?for(i = 0; i< trainindIdArray.length; i++){
    alert(trainindIdArray[i]); //outputs individual numbers in array
    }? 

What should my Objective-C singleton look like?

I usually use code roughly similar to that in Ben Hoffstein's answer (which I also got out of Wikipedia). I use it for the reasons stated by Chris Hanson in his comment.

However, sometimes I have a need to place a singleton into a NIB, and in that case I use the following:

@implementation Singleton

static Singleton *singleton = nil;

- (id)init {
    static BOOL initialized = NO;
    if (!initialized) {
        self = [super init];
        singleton = self;
        initialized = YES;
    }
    return self;
}

+ (id)allocWithZone:(NSZone*)zone {
    @synchronized (self) {
        if (!singleton)
            singleton = [super allocWithZone:zone];     
    }
    return singleton;
}

+ (Singleton*)sharedSingleton {
    if (!singleton)
        [[Singleton alloc] init];
    return singleton;
}

@end

I leave the implementation of -retain (etc.) to the reader, although the above code is all you need in a garbage collected environment.

$.widget is not a function

May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....

displayname attribute vs display attribute

Perhaps this is specific to .net core, I found DisplayName would not work but Display(Name=...) does. This may save someone else the troubleshooting involved :)

//using statements
using System;
using System.ComponentModel.DataAnnotations;  //needed for Display annotation
using System.ComponentModel;  //needed for DisplayName annotation

public class Whatever
{
    //Property
    [Display(Name ="Release Date")]
    public DateTime ReleaseDate { get; set; }
}


//cshtml file
@Html.DisplayNameFor(model => model.ReleaseDate)

How to trigger the window resize event in JavaScript?

You can do this with this library. https://github.com/itmor/events-js

const events = new Events();

events.add({  
  blockIsHidden: () =>  {
    if ($('div').css('display') === 'none') return true;
  }
});

function printText () {
  console.log('The block has become hidden!');
}

events.on('blockIsHidden', printText);

How do you format code in Visual Studio Code (VSCode)

If you want to custom the style of format-document, you should use Beautify extention.

Refer to this screenshot:

img

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

Best solution that i found is create a new database role i.e.

CREATE ROLE db_executor;

and then grant that role exec permission.

GRANT EXECUTE TO db_executor;

Now when you go to the properties of the user and go to User Mapping and select the database where you have added new role,now new role will be visible in the Database role membership for: section

For more detail read full article

Find in Files: Search all code in Team Foundation Server

This add-in claims to have the functionality that I believe you seek:

Team Foundation Sidekicks

Java Round up Any Number

I don't know why you are dividing by 100 but here my assumption int a;

int b = (int) Math.ceil( ((double)a) / 100);

or

int b = (int) Math.ceil( a / 100.0);

Can I write into the console in a unit test? If yes, why doesn't the console window open?

You could use this line to write to Output Window of the Visual Studio:

System.Diagnostics.Debug.WriteLine("Matrix has you...");

Must run in Debug mode.

Recursively counting files in a Linux directory

Since filenames in UNIX may contain newlines (yes, newlines), wc -l might count too many files. I would print a dot for every file and then count the dots:

find DIR_NAME -type f -printf "." | wc -c

error MSB6006: "cmd.exe" exited with code 1

Navigate from Error List Tab to the Visual Studios Output folder by one of the following:

  • Select tab Output in standard VS view at the bottom
  • Click in Menubar View > Output or Ctrl+Alt+O

where Show output from <build> should be selected.

You can find out more by analyzing the output logs.


In my case it was an error in the Cmake step, see below. It could be in any build step, as described in the other answers.

> -- Build Type is debug 
> CMake Error in CMakeLists.txt:
>     A logical block opening on the line
>     <path_to_file:line_number>    
>     is not closed.

Counting unique / distinct values by group in a data frame

Few years old .. although had similar requirement and ended up writing my own solution. Applying here:

 x<-data.frame(
 
 "Name"=c("Amy","Jack","Jack","Dave","Amy","Jack","Tom","Larry","Tom","Dave","Jack","Tom","Amy","Jack"),
 "OrderNo"=c(12,14,16,11,12,16,19,22,19,11,17,20,23,16)
)

table(sub("~.*","",unique(paste(x$Name,x$OrderNo,sep="~",collapse=NULL))))

  Amy  Dave  Jack Larry   Tom
    2     1     3     1     2

How to horizontally center a floating element of a variable width?

This works better when the id = container (which is the outer div) and id = contained (which is the inner div). The problem with the highly recommended solution is that it results in some cases into an horizontal scrolling bar when the browser is trying to cater for the left: -50% attribute. There is a good reference for this solution

        #container {
            text-align: center;
        }
        #contained {
            text-align: left;
            display: inline-block;
        }

Using android.support.v7.widget.CardView in my project (Eclipse)

Using Gradle or Android Studio, try adding a dependency on com.android.support:cardview-v7.

There does not seem to be a regular Android library project at this time for cardview-v7, leanback-v17, palette-v7, or recyclerview-v7. I have no idea if/when Google will ship such library projects.

Why has it failed to load main-class manifest attribute from a JAR file?

If your class path is fully specified in manifest, maybe you need the last version of java runtime environment. My problem fixed when i reinstalled the jre 8.

Pure CSS to make font-size responsive based on dynamic amount of characters

I used smth like this:

1.style.fontSize = 15.6/(document.getElementById("2").innerHTML.length)+ 'vw'

Where: 1 - parent div Id and 2 - Id of div with my text

Fade In Fade Out Android Animation in Java

Here is my solution using AnimatorSet which seems to be a bit more reliable than AnimationSet.

// Custom animation on image
ImageView myView = (ImageView)splashDialog.findViewById(R.id.splashscreenImage);

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(myView, "alpha",  1f, .3f);
fadeOut.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(myView, "alpha", .3f, 1f);
fadeIn.setDuration(2000);

final AnimatorSet mAnimationSet = new AnimatorSet();

mAnimationSet.play(fadeIn).after(fadeOut);

mAnimationSet.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        super.onAnimationEnd(animation);
        mAnimationSet.start();
    }
});
mAnimationSet.start();

Delete all the records

Use the DELETE statement

Delete From <TableName>

Eg:

Delete from Student;

TypeError: 'dict' object is not callable

Access the dictionary with square brackets.

strikes = [number_map[int(x)] for x in input_str.split()]

PHP: If internet explorer 6, 7, 8 , or 9

You can check the HTTP_USER_AGENT server variable. The user agent transfered by IE contains MSIE

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) { ... }

For specific versions you can extend your condition

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.') !== false) { ... }

Also see this related question.

Understanding SQL Server LOCKS on SELECT queries

I have to add an important comment. Everyone is mentioning that NOLOCKreads only dirty data. This is not precise. It is also possible that you'll get same row twice or whole row is skipped during your read. Reason is that you could ask for some data in same time when SQL Server is re-balancing b-tree.

Check another threads

https://stackoverflow.com/a/5469238/2108874

http://www.sqlmag.com/article/sql-server/quaere-verum-clustered-index-scans-part-iii.aspx)

With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice.

iconv - Detected an illegal character in input string

BE VERY CAREFUL, the problem may come from multibytes encoding and inappropriate PHP functions used...

It was the case for me and it took me a while to figure it out.

For example, I get the a string from MySQL using utf8mb4 (very common now to encode emojis):

$formattedString = strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WILL RETURN THE ERROR 'Detected an illegal character in input string'

The problem does not stand in iconv() but stands in strtolower() in this case.

The appropriate way is to use Multibyte String Functions mb_strtolower() instead of strtolower()

$formattedString = mb_strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WORK FINE

MORE INFO

More examples of this issue are available at this SO answer

PHP Manual on the Multibyte String

clear form values after submission ajax

You can do this inside your $.post calls success callback like this

$.post('mail.php',{name:$('#name').val(),
                              email:$('#e-mail').val(),
                              phone:$('#phone').val(),
                              message:$('#message').val()},

            //return the data
            function(data){

              //hide the graphic
              $('.bar').css({display:'none'});
              $('.loader').append(data);

              //clear fields
              $('input[type="text"],textarea').val('');

            });

how to convert a string to date in mysql?

As was told at MySQL Using a string column with date text as a date field, you can do

SELECT  STR_TO_DATE(yourdatefield, '%m/%d/%Y')
FROM    yourtable

You can also handle these date strings in WHERE clauses. For example

SELECT whatever
  FROM yourtable
 WHERE STR_TO_DATE(yourdatefield, '%m/%d/%Y') > CURDATE() - INTERVAL 7 DAY

You can handle all kinds of date/time layouts this way. Please refer to the format specifiers for the DATE_FORMAT() function to see what you can put into the second parameter of STR_TO_DATE().

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Github Push Error: RPC failed; result=22, HTTP code = 413

I already had "HTTPS//" in the git URL yet faced this error.

All I did was to add option -u with push and it worked.

git push -u origin master

Select method in List<t> Collection

Try this:

using System.Data.Linq;
var result = from i in list
             where i.age > 45
             select i;

Using lambda expression please use this Statement:

var result = list.where(i => i.age > 45);

How to clear all input fields in a specific div with jQuery?

This function is used to clear all the elements in the form including radio button, check-box, select, multiple select, password, text, textarea, file.

function clear_form_elements(class_name) {
  jQuery("."+class_name).find(':input').each(function() {
    switch(this.type) {
        case 'password':
        case 'text':
        case 'textarea':
        case 'file':
        case 'select-one':
        case 'select-multiple':
        case 'date':
        case 'number':
        case 'tel':
        case 'email':
            jQuery(this).val('');
            break;
        case 'checkbox':
        case 'radio':
            this.checked = false;
            break;
    }
  });
}

Difference between onCreate() and onStart()?

Take a look on life cycle of Activity enter image description here

Where

***onCreate()***

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().

***onStart()***

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

And you can write your simple class to take a look when these methods call

public class TestActivity extends Activity {
    /** Called when the activity is first created. */

    private final static String TAG = "TestActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i(TAG, "On Create .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onDestroy()
    */
    @Override
    protected void onDestroy() { 
        super.onDestroy();
        Log.i(TAG, "On Destroy .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onPause()
    */
    @Override
    protected void onPause() { 
        super.onPause();
        Log.i(TAG, "On Pause .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onRestart()
    */
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "On Restart .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onResume()
    */
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "On Resume .....");
    }

    /* (non-Javadoc)
    * @see android.app.Activity#onStart()
    */
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "On Start .....");
    }
    /* (non-Javadoc)
    * @see android.app.Activity#onStop()
    */
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "On Stop .....");
    }
}

Hope this will clear your confusion.

And take a look here for details.

Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.

Convert integer to hex and hex to integer

Here is the function for SQL server which converts integer value into its hexadecimal representation as a varchar. It should be easy to adapt to other database types

For example:

SELECT dbo.ToHex(4095) --> FFF

SQL:

CREATE FUNCTION ToHex(@value int)
RETURNS varchar(50)
AS
BEGIN
    DECLARE @seq char(16)
    DECLARE @result varchar(50)
    DECLARE @digit char(1)
    SET @seq = '0123456789ABCDEF'

    SET @result = SUBSTRING(@seq, (@value%16)+1, 1)

    WHILE @value > 0
    BEGIN
        SET @digit = SUBSTRING(@seq, ((@value/16)%16)+1, 1)

        SET @value = @value/16
        IF @value <> 0 SET @result = @digit + @result
    END 

    RETURN @result
END
GO

Performing Inserts and Updates with Dapper

We are looking at building a few helpers, still deciding on APIs and if this goes in core or not. See: https://code.google.com/archive/p/dapper-dot-net/issues/6 for progress.

In the mean time you can do the following

val = "my value";
cnn.Execute("insert into Table(val) values (@val)", new {val});

cnn.Execute("update Table set val = @val where Id = @id", new {val, id = 1});

etcetera

See also my blog post: That annoying INSERT problem

Update

As pointed out in the comments, there are now several extensions available in the Dapper.Contrib project in the form of these IDbConnection extension methods:

T Get<T>(id);
IEnumerable<T> GetAll<T>();
int Insert<T>(T obj);
int Insert<T>(Enumerable<T> list);
bool Update<T>(T obj);
bool Update<T>(Enumerable<T> list);
bool Delete<T>(T obj);
bool Delete<T>(Enumerable<T> list);
bool DeleteAll<T>();

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

git commit -a -m "Your commit message here"

will quickly commit all changes with the commit message. Git commit "title" and "description" (as you call them) are nothing more than just the first line, and the rest of the lines in the commit message, usually separated by a blank line, by convention. So using this command will just commit the "title" and no description.

If you want to commit a longer message, you can do that, but it depends on which shell you use.

In bash the quick way would be:

git commit -a -m $'Commit title\n\nRest of commit message...'

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are exactly the same. When you use it be consistent. Use one of them in your database

How to make Java work with SQL Server?

Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).

I used 1.5 for the other server, so I waisted a lot of time on this.

Tricky issue.

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

Ruby value of a hash key?

As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch instead of []. For fetch not to throw an exception when the key is not found, pass it a default value.

puts "ok" if hash.fetch('key', nil) == 'X'

Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .

How to print to the console in Android Studio?

Be careful when using Logcat, it will truncate your message after ~4,076 bytes which can cause a lot of headache if you're printing out large amounts of data.

To get around this you have to write a function that will break it up into multiple parts like so.

Correctly Parsing JSON in Swift 3

The problem is with the API interaction method. The JSON parsing is changed only in syntax. The main problem is with the way of fetching data. What you are using is a synchronous way of getting data. This doesn't work in every case. What you should be using is an asynchronous way to fetch data. In this way, you have to request data through the API and wait for it to respond with data. You can achieve this with URL session and third party libraries like Alamofire. Below is the code for URL Session method.

let urlString = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
let url = URL.init(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
    guard error == nil else {
        print(error)
    }
    do {
        let Data = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
        // Note if your data is coming in Array you should be using [Any]()
        //Now your data is parsed in Data variable and you can use it normally
        let currentConditions = Data["currently"] as! [String:Any]
        print(currentConditions)
        let currentTemperatureF = currentConditions["temperature"] as! Double
        print(currentTemperatureF)
    } catch let error as NSError {
        print(error)
    }
}.resume()

jQuery multiselect drop down menu

You could hack your own, not relying on jQuery plugins... though you'd need to keep track externally (in JS) of selected items since the transition would remove the selected state info:

<head>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
  <script type='text/javascript'>
    $(window).load(function(){
      $('#transactionType').focusin(function(){
        $('#transactionType').attr('multiple', true);
      });
      $('#transactionType').focusout(function(){
        $('#transactionType').attr('multiple', false);
      });
    });>  
  </script>
</head>
<body>
  <select id="transactionType">
    <option value="ALLOC">ALLOC</option>
    <option value="LOAD1">LOAD1</option>
    <option value="LOAD2">LOAD2</option>
  </select>  
</body>

How to secure the ASP.NET_SessionId cookie?

Going with Marcel's solution above to secure Forms Authentication cookie you should also update "authentication" config element to use SSL

<authentication mode="Forms">
   <forms ...  requireSSL="true" />
</authentication>

Other wise authentication cookie will not be https

See: http://msdn.microsoft.com/en-us/library/vstudio/1d3t3c61(v=vs.100).aspx

How to preview an image before and after upload?

On input type=file add an event onchange="preview()"

For the function preview() type:

thumb.src=URL.createObjectURL(event.target.files[0]);

Live example:

_x000D_
_x000D_
function preview() {
   thumb.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
    <input type="file" onchange="preview()">
    <img id="thumb" src="" width="150px"/>
</form>
_x000D_
_x000D_
_x000D_

PHP Curl And Cookies

You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Swift 5 version

The answers given here are either outdated or incorrect because they don't take into account the following:

  1. The pixel size of the image can differ from its point size that is returned by image.size.width/image.size.height.
  2. There can be various layouts used by pixel components in the image, such as BGRA, ABGR, ARGB etc. or may not have an alpha component at all, such as BGR and RGB. For example, UIView.drawHierarchy(in:afterScreenUpdates:) method can produce BGRA images.
  3. Color components can be premultiplied by the alpha for all pixels in the image and need to be divided by alpha in order to restore the original color.
  4. For memory optimization used by CGImage, the size of a pixel row in bytes can be greater than the mere multiplication of the pixel width by 4.

The code below is to provide a universal Swift 5 solution to get the UIColor of a pixel for all such special cases. The code is optimized for usability and clarity, not for performance.

public extension UIImage {

    var pixelWidth: Int {
        return cgImage?.width ?? 0
    }

    var pixelHeight: Int {
        return cgImage?.height ?? 0
    }

    func pixelColor(x: Int, y: Int) -> UIColor {
        assert(
            0..<pixelWidth ~= x && 0..<pixelHeight ~= y,
            "Pixel coordinates are out of bounds")

        guard
            let cgImage = cgImage,
            let data = cgImage.dataProvider?.data,
            let dataPtr = CFDataGetBytePtr(data),
            let colorSpaceModel = cgImage.colorSpace?.model,
            let componentLayout = cgImage.bitmapInfo.componentLayout
        else {
            assertionFailure("Could not get a pixel of an image")
            return .clear
        }

        assert(
            colorSpaceModel == .rgb,
            "The only supported color space model is RGB")
        assert(
            cgImage.bitsPerPixel == 32 || cgImage.bitsPerPixel == 24,
            "A pixel is expected to be either 4 or 3 bytes in size")

        let bytesPerRow = cgImage.bytesPerRow
        let bytesPerPixel = cgImage.bitsPerPixel/8
        let pixelOffset = y*bytesPerRow + x*bytesPerPixel

        if componentLayout.count == 4 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2],
                dataPtr[pixelOffset + 3]
            )

            var alpha: UInt8 = 0
            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgra:
                alpha = components.3
                red = components.2
                green = components.1
                blue = components.0
            case .abgr:
                alpha = components.0
                red = components.3
                green = components.2
                blue = components.1
            case .argb:
                alpha = components.0
                red = components.1
                green = components.2
                blue = components.3
            case .rgba:
                alpha = components.3
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            // If chroma components are premultiplied by alpha and the alpha is `0`,
            // keep the chroma components to their current values.
            if cgImage.bitmapInfo.chromaIsPremultipliedByAlpha && alpha != 0 {
                let invUnitAlpha = 255/CGFloat(alpha)
                red = UInt8((CGFloat(red)*invUnitAlpha).rounded())
                green = UInt8((CGFloat(green)*invUnitAlpha).rounded())
                blue = UInt8((CGFloat(blue)*invUnitAlpha).rounded())
            }

            return .init(red: red, green: green, blue: blue, alpha: alpha)

        } else if componentLayout.count == 3 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2]
            )

            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgr:
                red = components.2
                green = components.1
                blue = components.0
            case .rgb:
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            return .init(red: red, green: green, blue: blue, alpha: UInt8(255))

        } else {
            assertionFailure("Unsupported number of pixel components")
            return .clear
        }
    }

}

public extension UIColor {

    convenience init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
        self.init(
            red: CGFloat(red)/255,
            green: CGFloat(green)/255,
            blue: CGFloat(blue)/255,
            alpha: CGFloat(alpha)/255)
    }

}

public extension CGBitmapInfo {

    enum ComponentLayout {

        case bgra
        case abgr
        case argb
        case rgba
        case bgr
        case rgb

        var count: Int {
            switch self {
            case .bgr, .rgb: return 3
            default: return 4
            }
        }

    }

    var componentLayout: ComponentLayout? {
        guard let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue) else { return nil }
        let isLittleEndian = contains(.byteOrder32Little)

        if alphaInfo == .none {
            return isLittleEndian ? .bgr : .rgb
        }
        let alphaIsFirst = alphaInfo == .premultipliedFirst || alphaInfo == .first || alphaInfo == .noneSkipFirst

        if isLittleEndian {
            return alphaIsFirst ? .bgra : .abgr
        } else {
            return alphaIsFirst ? .argb : .rgba
        }
    }

    var chromaIsPremultipliedByAlpha: Bool {
        let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue)
        return alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast
    }

}

How to pass a parameter to routerLink that is somewhere inside the URL?

There are multiple ways of achieving this.

  • Through [routerLink] directive
  • The navigate(Array) method of the Router class
  • The navigateByUrl(string) method which takes a string and returns a promise

The routerLink attribute requires you to import the routingModule into the feature module in case you lazy loaded the feature module or just import the app-routing-module if it is not automatically added to the AppModule imports array.

  • RouterLink
<a [routerLink]="['/user', user.id]">John Doe</a>
<a routerLink="urlString">John Doe</a> // urlString is computed in your component
  • Navigate
// Inject Router into your component
// Inject ActivatedRoute into your component. This will allow the route to be done related to the current url
this._router.navigate(['user',user.id], {relativeTo: this._activatedRoute})
  • NavigateByUrl
this._router.navigateByUrl(urlString).then((bool) => {}).catch()

Regular expression to match balanced parentheses

because js regex doesn't support recursive match, i can't make balanced parentheses matching work.

so this is a simple javascript for loop version that make "method(arg)" string into array

push(number) map(test(a(a()))) bass(wow, abc)
$$(groups) filter({ type: 'ORGANIZATION', isDisabled: { $ne: true } }) pickBy(_id, type) map(test()) as(groups)
const parser = str => {
  let ops = []
  let method, arg
  let isMethod = true
  let open = []

  for (const char of str) {
    // skip whitespace
    if (char === ' ') continue

    // append method or arg string
    if (char !== '(' && char !== ')') {
      if (isMethod) {
        (method ? (method += char) : (method = char))
      } else {
        (arg ? (arg += char) : (arg = char))
      }
    }

    if (char === '(') {
      // nested parenthesis should be a part of arg
      if (!isMethod) arg += char
      isMethod = false
      open.push(char)
    } else if (char === ')') {
      open.pop()
      // check end of arg
      if (open.length < 1) {
        isMethod = true
        ops.push({ method, arg })
        method = arg = undefined
      } else {
        arg += char
      }
    }
  }

  return ops
}

// const test = parser(`$$(groups) filter({ type: 'ORGANIZATION', isDisabled: { $ne: true } }) pickBy(_id, type) map(test()) as(groups)`)
const test = parser(`push(number) map(test(a(a()))) bass(wow, abc)`)

console.log(test)

the result is like

[ { method: 'push', arg: 'number' },
  { method: 'map', arg: 'test(a(a()))' },
  { method: 'bass', arg: 'wow,abc' } ]
[ { method: '$$', arg: 'groups' },
  { method: 'filter',
    arg: '{type:\'ORGANIZATION\',isDisabled:{$ne:true}}' },
  { method: 'pickBy', arg: '_id,type' },
  { method: 'map', arg: 'test()' },
  { method: 'as', arg: 'groups' } ]

Rounded corner for textview in android

  1. Right Click on Drawable Folder and Create new File
  2. Name the file according to you and add the extension as .xml.
  3. Add the following code in the file
  <?xml version="1.0" encoding="utf-8"?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android"
      android:shape="rectangle">
      <corners android:radius="5dp" />
      <stroke android:width="1dp"  />
      <solid android:color="#1e90ff" />
  </shape>
  1. Add the line where you want the rounded edge android:background="@drawable/corner"

How can I get my webapp's base URL in ASP.NET MVC?

Maybe it is extension or modification of the answers posted here but I use simply the following line and it works:

Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~")

When my path is: http://host/iis_foldername/controller/action
then I receive : http://host/iis_foldername/

CSS white space at bottom of page despite having both min-height and height tag

I had white space at the bottom of all my websites; this is how I solved the matter:

the first and best thing you can do when you are debugging css issues like this is to add:

*{ border: 1px solid red; }

this css line puts a red box around all your css elements.

I had white space at the bottom of my page due to a faulty chrome extension which was adding the div 'dp_swf_engine' to the bottom of my page:

without the red box, I would have never noticed a 1px div. I then got rid of the faulty extension, and put 'display:none' on #dp_swf_engine as a secondary measure. (who knows when it could come back to add random white space at the bottom of my page for all my pages and apps?!)

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Why does JSHint throw a warning if I am using const?

In your package.json you can tell Jshint to use es6 like this

"jshintConfig":{
    "esversion": 6 
}

Use of document.getElementById in JavaScript

Consider

 var x = document.getElementById("age");

Here x is the element with id="age".

Now look at the following line

var age = document.getElementById("age").value;

this means you are getting the value of the element which has id="age"

In Angular, What is 'pathmatch: full' and what effect does it have?

While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full does if you don't know how the router works in the first place.


Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section.

  1. It may be obvious but let's first point out that query parameters (?from=134) and fragments (#section) do not play any role in path matching. Only the base url (/users/james/articles) matters.

  2. Angular splits URLs into segments. The segments of /users/james/articles are, of course, users, james and articles.

  3. The router configuration is a tree structure with a single root node. Each Route object is a node, which may have children nodes, which may in turn have other children or be leaf nodes.

The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.

E.g. if your target URL is /a/b/c but the router is only able to match either /a/b or /a/b/c/d, then there is no match and the application will not render anything.

Finally, routes with redirectTo behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full. But we will get to this later.

Default (prefix) path matching

The reasoning behind the name prefix is that such a route configuration will check if the configured path is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.

Anyway, let's say this is our root-level router configuration:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

Note that every single Route object here uses the default matching strategy, which is prefix. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:

  1. Iterate over the root array looking for a an exact match for the first URL segment - users.
  2. 'products' !== 'users', so skip that branch. Note that we are using an equality check rather than a .startsWith() or .includes() - only full segment matches count!
  3. :other matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james and articles), thus the router looks for children.
  • The only child of :other is tricks, which is !== 'james', hence not a match.
  1. Angular then retraces back to the root array and continues from there.
  2. 'user' !== 'users, skip branch.
  3. 'users' === 'users - the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).
  • 'permissions' !== 'james', skip it.
  • :userID matches anything, thus we have a match for the james segment. However this is still not a full match, thus we need to look for a child which would match articles.
    1. We can see that :userID has a child route articles, which gives us a full match! Thus the application renders UserArticlesComponent.

Full URL (full) matching

Example 1

Imagine now that the users route configuration object looked like this:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

Note the usage of pathMatch: full. If this were the case, steps 1-5 would be the same, however step 6 would be different:

  1. 'users' !== 'users/james/articles - the segment does not match because the path configuration users with pathMatch: full does not match the full URL, which is users/james/articles.
  2. Since there is no match, we are skipping this branch.
  3. At this point we reached the end of the router configuration without having found a match. The application renders nothing.

Example 2

What if we had this instead:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userID with pathMatch: full matches only users/james thus it's a no-match once again, and the application renders nothing.

Example 3

Let's consider this:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

In this case:

  1. 'users' === 'users - the segment matches, but james/articles still remains unmatched. Let's look for children.
  • 'permissions' !== 'james' - skip.
  • :userID' can only match a single segment, which would be james. However, it's a pathMatch: full route, and it must match james/articles (the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!
  1. Again, we failed to find any match for the URL and the application renders nothing.

As you may have noticed, a pathMatch: full configuration is basically saying this:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

Redirects

Any Route which has defined a redirectTo will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix strategy, a partial match is enough to cause a redirect. Here's a good example:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

For our initial URL (/users/james/articles), here's what would happen:

  1. 'not-found' !== 'users' - skip it.
  2. 'users' === 'users' - we have a match.
  3. This match has a redirectTo: 'not-found', which is applied immediately.
  4. The target URL changes to not-found.
  5. The router begins matching again and finds a match for not-found right away. The application renders NotFoundComponent.

Now consider what would happen if the users route also had pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - skip it.
  2. users would match the first segment of the URL, but the route configuration requires a full match, thus skip it.
  3. 'users/:userID' matches users/james. articles is still not matched but this route has children.
  • We find a match for articles in the children. The whole URL is now matched and the application renders UserArticlesComponent.

Empty path (path: '')

The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

Let's say we are trying to access /users:

  • path: '' will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users!
  • We can see that there is a child users, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent.

Now back to the original question

The OP used this router configuration:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

If we are navigating to the root URL (/), here's how the router would resolve that:

  1. welcome does not match an empty segment, so skip it.
  2. path: '' matches the empty segment. It has a pathMatch: 'full', which is also satisfied as we have matched the whole URL (it had a single empty segment).
  3. A redirect to welcome happens and the application renders WelcomeComponent.

What if there was no pathMatch: 'full'?

Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }) because if you put this Route above welcome, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)

Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).

What about path: '**'?

path: '**' will match absolutely anything (af/frewf/321532152/fsa is a match) with or without a pathMatch: 'full'.

Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' } completely redundant in this setup.

Funnily enough, it is perfectly fine to have this configuration:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

If we navigate to /welcome, path: '**' will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.

JavaScript function in href vs. onclick

it worked for me using this line of code:

<a id="LinkTest" title="Any Title"  href="#" onclick="Function(); return false; ">text</a>

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

IndexError: list index out of range and python

If you read a list from text file, you may get the last empty line as a list element. You can get rid of it like this:

list.pop()
for i in list:
   i[12]=....

How can I start and check my MySQL log?

Its given on OFFICIAL MYSQL website.

SET GLOBAL general_log = 'ON';

You can also use custom path:

[mysqld]
# Set Slow Query Log
long_query_time = 1
slow_query_log = 1
slow_query_log_file = "C:/slowquery.log"

#Set General Log
log = "C:/genquery.log"

Cannot set some HTTP headers when using System.Net.WebRequest

If you need the short and technical answer go right to the last section of the answer.

If you want to know better, read it all, and i hope you'll enjoy...


I countered this problem too today, and what i discovered today is that:

  1. the above answers are true, as:

    1.1 it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again.

    1.2 Anytime you're changing the headers of an HttpWebRequest, you need to use the appropriate properties on the object itself, if they exist.

Thanks FOR and Jvenema for the leading guidelines...

  1. But, What i found out, and that was the missing piece in the puzzle is that:

    2.1 The WebHeaderCollection class is generally accessed through WebRequest.Headers or WebResponse.Headers. Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.

The restricted headers are:

  • Accept
  • Connection
  • Content-Length
  • Content-Type
  • Date
  • Expect
  • Host
  • If-Modified-Since
  • Range
  • Referer
  • Transfer-Encoding
  • User-Agent
  • Proxy-Connection

So, next time you are facing this exception and don't know how to solve this, remember that there are some restricted headers, and the solution is to modify their values using the appropriate property explicitly from the WebRequest/HttpWebRequest class.


Edit: (useful, from comments, comment by user Kaido)

Solution is to check if the header exists already or is restricted (WebHeaderCollection.IsRestricted(key)) before calling add

What's the difference between Perl's backticks, system, and exec?

What's the difference between Perl's backticks (`), system, and exec?

exec -> exec "command"; ,
system -> system("command"); and 
backticks -> print `command`;

exec

exec executes a command and never resumes the Perl script. It's to a script like a return statement is to a function.

If the command is not found, exec returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in perlfunc, because it is a function.

E.g.:

#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";

In above code, there are three print statements, but due to exec leaving the script, only the first print statement is executed. Also, the exec command output is not being assigned to any variable.

Here, only you're only getting the output of the first print statement and of executing the ls command on standard out.

system

system executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.

E.g.:

#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements. As the script is resumed after the system command, all three print statements are executed.

Also, the result of running system is assigned to data2, but the assigned value is 0 (the exit code from ls).

Here, you're getting the output of the first print statement, then that of the ls command, followed by the outputs of the final two print statements on standard out.

backticks (`)

Like system, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system, the return value is STDOUT of the command. qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec, it is an operator.

E.g.:

#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements and all three are being executed. The output of ls is not going to standard out directly, but assigned to the variable data2 and then printed by the final print statement.

How to get file_get_contents() to work with HTTPS?

This is probably due to your target server not having a valid SSL certificate.

Why do I need an IoC container as opposed to straightforward DI code?

So, it's been almost 3 years, eh?

  1. 50% of those who commented in favor of IoC frameworks don't understand the difference between IoC and IoC Frameworks. I doubt they know that you can write code without being deployed to an app server

  2. If we take most popular Java Spring framework, it is IoC configuration moved from XMl into the code and now look like this

`@Configuration public class AppConfig {

public @Bean TransferService transferService() {
    return new TransferServiceImpl(accountRepository());
}

public @Bean AccountRepository accountRepository() {
    return new InMemoryAccountRepository();
}

} ` And we need a framework to do this why exactly?

Recommendation for compressing JPG files with ImageMagick

Here's a complete solution for those using Imagick in PHP:

$im = new \Imagick($filePath);
$im->setImageCompression(\Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(85);
$im->stripImage();
$im->setInterlaceScheme(\Imagick::INTERLACE_PLANE);

// Try between 0 or 5 radius. If you find radius of 5 
// produces too blurry  pictures decrease to 0 until you 
// find a good balance between size and quality. 
$im->gaussianBlurImage(0.05, 5);



// Include this part if you also want to specify a maximum size for the images

$size = $im->getImageGeometry();
$maxWidth = 1920;
$maxHeight = 1080;


// ----------
// |        |
// ----------
if($size['width'] >= $size['height']){
  if($size['width'] > $maxWidth){
    $im->resizeImage($maxWidth, 0, \Imagick::FILTER_LANCZOS, 1);
  }
}


// ------
// |    |
// |    |
// |    |
// |    |
// ------
else{
  if($size['height'] > $maxHeight){
    $im->resizeImage(0, $maxHeight, \Imagick::FILTER_LANCZOS, 1);
  }
}

How to install Python MySQLdb module using pip?

First

pip install pymysql

Then put the code below into __init__.py (projectname/__init__.py)

import pymysql
pymysql.install_as_MySQLdb()

My environment is (python3.5, django1.10) and this solution works for me!

Hope this helps!!

how to set default method argument values?

If your arguments are the same type you could use varargs:

public int something(int... args) {
    int a = 0;
    int b = 0;
    if (args.length > 0) {
      a = args[0];
    }
    if (args.length > 1) {
      b = args[1];
    }
    return a + b
}

but this way you lose the semantics of the individual arguments, or

have a method overloaded which relays the call to the parametered version

public int something() {
  return something(1, 2);
}

or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:

class FoodBuilder {
   int saltAmount;
   int meatAmount;
   FoodBuilder setSaltAmount(int saltAmount) {
       this.saltAmount = saltAmount;
       return this;
   }
   FoodBuilder setMeatAmount(int meatAmount) {
       this.meatAmount = meatAmount;
       return this;
   }
   Food build() {
       return new Food(saltAmount, meatAmount);
   }
}

Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();

Then work with the Food object

int doSomething(Food f) {
    return f.getSaltAmount() + f.getMeatAmount();
}

The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.

Regex for empty string or white space

If you're using jQuery, you have .trim().

if ($("#siren").val().trim() == "") {
  // it's empty
}

Matplotlib make tick labels font size smaller

You can also change label display parameters like fontsize with a line like this:

zed = [tick.label.set_fontsize(14) for tick in ax.yaxis.get_major_ticks()]

Is there a replacement for unistd.h for Windows (Visual C)?

Yes, there is: https://github.com/robinrowe/libunistd

Clone the repository and add path\to\libunistd\unistd to the INCLUDE environment variable.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

Bootstrap: how do I change the width of the container?

Add these piece of CSS in your css styling. Its better to add this after the bootstrap css file is added in order to overwrite the same.

html, body {
 height: 100%;
 max-width: 100%;
 overflow-x: hidden;
}`

Simple working Example of json.net in VB.net

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".

So either create a class for that, e.g.:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

or change your JSON string to

{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

or use e.g. a ContractResolver to parse the JSON string.

How do I adb pull ALL files of a folder present in SD Card

Directory pull is available on new android tools. ( I don't know from which version it was added, but its working on latest ADT 21.1 )

adb pull /sdcard/Robotium-Screenshots
pull: building file list...
pull: /sdcard/Robotium-Screenshots/090313-110415.jpg -> ./090313-110415.jpg
pull: /sdcard/Robotium-Screenshots/090313-110412.jpg -> ./090313-110412.jpg
pull: /sdcard/Robotium-Screenshots/090313-110408.jpg -> ./090313-110408.jpg
pull: /sdcard/Robotium-Screenshots/090313-110406.jpg -> ./090313-110406.jpg
pull: /sdcard/Robotium-Screenshots/090313-110404.jpg -> ./090313-110404.jpg
5 files pulled. 0 files skipped.
61 KB/s (338736 bytes in 5.409s)

What is the exact location of MySQL database tables in XAMPP folder?

Data are store in this path. You can search data location, just put the below address in your search location (url address):

C:\xampp\mysql\data

SOAP vs REST (differences)

REST(REpresentational State Transfer)
REpresentational State of an Object is Transferred is REST i.e. we don't send Object, we send state of Object. REST is an architectural style. It doesn’t define so many standards like SOAP. REST is for exposing Public APIs(i.e. Facebook API, Google Maps API) over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP(Simple Object Access Protocol)
SOAP brings its own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each operation implement some business logic. Though SOAP is commonly referred to as web services this is misnomer. SOAP has a very little if anything to do with the Web. REST provides true Web services based on URIs and HTTP.

Why REST?

  • Since REST uses standard HTTP it is much simpler in just about ever way.
  • REST is easier to implement, requires less bandwidth and resources.
  • REST permits many different data formats where as SOAP only permits XML.
  • REST allows better support for browser clients due to its support for JSON.
  • REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached.
  • If security is not a major concern and we have limited resources. Or we want to create an API that will be easily used by other developers publicly then we should go with REST.
  • If we need Stateless CRUD operations then go with REST.
  • REST is commonly used in social media, web chat, mobile services and Public APIs like Google Maps.
  • RESTful service return various MediaTypes for the same resource, depending on the request header parameter "Accept" as application/xml or application/json for POST and /user/1234.json or GET /user/1234.xml for GET.
  • REST services are meant to be called by the client-side application and not the end user directly.
  • ST in REST comes from State Transfer. You transfer the state around instead of having the server store it, this makes REST services scalable.

Why SOAP?

  • SOAP is not very easy to implement and requires more bandwidth and resources.
  • SOAP message request is processed slower as compared to REST and it does not use web caching mechanism.
  • WS-Security: While SOAP supports SSL (just like REST) it also supports WS-Security which adds some enterprise security features.
  • WS-AtomicTransaction: Need ACID Transactions over a service, you’re going to need SOAP.
  • WS-ReliableMessaging: If your application needs Asynchronous processing and a guaranteed level of reliability and security. Rest doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying.
  • If the security is a major concern and the resources are not limited then we should use SOAP web services. Like if we are creating a web service for payment gateways, financial and telecommunication related work then we should go with SOAP as here high security is needed.

enter image description here

source1
source2

Insert a new row into DataTable

// get the data table
DataTable dt = ...;

// generate the data you want to insert
DataRow toInsert = dt.NewRow();

// insert in the desired place
dt.Rows.InsertAt(toInsert, index);

How to install mcrypt extension in xampp

First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows

Then, you should copy php_mcrypt.dll to ../xampp/php/ext/ and enable the extension by adding extension=mcrypt to your xampp/php/php.ini file.

Windows 8.1 gets Error 720 on connect VPN

Based on the Microsoft support KBs, this can occur if TCP/IP is damaged or is not bound to your dial-up adapter.You can try reinstalling or resetting TCP/IP as follows:

  • Reset TCP/IP to Original Configuration- Using the NetShell utility, type this command (in CommandLine): netsh int ip reset [file_name.txt], [file_name.txt] is the name of the file where the actions taken by NetShell are record, for example netsh hint ip reset fixtcpip.txt.

  • Remove and re-install NIC – Open Controller and select System. Click Hardware tab and select devices. Double-click on Network Adapter and right-click on the NIC, select Uninstall. Restart the computer and the Windows should auto detect the NIC and re-install it.

  • Upgrade the NIC driver – You may download the latest NIC driver and upgrade the driver.

Hope it could help.

Summarizing multiple columns with dplyr?

We can summarize by using summarize_at, summarize_all and summarize_if on dplyr 0.7.4. We can set the multiple columns and functions by using vars and funs argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4, summarise_each(and mutate_each) is already deprecated, so we cannot use these functions.

options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)

library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’

set.seed(123)
df <- data_frame(
  a = sample(1:5, 10, replace=T), 
  b = sample(1:5, 10, replace=T), 
  c = sample(1:5, 10, replace=T), 
  d = sample(1:5, 10, replace=T), 
  grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)

df %>% group_by(grp) %>% 
  summarise_each(.vars = letters[1:4],
                 .funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean

You should change to the following code. The following codes all have the same result.

# summarise_at
df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = names(.)[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = vars(a,b,c,d),
               .funs = c(mean="mean"))

# summarise_all
df %>% group_by(grp) %>% 
  summarise_all(.funs = c(mean="mean"))

# summarise_if
df %>% group_by(grp) %>% 
  summarise_if(.predicate = function(x) is.numeric(x),
               .funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr>  <dbl>  <dbl>  <dbl>  <dbl>
# 1     1   2.80   3.00    3.6   3.00
# 2     2   4.25   2.75    4.0   3.75
# 3     3   3.00   5.00    1.0   2.00

You can also have multiple functions.

df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:2],
               .funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean      a_Sd     b_Sd
# <chr>  <dbl>  <dbl>     <dbl>    <dbl>
# 1     1   2.80   3.00 1.4832397 1.870829
# 2     2   4.25   2.75 0.9574271 1.258306
# 3     3   3.00   5.00        NA       NA

Get Specific Columns Using “With()” Function in Laravel Eloquent

For loading models with specific column, though not eager loading, you could:

In your Post model

public function user()
{
    return $this->belongsTo('User')->select(array('id', 'username'));
}

Original credit goes to Laravel Eager Loading - Load only specific columns

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

https://support.google.com/a/answer/3001912?hl=en

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

ImportError: No module named sqlalchemy

On Windows 10 @ 2019

I faced the same problem. Turns out I forgot to install the following package:

pip install flask_sqlalchemy

After installing the package, everything worked perfectly. Hope, it helped some other noob like me.

How to Deserialize XML document

The following snippet should do the trick (and you can ignore most of the serialization attributes):

public class Car
{
  public string StockNumber { get; set; }
  public string Make { get; set; }
  public string Model { get; set; }
}

[XmlRootAttribute("Cars")]
public class CarCollection
{
  [XmlElement("Car")]
  public Car[] Cars { get; set; }
}

...

using (TextReader reader = new StreamReader(path))
{
  XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
  return (CarCollection) serializer.Deserialize(reader);
}

WordPress is giving me 404 page not found for all pages except the homepage

after 2 long days, the solution was to add options +FollowSymLinks to the top of my .htaccess file.

Attach the Source in Eclipse of a jar

Eclipse is showing no source found because there is no source available . Your jar only has the compiled classes.

You need to import the project from jar and add the Project as dependency .

Other option is to go to the

Go to Properties (for the Project) -> Java Build Path -> Libraries , select your jar file and click on the source , there will be option to attach the source and Javadocs.

EXCEL Multiple Ranges - need different answers for each range

use

=VLOOKUP(D4,F4:G9,2)

with the range F4:G9:

0   0.1
1   0.15
5   0.2
15  0.3
30  1
100 1.3

and D4 being the value in question, e.g. 18.75 -> result: 0.3

how to call a variable in code behind to aspx page

You need to declare your clients variable as public, e.g.

public string clients;

but you should probably do it as a Property, e.g.

private string clients;
public string Clients{ get{ return clients; } set {clients = value;} }

And then you can call it in your .aspx page like this:

<%=Clients%>

Variables in C# are private by default. Read more on access modifiers in C# on MSDN and properties in C# on MSDN

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

Android's default system path of your application database is /data/data/YOUR_PACKAGE/databases/YOUR_DB_NAME

Your logcat clearly says Failed to open database '/data/data/com.example.quotes/databasesQuotesdb'

Which means there is no file present on the given path or You have given the wrong path for the data file. As I can see there should be "/" after databases folder.

Your DB_PATH variable should end with a "/".

private static String DB_PATH = "/data/data/com.example.quotes/databases/";

Your correct path will be now "/data/data/com.example.quotes/databases/Quotesdb"

In Javascript/jQuery what does (e) mean?

e is the short var reference for event object which will be passed to event handlers.

The event object essentially has lot of interesting methods and properties that can be used in the event handlers.

In the example you have posted is a click handler which is a MouseEvent

$(<element selector>).click(function(e) {
    // does something
    alert(e.type); //will return you click
}

DEMO - Mouse Events DEMO uses e.which and e.type

Some useful references:

http://api.jquery.com/category/events/

http://www.quirksmode.org/js/events_properties.html

http://www.javascriptkit.com/jsref/event.shtml

http://www.quirksmode.org/dom/events/index.html

http://www.w3.org/TR/DOM-Level-3-Events/#event-types-list

Replace a character at a specific index in a string?

You can overwrite a string, as follows:

String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);  

Note that the string myName occurs on both lines, and on both sides of the second line.

Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.

How to prevent the "Confirm Form Resubmission" dialog?

It seems you are looking for the Post/Redirect/Get pattern.

As another solution you may stop to use redirecting at all.

You may process and render the processing result at once with no POST confirmation alert. You should just manipulate the browser history object:

history.replaceState("", "", "/the/result/page")

See full or short answers

apc vs eaccelerator vs xcache

Check out benchmarks and comparisons:

here and here and there

Bootstrap radio button "checked" flag

Assuming you want a default button checked.

<div class="row">
    <h1>Radio Group #2</h1>
    <label for="year" class="control-label input-group">Year</label>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="year" value="2011">2011
        </label>
        <label class="btn btn-default">
            <input type="radio" name="year" value="2012">2012
        </label>
        <label class="btn btn-default active">
            <input type="radio" name="year" value="2013" checked="">2013
        </label>
    </div>
  </div>

Add the active class to the button (label tag) you want defaulted and checked="" to its input tag so it gets submitted in the form by default.

converting CSV/XLS to JSON?

You can try this tool I made:

Mr. Data Converter

It converts to JSON, XML and others.

It's all client side, too, so your data never leaves your computer.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

bootstrap datepicker setDate format dd/mm/yyyy

for me it is daterangepicker worked by this :

     $('#host1field').daterangepicker({
                   locale: {
                            format: 'DD/MM/YYYY'
                            }
                 });

How to center an unordered list?

http://jsfiddle.net/psbu2/3/

If it is possible for you to use your own list bullets

Try this:

<html>
    <head>
        <style type="text/css">

            ul {
                margin:0;
                padding:0;
                text-align: center;
                list-style:none;                
            }
            ul  li {
                padding: 2px 5px;               
            }

            ul li:before {
                content:url(http://www.un.org/en/oaj/unjs/efiling/added/images/bullet-list-icon-blue.jpg);;
            }
        </style>
    </head>
    <body>

            <ul>
                <li>1</li>
                <li>2</li>
                <li>3</li>
            </ul>

    </body>
</html>

Get date from input form within PHP

    <?php
if (isset($_POST['birthdate'])) {
    $timestamp = strtotime($_POST['birthdate']); 
    $date=date('d',$timestamp);
    $month=date('m',$timestamp);
    $year=date('Y',$timestamp);
}
?>  

How can I delete a service in Windows?

For me my service that I created had to be uninstalled in Control Panel > Programs and Features

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Difference between Visual Basic 6.0 and VBA

VBA stands for Visual Basic For Applications and its a Visual Basic implementation intended to be used in the Office Suite.

The difference between them is that VBA is embedded inside Office documents (its an Office feature). VB is the ide/language for developing applications.

RegEx to extract all matches from string using RegExp.exec

Here's a one line solution without a while loop.

The order is preserved in the resulting list.

The potential downsides are

  1. It clones the regex for every match.
  2. The result is in a different form than expected solutions. You'll need to process them one more time.
let re = /\s*([^[:]+):\"([^"]+)"/g
let str = '[description:"aoeu" uuid:"123sth"]'

(str.match(re) || []).map(e => RegExp(re.source, re.flags).exec(e))

[ [ 'description:"aoeu"',
    'description',
    'aoeu',
    index: 0,
    input: 'description:"aoeu"',
    groups: undefined ],
  [ ' uuid:"123sth"',
    'uuid',
    '123sth',
    index: 0,
    input: ' uuid:"123sth"',
    groups: undefined ] ]

What does flex: 1 mean?

Here is the explanation:

https://www.w3.org/TR/css-flexbox-1/#flex-common

flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

Therefore flex:1 is equivalent to flex: 1 1 0