Programs & Examples On #Stubbing

Stubbing is modifying an instance method or property of an object at runtime to extend its functionality.

Mockito - NullpointerException when stubbing Method

Corner case:
If you're using Scala and you try to create an any matcher on a value class, you'll get an unhelpful NPE.

So given case class ValueClass(value: Int) extends AnyVal, what you want to do is ValueClass(anyInt) instead of any[ValueClass]

when(mock.someMethod(ValueClass(anyInt))).thenAnswer {
   ...
   val v  = ValueClass(invocation.getArguments()(0).asInstanceOf[Int])
   ...
}

This other SO question is more specifically about that, but you'd miss it when you don't know the issue is with value classes.

SQL Server 2000: How to exit a stored procedure?

This works over here.

ALTER PROCEDURE dbo.Archive_Session
    @SessionGUID int
AS 
    BEGIN
        SET NOCOUNT ON
        PRINT 'before raiserror'
        RAISERROR('this is a raised error', 18, 1)
        IF @@Error != 0 
            RETURN
        PRINT 'before return'
        RETURN -1
        PRINT 'after return'
    END
go

EXECUTE dbo.Archive_Session @SessionGUID = 1

Returns

before raiserror
Msg 50000, Level 18, State 1, Procedure Archive_Session, Line 7
this is a raised error

Create an enum with string values

In latest version (1.0RC) of TypeScript, you can use enums like this:

enum States {
    New,
    Active,
    Disabled
} 

// this will show message '0' which is number representation of enum member
alert(States.Active); 

// this will show message 'Disabled' as string representation of enum member
alert(States[States.Disabled]);

Update 1

To get number value of enum member from string value, you can use this:

var str = "Active";
// this will show message '1'
alert(States[str]);

Update 2

In latest TypeScript 2.4, there was introduced string enums, like this:

enum ActionType {
    AddUser = "ADD_USER",
    DeleteUser = "DELETE_USER",
    RenameUser = "RENAME_USER",

    // Aliases
    RemoveUser = DeleteUser,
}

For more info about TypeScript 2.4, read blog on MSDN.

How to see if an object is an array without using reflection?

One can access each element of an array separately using the following code:

Object o=...;
if ( o.getClass().isArray() ) {
    for(int i=0; i<Array.getLength(o); i++){
        System.out.println(Array.get(o, i));
    }
}

Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.

Creating a ZIP archive in memory using System.IO.Compression

       private void button6_Click(object sender, EventArgs e)
    {

        //create With Input FileNames
        AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
            new ZipItem(@"E:\b\2.txt",@"text\2.txt")}, @"C:\test.zip");

        //create with input stream
        AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem(File.ReadAllBytes( @"E:\b\1.jpg"),@"images\1.jpg"),
            new ZipItem(File.ReadAllBytes(@"E:\b\2.txt"),@"text\2.txt")}, @"C:\test.zip");

        //Create Archive And Return StreamZipFile
        MemoryStream GetStreamZipFile = AddFileToArchive(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
            new ZipItem(@"E:\b\2.txt",@"text\2.txt")});


        //Extract in memory
        ZipItem[] ListitemsWithBytes = ExtractItems(@"C:\test.zip");

        //Choese Files For Extract To memory
        List<string> ListFileNameForExtract = new List<string>(new string[] { @"images\1.jpg", @"text\2.txt" });
        ListitemsWithBytes = ExtractItems(@"C:\test.zip", ListFileNameForExtract);


        // Choese Files For Extract To Directory
        ExtractItems(@"C:\test.zip", ListFileNameForExtract, "c:\\extractFiles");

    }

    public struct ZipItem
    {
        string _FileNameSource;
        string _PathinArchive;
        byte[] _Bytes;
        public ZipItem(string __FileNameSource, string __PathinArchive)
        {
            _Bytes=null ;
            _FileNameSource = __FileNameSource;
            _PathinArchive = __PathinArchive;
        }
        public ZipItem(byte[] __Bytes, string __PathinArchive)
        {
            _Bytes = __Bytes;
            _FileNameSource = "";
            _PathinArchive = __PathinArchive;

        }
        public string FileNameSource
        {
            set
            {
                FileNameSource = value;
            }
            get
            {
                return _FileNameSource;
            }
        }
        public string PathinArchive
        {
            set
            {
                _PathinArchive = value;
            }
            get
            {
                return _PathinArchive;
            }
        }
        public byte[] Bytes
        {
            set
            {
                _Bytes = value;
            }
            get
            {
                return _Bytes;
            }
        }
    }


     public void AddFileToArchive(ZipItem[] ZipItems, string SeveToFile)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
            FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 0;
            while (fsReader.Position != fsReader.Length)
            {
                //Read Bytes
                ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);

                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
            }
            fsReader.Dispose();
            OpenFileInArchive.Close();


        }
        archive.Dispose();

        using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }





    }
     public MemoryStream  AddFileToArchive(ZipItem[] ZipItems)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
            FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 0;
            while (fsReader.Position != fsReader.Length)
            {
                //Read Bytes
                ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);

                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
            }
            fsReader.Dispose();
            OpenFileInArchive.Close();


        }
        archive.Dispose();




        return memoryStream;


    }

     public void AddFileToArchive_InputByte(ZipItem[] ZipItems, string SeveToFile)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
          //  FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 4096 ;int  TotalWrite=0;
            while (TotalWrite != item.Bytes.Length)
            {

                if(TotalWrite+4096>item.Bytes.Length)
                 ReadByte=item.Bytes.Length-TotalWrite;



                Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);




                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
                TotalWrite += ReadByte;
            }

            OpenFileInArchive.Close();


        }
        archive.Dispose();

        using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }


    }
     public MemoryStream  AddFileToArchive_InputByte(ZipItem[] ZipItems)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
          //  FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 4096 ;int  TotalWrite=0;
            while (TotalWrite != item.Bytes.Length)
            {

                if(TotalWrite+4096>item.Bytes.Length)
                 ReadByte=item.Bytes.Length-TotalWrite;



                Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);




                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
                TotalWrite += ReadByte;
            }

            OpenFileInArchive.Close();


        }
        archive.Dispose();



        return memoryStream;
    }

     public void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
     {
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {
             if (Directory.Exists(destinationDirectoryName)==false )
                 Directory.CreateDirectory(destinationDirectoryName);

             //Loops through each file in the zip file
             archive.ExtractToDirectory(destinationDirectoryName);

         }
     }  
     public void   ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive, string destinationDirectoryName)
     {

         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {


             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 int PosResult = _PathFilesinArchive.IndexOf(file.FullName);
                 if (PosResult != -1)
                 {
                     //Create Folder
                     if (Directory.Exists( destinationDirectoryName + "\\" +Path.GetDirectoryName( _PathFilesinArchive[PosResult])) == false)
                         Directory.CreateDirectory(destinationDirectoryName + "\\" + Path.GetDirectoryName(_PathFilesinArchive[PosResult]));

                     Stream OpenFileGetBytes = file.Open();

                     FileStream   FileStreamOutput = new FileStream(destinationDirectoryName + "\\" + _PathFilesinArchive[PosResult], FileMode.Create);

                     byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                     int ReadByte = 0; int TotalRead = 0; 
                     while (TotalRead != file.Length)
                     {
                         //Read Bytes
                         ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                         TotalRead += ReadByte;

                         //Write Bytes
                         FileStreamOutput.Write(ReadAllbytes, 0, ReadByte);
                     }

                     FileStreamOutput.Close();
                     OpenFileGetBytes.Close();



                     _PathFilesinArchive.RemoveAt(PosResult);
                 }

                 if (_PathFilesinArchive.Count == 0)
                     break;
             }
         }


     }

     public ZipItem[] ExtractItems(string sourceArchiveFileName)
     {
       List<  ZipItem> ZipItemsReading = new List<ZipItem>();
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {


             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 Stream OpenFileGetBytes = file.Open();

                 MemoryStream memstreams = new MemoryStream();
                 byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                 int ReadByte = 0; int TotalRead = 0;
                 while (TotalRead != file.Length)
                 {
                     //Read Bytes
                     ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                     TotalRead += ReadByte;

                     //Write Bytes
                     memstreams.Write(ReadAllbytes, 0, ReadByte);
                 }

                 memstreams.Position = 0;
                 OpenFileGetBytes.Close();
                 memstreams.Dispose();

                 ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));


             }
         }

         return ZipItemsReading.ToArray();
     }
     public ZipItem[] ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive)
     {
       List<  ZipItem> ZipItemsReading = new List<ZipItem>();
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {

             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 int PosResult = _PathFilesinArchive.IndexOf(file.FullName); 
                 if (PosResult!= -1)
                 {
                     Stream OpenFileGetBytes = file.Open();

                     MemoryStream memstreams = new MemoryStream();
                     byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                     int ReadByte = 0; int TotalRead = 0;  
                     while (TotalRead != file.Length)
                     {
                         //Read Bytes
                         ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                         TotalRead += ReadByte;

                         //Write Bytes
                         memstreams.Write(ReadAllbytes, 0, ReadByte);
                     }

                     //Create item
                     ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));

                     OpenFileGetBytes.Close();
                     memstreams.Dispose();



                     _PathFilesinArchive.RemoveAt(PosResult);
                 }

                 if (_PathFilesinArchive.Count == 0)
                     break;


             }
         }

         return ZipItemsReading.ToArray();
     }

How to add row of data to Jtable from values received from jtextfield and comboboxes

String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);

Here;this is the solution.

Dynamically load JS inside JS

Necromancing.

I use this to load dependant scripts;
it works with IE8+ without adding any dependency on another library like jQuery !

var cScriptLoader = (function ()
{
    function cScriptLoader(files)
    {
        var _this = this;
        this.log = function (t)
        {
            console.log("ScriptLoader: " + t);
        };
        this.withNoCache = function (filename)
        {
            if (filename.indexOf("?") === -1)
                filename += "?no_cache=" + new Date().getTime();
            else
                filename += "&no_cache=" + new Date().getTime();
            return filename;
        };
        this.loadStyle = function (filename)
        {
            // HTMLLinkElement
            var link = document.createElement("link");
            link.rel = "stylesheet";
            link.type = "text/css";
            link.href = _this.withNoCache(filename);
            _this.log('Loading style ' + filename);
            link.onload = function ()
            {
                _this.log('Loaded style "' + filename + '".');
            };
            link.onerror = function ()
            {
                _this.log('Error loading style "' + filename + '".');
            };
            _this.m_head.appendChild(link);
        };
        this.loadScript = function (i)
        {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = _this.withNoCache(_this.m_js_files[i]);
            var loadNextScript = function ()
            {
                if (i + 1 < _this.m_js_files.length)
                {
                    _this.loadScript(i + 1);
                }
            };
            script.onload = function ()
            {
                _this.log('Loaded script "' + _this.m_js_files[i] + '".');
                loadNextScript();
            };
            script.onerror = function ()
            {
                _this.log('Error loading script "' + _this.m_js_files[i] + '".');
                loadNextScript();
            };
            _this.log('Loading script "' + _this.m_js_files[i] + '".');
            _this.m_head.appendChild(script);
        };
        this.loadFiles = function ()
        {
            // this.log(this.m_css_files);
            // this.log(this.m_js_files);
            for (var i = 0; i < _this.m_css_files.length; ++i)
                _this.loadStyle(_this.m_css_files[i]);
            _this.loadScript(0);
        };
        this.m_js_files = [];
        this.m_css_files = [];
        this.m_head = document.getElementsByTagName("head")[0];
        // this.m_head = document.head; // IE9+ only
        function endsWith(str, suffix)
        {
            if (str === null || suffix === null)
                return false;
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
        for (var i = 0; i < files.length; ++i)
        {
            if (endsWith(files[i], ".css"))
            {
                this.m_css_files.push(files[i]);
            }
            else if (endsWith(files[i], ".js"))
            {
                this.m_js_files.push(files[i]);
            }
            else
                this.log('Error unknown filetype "' + files[i] + '".');
        }
    }
    return cScriptLoader;
})();
var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();

If you are interested in the typescript-version used to create this:

class cScriptLoader {
    private m_js_files: string[];
    private m_css_files: string[];
    private m_head:HTMLHeadElement;
    
    private log = (t:any) =>
    {
        console.log("ScriptLoader: " + t);
    }
    
    
    constructor(files: string[]) {
        this.m_js_files = [];
        this.m_css_files = [];
        this.m_head = document.getElementsByTagName("head")[0];
        // this.m_head = document.head; // IE9+ only
        
        
        function endsWith(str:string, suffix:string):boolean 
        {
            if(str === null || suffix === null)
                return false;
                
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
        
        
        for(let i:number = 0; i < files.length; ++i) 
        {
            if(endsWith(files[i], ".css"))
            {
                this.m_css_files.push(files[i]);
            }
            else if(endsWith(files[i], ".js"))
            {
                this.m_js_files.push(files[i]);
            }
            else
                this.log('Error unknown filetype "' + files[i] +'".');
        }
        
    }
    
    
    public withNoCache = (filename:string):string =>
    {
        if(filename.indexOf("?") === -1)
            filename += "?no_cache=" + new Date().getTime();
        else
            filename += "&no_cache=" + new Date().getTime();
            
        return filename;    
    }
    

    public loadStyle = (filename:string) =>
    {
        // HTMLLinkElement
        let link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = this.withNoCache(filename);
        
        this.log('Loading style ' + filename);
        link.onload = () =>
        {
            this.log('Loaded style "' + filename + '".');
            
        };
        
        link.onerror = () =>
        {
            this.log('Error loading style "' + filename + '".');
        };
        
        this.m_head.appendChild(link);
    }
    
    
    public loadScript = (i:number) => 
    {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = this.withNoCache(this.m_js_files[i]);
        
        var loadNextScript = () => 
        {
            if (i + 1 < this.m_js_files.length)
            {
                this.loadScript(i + 1);
            }
        }
        
        script.onload = () =>
        {
            this.log('Loaded script "' + this.m_js_files[i] + '".');
            loadNextScript();
        };
        
        
        script.onerror = () =>
        {
            this.log('Error loading script "' + this.m_js_files[i] + '".');
            loadNextScript();
        };
        
        
        this.log('Loading script "' + this.m_js_files[i] + '".');
        this.m_head.appendChild(script);
    }
    
    public loadFiles = () => 
    {
        // this.log(this.m_css_files);
        // this.log(this.m_js_files);
        
        for(let i:number = 0; i < this.m_css_files.length; ++i)
            this.loadStyle(this.m_css_files[i])
        
        this.loadScript(0);
    }
    
}


var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();

If it's to load a dynamic list of scripts, write the scripts into an attribute, such as data-main, e.g. <script src="scriptloader.js" data-main="file1.js,file2.js,file3.js,etc." ></script>
and do a element.getAttribute("data-main").split(',')

such as

var target = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  // Note: this is for IE as IE doesn't support currentScript
  // this does not work if you have deferred loading with async
  // e.g. <script src="..." async="async" ></script>
  // https://web.archive.org/web/20180618155601/https://www.w3schools.com/TAgs/att_script_async.asp
  return scripts[scripts.length - 1];
})();

target.getAttribute("data-main").split(',')

to obtain the list.

Selenium Finding elements by class name in python

As per the HTML:

<html>
    <body>
    <p class="content">Link1.</p>
    </body>
<html>
<html>
    <body>
    <p class="content">Link2.</p>
    </body>
<html>

Two(2) <p> elements are having the same class content.

So to filter the elements having the same class i.e. content and create a list you can use either of the following Locator Strategies:

  • Using class_name:

    elements = driver.find_elements_by_class_name("content")
    
  • Using css_selector:

     elements = driver.find_elements_by_css_selector(".content")
    
  • Using xpath:

    elements = driver.find_elements_by_xpath("//*[@class='content']")
    

Ideally, to click on the element you need to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

  • Using CLASS_NAME:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "content")))
    
  • Using CSS_SELECTOR:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".content")))
    
  • Using XPATH:

    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='content']")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

References

You can find a couple of relevant discussions in:

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

Modify tick label text

I noticed that all the solutions posted here that use set_xticklabels() are not preserving the offset, which is a scaling factor applied to the ticks values to create better-looking tick labels. For instance, if the ticks are on the order of 0.00001 (1e-5), matplotlib will automatically add a scaling factor (or offset) of 1e-5, so the resultant tick labels may end up as 1 2 3 4, rather than 1e-5 2e-5 3e-5 4e-5.

Below gives an example:

The x array is np.array([1, 2, 3, 4])/1e6, and y is y=x**2. So both are very small values.

Left column: manually change the 1st and 3rd labels, as suggested by @Joe Kington. Note that the offset is lost.

Mid column: similar as @iipr suggested, using a FuncFormatter.

Right column: My suggested offset-preserving solution.

Figure here: enter image description here

Complete code here:

import matplotlib.pyplot as plt
import numpy as np

# create some *small* data to plot
x = np.arange(5)/1e6
y = x**2

fig, axes = plt.subplots(1, 3, figsize=(10,6))

#------------------The set_xticklabels() solution------------------
ax1 = axes[0]
ax1.plot(x, y)
fig.canvas.draw()
labels = [item.get_text() for item in ax1.get_xticklabels()]

# Modify specific labels
labels[1] = 'Testing'
labels[3] = 'Testing2'
ax1.set_xticklabels(labels)
ax1.set_title('set_xticklabels()')

#--------------FuncFormatter solution--------------
import matplotlib.ticker as mticker

def update_ticks(x, pos):
    if pos==1:
        return 'testing'
    elif pos==3:
        return 'testing2'
    else:
        return x

ax2=axes[1]
ax2.plot(x,y)
ax2.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
ax2.set_title('Func Formatter')

#-------------------My solution-------------------
def changeLabels(axis, pos, newlabels):
    '''Change specific x/y tick labels

    Args:
        axis (Axis): .xaxis or .yaxis obj.
        pos (list): indices for labels to change.
        newlabels (list): new labels corresponding to indices in <pos>.
    '''

    if len(pos) != len(newlabels):
        raise Exception("Length of <pos> doesn't equal that of <newlabels>.")

    ticks = axis.get_majorticklocs()
    # get the default tick formatter
    formatter = axis.get_major_formatter()
    # format the ticks into strings
    labels = formatter.format_ticks(ticks)

    # Modify specific labels
    for pii, lii in zip(pos, newlabels):
        labels[pii] = lii

    # Update the ticks and ticklabels. Order is important here.
    # Need to first get the offset (1e-6 in this case):
    offset = formatter.get_offset()
    # Then set the modified labels:
    axis.set_ticklabels(labels)
    # In doing so, matplotlib creates a new FixedFormatter and sets it to the xaxis
    # and the new FixedFormatter has no offset. So we need to query the
    # formatter again and re-assign the offset:
    axis.get_major_formatter().set_offset_string(offset)

    return

ax3 = axes[2]
ax3.plot(x, y)

changeLabels(ax3.xaxis, [1, 3], ['Testing', 'Testing2'])
ax3.set_title('With offset')

fig.show()
plt.savefig('tick_labels.png')

Caveat: it appears that solutions that use set_xticklabels(), including my own, relies on FixedFormatter, which is static and doesn't respond to figure resizing. To observe the effect, change the figure to a smaller size, e.g. fig, axes = plt.subplots(1, 3, figsize=(6,6)) and enlarge the figure window. You will notice that that only the mid column responds to resizing and adds more ticks as the figure gets larger. The left and right column will have empty tick labels (see figure below).

Caveat 2: I also noticed that if your tick values are floats, calling set_xticklabels(ticks) directly might give you ugly-looking strings, like 1.499999999998 instead of 1.5.

enter image description here

Outline effect to text

I had this issue as well, and the text-shadow wasn't an option because the corners would look bad (unless I had many many shadows), and I didn't want any blur, therefore my only other option was to do the following: Have 2 divs, and for the background div, put a -webkit-text-stroke on it, which then allows for as big of an outline as you like.

_x000D_
_x000D_
div {_x000D_
  font-size: 200px;_x000D_
  position: absolute;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
_x000D_
.front {_x000D_
 color: blue;_x000D_
}_x000D_
_x000D_
.outline {_x000D_
  -webkit-text-stroke: 30px red;_x000D_
  user-select: none;_x000D_
}
_x000D_
<div class="outline">_x000D_
 outline text_x000D_
</div>_x000D_
_x000D_
<div class="front">_x000D_
 outline text_x000D_
</div>  
_x000D_
_x000D_
_x000D_

Using this, I was able to achieve an outline, because the stroke-width method was not an option if you want your text to remain legible with a very large outline (because with stroke-width the outline will start inside the lettering which makes it not legible when the width gets larger than the letters.

Note: the reason I needed such a fat outline was I was emulating the street labels in "google maps" and I wanted a fat white halo around the text. This solution worked perfectly for me.

Here is a fiddle showing this solution

enter image description here

bower proxy configuration

Inside your local project open the .bowerrc that contains:

{
   "directory": "bower_components"
 }

and add the following code-line:

{
   "directory": "bower_components",
  "proxy": "http://yourProxy:yourPort",
  "https-proxy":"http://yourProxy:yourPort"
}

bower version: 1.7.1

Cheers

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:

eval(your_json_format_string)

Example:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

selenium - chromedriver executable needs to be in PATH

An answer from 2020. The following code solves this. A lot of people new to selenium seem to have to get past this step. Install the chromedriver and put it inside a folder on your desktop. Also make sure to put the selenium python project in the same folder as where the chrome driver is located.

Change USER_NAME and FOLDER in accordance to your computer.

For Windows

driver = webdriver.Chrome(r"C:\Users\USER_NAME\Desktop\FOLDER\chromedriver")

For Linux/Mac

driver = webdriver.Chrome("/home/USER_NAME/FOLDER/chromedriver")

How to stop execution after a certain time in Java?

you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

With this you don't need to program the loop the time measuring by yourself.

public class Starter {

    public static void main(final String[] args) {
        final ExecutorService service = Executors.newSingleThreadExecutor();

        try {
            final Future<Object> f = service.submit(() -> {
                // Do you long running calculation here
                Thread.sleep(1337); // Simulate some delay
                return "42";
            });

            System.out.println(f.get(1, TimeUnit.SECONDS));
        } catch (final TimeoutException e) {
            System.err.println("Calculation took to long");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }
    }
}

Normalize data in pandas

You can use apply for this, and it's a bit neater:

import numpy as np
import pandas as pd

np.random.seed(1)

df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)

          0         1         2         3
0  9.497381  0.552974  0.887313 -1.291874
1  6.461631 -6.206155  9.979247 -0.044828
2  4.276156  2.002518  8.848432 -5.240563
3  1.710331  1.463783  7.535078 -1.399565

df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

          0         1         2         3
0  0.515087  0.133967 -0.651699  0.135175
1  0.125241 -0.689446  0.348301  0.375188
2 -0.155414  0.310554  0.223925 -0.624812
3 -0.484913  0.244924  0.079473  0.114448

Also, it works nicely with groupby, if you select the relevant columns:

df['grp'] = ['A', 'A', 'B', 'B']

          0         1         2         3 grp
0  9.497381  0.552974  0.887313 -1.291874   A
1  6.461631 -6.206155  9.979247 -0.044828   A
2  4.276156  2.002518  8.848432 -5.240563   B
3  1.710331  1.463783  7.535078 -1.399565   B


df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

     0    1    2    3
0  0.5  0.5 -0.5 -0.5
1 -0.5 -0.5  0.5  0.5
2  0.5  0.5  0.5 -0.5
3 -0.5 -0.5 -0.5  0.5

How to concatenate variables into SQL strings

You can accomplish this (if I understand what you are trying to do) using dynamic SQL.

The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.

So you can use something like this approach:

SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue 
    + ' AS fld1 FROM tbl' + @KeyValue

EXEC (@stmt)

First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:

'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'

At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE (or EXEC for short).

The old-school sp_executesql procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.


FOLLOWUP

EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.

Consider what would happen if @KeyValue contained the string:

'1 AS foo; DROP TABLE students; -- '

The string we would produce as a SQL statement would be:

'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'

When we EXECUTE that string as a SQL statement:

INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...

And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)

One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'. If an illegal character is found, then reject the value, and exit without executing any SQL.

How to check the input is an integer or not in Java?

If you are getting the user input with Scanner, you can do:

if(yourScanner.hasNextInt()) {
    yourNumber = yourScanner.nextInt();
}

If you are not, you'll have to convert it to int and catch a NumberFormatException:

try{
    yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
    //handle exception here
}

Eliminate space before \begin{itemize}

I'm very happy with the paralist package. Besides adding the option to eliminate the space it also adds other nice things like compact versions of the itemize, enumerate and describe environments.

How to remove a web site from google analytics

You can also do in this way : select your profile then go to admin => in admin second column "Property" select the site you want to remove => go to third column "view settings" clic => on the right bottom you ll see delete the view => confirm and it s done , have a nice day all

Passing a 2D array to a C++ function

If you want to pass int a[2][3] to void func(int** pp) you need auxiliary steps as follows.

int a[2][3];
int* p[2] = {a[0],a[1]};
int** pp = p;

func(pp);

As the first [2] can be implicitly specified, it can be simplified further as.

int a[][3];
int* p[] = {a[0],a[1]};
int** pp = p;

func(pp);

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

I like to use this simple method to get the selected values and join them into a string

private string JoinCBLSelectedValues(CheckBoxList cbl, string separator = "")
{
    return string.Join(separator, cbl.Items.Cast<ListItem>().Where(li => li.Selected).ToList());
}

store return value of a Python script in a bash script

read it in the docs. If you return anything but an int or None it will be printed to stderr.

To get just stderr while discarding stdout do:

output=$(python foo.py 2>&1 >/dev/null)

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

I tried @knittl's write-tree/commit-tree approach.

branch-a: the kept branch

branch-b: the abandoned branch

// goto branch-a branch
$ git checkout branch-a

$ git write-tree
6fa6989240d2fc6490f8215682a20c63dac5560a // echo tree id? I guess

$ git commit-tree  -p branch-a -p branch-b 6fa6989240d2fc6490f8215682a20c63dac5560a
<type some commit message end with Ctrl-d>
20bc36a2b0f2537ed11328d1aedd9c3cff2e87e9 // echo new commit id

$ git reset --hard 20bc36a2b0f2537ed11328d1aedd9c3cff2e87e9

/etc/apt/sources.list" E212: Can't open file for writing

change user to root

sodu su -

browse to etc

vi sudoers

look for root user in user priviledge section. you will get it like

root ALL=(ALL:ALL) ALL 

make same entry for your user name. if you username is 'myuser' then add

myuser ALL=(ALL:ALL) ALL

it will look like

root ALL=(ALL:ALL) ALL 

myuser ALL=(ALL:ALL) ALL 

save it. change root user to your user. now try the same where you were getting the sudoers issue

Disable and later enable all table indexes in Oracle

If you are using non-parallel direct path loads then consider and benchmark not dropping the indexes at all, particularly if the indexes only cover a minority of the columns. Oracle has a mechanism for efficient maintenance of indexes on direct path loads.

Otherwise, I'd also advise making the indexes unusable instead of dropping them. Less chance of accidentally not recreating an index.

Is there any way to kill a Thread?

It is definitely possible to implement a Thread.stop method as shown in the following example code:

import sys
import threading
import time


class StopThread(StopIteration):
    pass

threading.SystemExit = SystemExit, StopThread


class Thread2(threading.Thread):

    def stop(self):
        self.__stop = True

    def _bootstrap(self):
        if threading._trace_hook is not None:
            raise ValueError('Cannot run thread with tracing!')
        self.__stop = False
        sys.settrace(self.__trace)
        super()._bootstrap()

    def __trace(self, frame, event, arg):
        if self.__stop:
            raise StopThread()
        return self.__trace


class Thread3(threading.Thread):

    def _bootstrap(self, stop_thread=False):
        def stop():
            nonlocal stop_thread
            stop_thread = True
        self.stop = stop

        def tracer(*_):
            if stop_thread:
                raise StopThread()
            return tracer
        sys.settrace(tracer)
        super()._bootstrap()

###############################################################################


def main():
    test1 = Thread2(target=printer)
    test1.start()
    time.sleep(1)
    test1.stop()
    test1.join()
    test2 = Thread2(target=speed_test)
    test2.start()
    time.sleep(1)
    test2.stop()
    test2.join()
    test3 = Thread3(target=speed_test)
    test3.start()
    time.sleep(1)
    test3.stop()
    test3.join()


def printer():
    while True:
        print(time.time() % 1)
        time.sleep(0.1)


def speed_test(count=0):
    try:
        while True:
            count += 1
    except StopThread:
        print('Count =', count)

if __name__ == '__main__':
    main()

The Thread3 class appears to run code approximately 33% faster than the Thread2 class.

How to add key,value pair to dictionary?

I got here looking for a way to add a key/value pair(s) as a group - in my case it was the output of a function call, so adding the pair using dictionary[key] = value would require me to know the name of the key(s).

In this case, you can use the update method: dictionary.update(function_that_returns_a_dict(*args, **kwargs)))

Beware, if dictionary already contains one of the keys, the original value will be overwritten.

How do I add comments to package.json for npm install?

You can always abuse the fact that duplicated keys are overwritten. This is what I just wrote:

"dependencies": {
  "grunt": "...",
  "grunt-cli": "...",

  "api-easy": "# Here is the pull request: https://github.com/...",
  "api-easy": "git://..."

  "grunt-vows": "...",
  "vows": "..."
}

However, it is not clear whether JSON allows duplicated keys (see Does JSON syntax allow duplicate keys in an object?. It seems to work with npm, so I take the risk.

The recommened hack is to use "//" keys (from the nodejs mailing list). When I tested it, it did not work with "dependencies" sections, though. Also, the example in the post uses multiple "//" keys, which implies that npm does not reject JSON files with duplicated keys. In other words, the hack above should always be fine.

Update: One annoying disadvantage of the duplicated key hack is that npm install --save silently eliminates all duplicates. Unfortunately, it is very easy to overlook it and your well-intentioned comments are gone.

The "//" hack is still the safest as it seems. However, multi-line comments will be removed by npm install --save, too.

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

CodeIgniter: 404 Page Not Found on Live Server

Try to add following line in root folder index.php after php starts:

ob_start();

This works for me.

File name without extension name VBA

This gets the file type as from the last character (so avoids the problem with dots in file names)

Function getFileType(fn As String) As String

''get last instance of "." (full stop) in a filename then returns the part of the filename starting at that dot to the end
Dim strIndex As Integer
Dim x As Integer
Dim myChar As String

strIndex = Len(fn)
For x = 1 To Len(fn)

    myChar = Mid(fn, strIndex, 1)

    If myChar = "." Then
        Exit For
    End If

    strIndex = strIndex - 1

Next x

getFileType = UCase(Mid(fn, strIndex, Len(fn) - x + 1))

End Function

I can't find my git.exe file in my Github folder

run github that you downloaded, click tools and options symbol(top right), click about github for windows and then open the debug log. under DIAGNOSTICS look for Git Executable Exists:

Use a JSON array with objects with javascript

This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:

var arrayOfObjects = [{
  "id": 28,
  "Title": "Sweden"
}, {
  "id": 56,
  "Title": "USA"
}, {
  "id": 89,
  "Title": "England"
}];

for (var i = 0; i < arrayOfObjects.length; i++) {
  var object = arrayOfObjects[i];
  for (var property in object) {
    alert('item ' + i + ': ' + property + '=' + object[property]);
  }
  // If property names are known beforehand, you can also just do e.g.
  // alert(object.id + ',' + object.Title);
}

If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.

var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...

To learn more about JSON, check MDN web docs: Working with JSON .

Parse an HTML string with JS

let content = "<center><h1>404 Not Found</h1></center>"
let result = $("<div/>").html(content).text()

content: <center><h1>404 Not Found</h1></center>,
result: "404 Not Found"

Cannot convert lambda expression to type 'string' because it is not a delegate type

My case it solved i was using

@Html.DropDownList(model => model.TypeId ...)  

using

@Html.DropDownListFor(model => model.TypeId ...) 

will solve it

How to force JS to do math instead of putting two strings together

I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value

example:

var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

dots = document.getElementById("txt").value;

could be changed to

dots = +(document.getElementById("txt").value);

to force it to a number

NOTE:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

OpenSSL and error in reading openssl.conf file

Run the command as administrator and copy the config file to somewhere where you have read rights and specify the path with the -config parameter.

UIView Infinite 360 degree rotation animation?

There are following different ways to perform 360 degree animation with UIView.

Using CABasicAnimation

var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (Double.pi))
rotationAnimation.duration = 1.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 100.0
view.layer.add(rotationAnimation, forKey: "rotationAnimation")


Here is an extension functions for UIView that handles start & stop rotation operations:

extension UIView {

    // Start rotation
    func startRotation() {
        let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.fromValue = 0
        rotation.toValue = NSNumber(value: Double.pi)
        rotation.duration = 1.0
        rotation.isCumulative = true
        rotation.repeatCount = FLT_MAX
        self.layer.add(rotation, forKey: "rotationAnimation")
    }

    // Stop rotation
    func stopRotation() {
        self.layer.removeAnimation(forKey: "rotationAnimation")
    }
}


Now using, UIView.animation closure:

UIView.animate(withDuration: 0.5, animations: { 
      view.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi)) 
}) { (isAnimationComplete) in
    // Animation completed 
}

Merge 2 arrays of objects

The easiest way is with some ES6 magic:

Merge two with duplicates:

const a = [{a: 1}, {b: 2}]
const b = [{a: 1}]

const result = a.concat(b) // [{a: 1}, {b: 2}, {a: 1}]

Without duplicates it is same as the above plus:

const distinct = [...new Set(result.map(item => item.YOUR_PROP_HERE))]

Creating multiple log files of different content with log4j

For the main logfile/appender, set up a .Threshold = INFO to limit what is actually logged in the appender to INFO and above, regardless of whether or not the loggers have DEBUG, TRACE, etc, enabled.

As for catching DEBUG and nothing above that... you'd probably have to write a custom appender.

However I'd recommend not doing this, as it sounds like it would make troubleshooting and analysis pretty hard:

  1. If your goal is to have a single file where you can look to troubleshoot something, then spanning your log data across different files will be annoying - unless you have a very regimented logging policy, you'll likely need content from both DEBUG and INFO to be able to trace execution of the problematic code effectively.
  2. By still logging all of your debug messages, you are losing any performance gains you usually get in a production system by turning the logging (way) down.

How to loop through file names returned by find?

What ever you do, don't use a for loop:

# Don't do this
for file in $(find . -name "*.txt")
do
    …code using "$file"
done

Three reasons:

  • For the for loop to even start, the find must run to completion.
  • If a file name has any whitespace (including space, tab or newline) in it, it will be treated as two separate names.
  • Although now unlikely, you can overrun your command line buffer. Imagine if your command line buffer holds 32KB, and your for loop returns 40KB of text. That last 8KB will be dropped right off your for loop and you'll never know it.

Always use a while read construct:

find . -name "*.txt" -print0 | while read -d $'\0' file
do
    …code using "$file"
done

The loop will execute while the find command is executing. Plus, this command will work even if a file name is returned with whitespace in it. And, you won't overflow your command line buffer.

The -print0 will use the NULL as a file separator instead of a newline and the -d $'\0' will use NULL as the separator while reading.

How to use WebRequest to POST some data and read response?

Here's an example of posting to a web service using the HttpWebRequest and HttpWebResponse objects.

StringBuilder sb = new StringBuilder();
    string query = "?q=" + latitude + "%2C" + longitude + "&format=xml&key=xxxxxxxxxxxxxxxxxxxxxxxx";
    string weatherservice = "http://api.worldweatheronline.com/free/v1/marine.ashx" + query;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherservice);
    request.Referer = "http://www.yourdomain.com";
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    Char[] readBuffer = new Char[256];
    int count = reader.Read(readBuffer, 0, 256);

    while (count > 0)
    {
        String output = new String(readBuffer, 0, count);
        sb.Append(output);
        count = reader.Read(readBuffer, 0, 256);
    }
    string xml = sb.ToString();

stdcall and cdecl

I want to improve on @adf88's answer. I feel that pseudocode for the STDCALL does not reflect the way of how it happens in reality. 'a', 'b', and 'c' aren't popped from the stack in the function body. Instead they are popped by the ret instruction (ret 12 would be used in this case) that in one swoop jumps back to the caller and at the same time pops 'a', 'b', and 'c' from the stack.

Here is my version corrected according to my understanding:

STDCALL:

/* 1. calling STDCALL in pseudo-assembler (similar to what the compiler outputs) */
push on the stack a copy of 'z', then copy of 'y', then copy of 'x'
call
move contents of register A to 'i' variable

/* 2. STDCALL 'Function' body in pseaudo-assembler */ copy 'a' (from stack) to register A copy 'b' (from stack) to register B add A and B, store result in A copy 'c' (from stack) to register B add A and B, store result in A jump back to caller code and at the same time pop 'a', 'b' and 'c' off the stack (a, b and c are removed from the stack in this step, result in register A)

How do I download a file from the internet to my linux server with Bash

Using wget

wget -O /tmp/myfile 'http://www.google.com/logo.jpg'

or curl:

curl -o /tmp/myfile 'http://www.google.com/logo.jpg'

Unmarshaling nested JSON objects

Like what Volker mentioned, nested structs is the way to go. But if you really do not want nested structs, you can override the UnmarshalJSON func.

https://play.golang.org/p/dqn5UdqFfJt

type A struct {
    FooBar string // takes foo.bar
    FooBaz string // takes foo.baz
    More   string 
}

func (a *A) UnmarshalJSON(b []byte) error {

    var f interface{}
    json.Unmarshal(b, &f)

    m := f.(map[string]interface{})

    foomap := m["foo"]
    v := foomap.(map[string]interface{})

    a.FooBar = v["bar"].(string)
    a.FooBaz = v["baz"].(string)
    a.More = m["more"].(string)

    return nil
}

Please ignore the fact that I'm not returning a proper error. I left that out for simplicity.

UPDATE: Correctly retrieving "more" value.

Return Bit Value as 1/0 and NOT True/False in SQL Server

Try with this script, maybe will be useful:

SELECT CAST('TRUE' as bit) -- RETURN 1
SELECT CAST('FALSE' as bit) --RETURN 0

Anyway I always would use a value of 1 or 0 (not TRUE or FALSE). Following your example, the update script would be:

Update Table Set BitField=CAST('TRUE' as bit) Where ID=1

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Try this:

jsonResponse = json.loads(response.decode('utf-8'))

Exit Shell Script Based on Process Exit Code

[ $? -eq 0 ] || exit $?; # Exit for nonzero return code

Load and execute external js file in node.js with access to local variables?

You need to understand CommonJS, which is a pattern to define modules. You shouldn't abuse GLOBAL scope that's always a bad thing to do, instead you can use the 'exports' token, like this:

// circle.js

var PI = 3.14; // PI will not be accessible from outside this module

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

And the client code that will use our module:

// client.js

var circle = require('./circle');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

This code was extracted from node.js documentation API:

http://nodejs.org/docs/v0.3.2/api/modules.html

Also, if you want to use something like Rails or Sinatra, I recommend Express (I couldn't post the URL, shame on Stack Overflow!)

Display current date and time without punctuation

A simple example in shell script

#!/bin/bash

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

How to export a MySQL database to JSON?

You can export any SQL query into JSON directly from PHPMyAdmin

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

This may also happen if you have a faulty or accidental equation in your csv file. i.e - One of the cells in your csv file starts with an equals sign (=) (An excel equation) which will, in turn throw an error. If you fix, or remove this equation by getting rid of the equals sign, it should solve the ORA-06502 error.

libstdc++-6.dll not found

useful to windows users who use eclipse for c/c++ but run *.exe file and get an error: "missing libstdc++6.dll"

4 ways to solve it

  1. Eclipse ->"Project" -> "Properties" -> "C/C++ Build" -> "Settings" -> "Tool Settings" -> "MinGW C++ Linker" -> "Misscellaneous" -> "Linker flags" (add '-static' to it)

  2. Add '{{the path where your MinGW was installed}}/bin' to current user environment variable - "Path" in Windows, then reboot eclipse, and finally recompile.

  3. Add '{{the path where your MinGW was installed}}/bin' to Windows environment variable - "Path", then reboot eclipse, and finally recompile.

  4. Copy the file "libstdc++-6.dll" to the path where the *.exe file is running, then rerun. (this is not a good way)

Note: the file "libstdc++-6.dll" is in the folder '{{the path where your MinGW was installed}}/bin'

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

TypeScript: casting HTMLElement

Since it's a NodeList, not an Array, you shouldn't really be using brackets or casting to Array. The property way to get the first node is:

document.getElementsByName(id).item(0)

You can just cast that:

var script = <HTMLScriptElement> document.getElementsByName(id).item(0)

Or, extend NodeList:

interface HTMLScriptElementNodeList extends NodeList
{
    item(index: number): HTMLScriptElement;
}
var scripts = <HTMLScriptElementNodeList> document.getElementsByName('script'),
    script = scripts.item(0);

How do I make a PHP form that submits to self?

Your submit button doesn't have a name. Add name="submit" to your submit button.

If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!

How to recover corrupted Eclipse workspace?

In my case, it was not the workspace that was broken but Eclipse itself. Even though it seemed like workspace is broken (the same error dialog, etc.), all I had to do was reinstall Eclipse and point it to the old workspace. You can't really repair a broken workspace if it is the workspace that is broken but you can do so just for good measure, maybe it'll work.

Half circle with CSS (border, outline only)

You could use border-top-left-radius and border-top-right-radius properties to round the corners on the box according to the box's height (and added borders).

Then add a border to top/right/left sides of the box to achieve the effect.

Here you go:

.half-circle {
    width: 200px;
    height: 100px; /* as the half of the width */
    background-color: gold;
    border-top-left-radius: 110px;  /* 100px of height + 10px of border */
    border-top-right-radius: 110px; /* 100px of height + 10px of border */
    border: 10px solid gray;
    border-bottom: 0;
}

WORKING DEMO.

Alternatively, you could add box-sizing: border-box to the box in order to calculate the width/height of the box including borders and padding.

.half-circle {
    width: 200px;
    height: 100px; /* as the half of the width */
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border: 10px solid gray;
    border-bottom: 0;

    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

UPDATED DEMO. (Demo without background color)

Python append() vs. + operator on lists, why do these give different results?

See the documentation:

list.append(x)

  • Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L) - Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

c.append(c) "appends" c to itself as an element. Since a list is a reference type, this creates a recursive data structure.

c += c is equivalent to extend(c), which appends the elements of c to c.

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

getting the last item in a javascript object

var myObj = {a: 1, b: 2, c: 3}, lastProperty;
for (lastProperty in myObj);
lastProperty;
//"c";

source:http://javascriptweblog.wordpress.com

How to list files in an android directory?

If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:

Android Q (10) ask permission to get access all storage. Scoped storage

I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.

How can I get the first two digits of a number?

Both of the previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too. Here's a solution for constant time and space:

num // 10 ** (int(math.log(num, 10)) - 1)

Function:

import math

def first_n_digits(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

Output:

>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456

You will need to add some checks if it's possible that your input number has less digits than you want.

top nav bar blocking top content of the page

with navbar navbar-default everything works fine, but if you are using navbar-fixed-top you have to include custom style body { padding-top: 60px;} otherwise it will block content underneath.

Set up git to pull and push all branches

The full procedure that worked for me to transfer ALL branches and tags is, combining the answers of @vikas027 and @kumarahul:

~$ git clone <url_of_old_repo>
~$ cd <name_of_old_repo>
~$ git remote add new-origin <url_of_new_repo>
~$ git push new-origin --mirror
~$ git push new-origin refs/remotes/origin/*:refs/heads/*
~$ git push new-origin --delete HEAD

The last step is because a branch named HEAD appears in the new remote due to the wildcard

Prevent textbox autofill with previously entered values

Please note that for Chrome to work properly it needs to be autocomplete="false"

JavaScript Array splice vs slice

Most answers are too wordy.

  • splice and slice return rest of elements in the array.
  • splice mutates the array being operated with elements removed while slice not.

enter image description here

How do I rotate a picture in WinForms

I found this article

  /// <summary>
    /// Creates a new Image containing the same image only rotated
    /// </summary>
    /// <param name=""image"">The <see cref=""System.Drawing.Image"/"> to rotate
    /// <param name=""offset"">The position to rotate from.
    /// <param name=""angle"">The amount to rotate the image, clockwise, in degrees
    /// <returns>A new <see cref=""System.Drawing.Bitmap"/"> of the same size rotated.</see>
    /// <exception cref=""System.ArgumentNullException"">Thrown if <see cref=""image"/"> 
    /// is null.</see>
    public static Bitmap RotateImage(Image image, PointF offset, float angle)
    {
        if (image == null)
            throw new ArgumentNullException("image");

        //create a new empty bitmap to hold rotated image
        Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
        rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        //make a graphics object from the empty bitmap
        Graphics g = Graphics.FromImage(rotatedBmp);

        //Put the rotation point in the center of the image
        g.TranslateTransform(offset.X, offset.Y);

        //rotate the image
        g.RotateTransform(angle);

        //move the image back
        g.TranslateTransform(-offset.X, -offset.Y);

        //draw passed in image onto graphics object
        g.DrawImage(image, new PointF(0, 0));

        return rotatedBmp;
    }

Correlation between two vectors?

For correlations you can just use the corr function (statistics toolbox)

corr(A_1(:), A_2(:))

Note that you can also just use

corr(A_1, A_2)

But the linear indexing guarantees that your vectors don't need to be transposed.

Styling HTML email for Gmail

The answers here are outdated, as of today Sep 30 2016. Gmail is currently rolling out support for the style tag in the head, as well as media queries. If Gmail is your only concern, you're safe to use classes like a modern developer!

For reference, you can check the official gmail CSS docs.

As a side note, Gmail was the only major client that didn't support style (reference, until they update anyway). That means you can almost safely stop putting styles inline. Some of the more obscure clients may still need them.

How to get label of select option with jQuery?

I found this helpful

$('select[name=users] option:selected').text()

When accessing the selector using the this keyword.

$(this).find('option:selected').text()

SQL query for today's date minus two months

TSQL, Alternative using variable declaration. (it might improve Query's readability)

DECLARE @gapPeriod DATETIME = DATEADD(MONTH,-2,GETDATE()); --Period:Last 2 months.

SELECT 
        *
    FROM 
        FB as A
    WHERE
        A.Dte <= @gapPeriod;                               --only older records.

How do I make a simple crawler in PHP?

I came up with the following spider code. I adapted it a bit from the following: PHP - Is the there a safe way to perform deep recursion? it seems fairly rapid....

    <?php
function  spider( $base_url , $search_urls=array() ) {
    $queue[] = $base_url;
    $done           =   array();
    $found_urls     =   array();
    while($queue) {
            $link = array_shift($queue);
            if(!is_array($link)) {
                $done[] = $link;
                foreach( $search_urls as $s) { if (strstr( $link , $s )) { $found_urls[] = $link; } }
                if( empty($search_urls)) { $found_urls[] = $link; }
                if(!empty($link )) {
echo 'LINK:::'.$link;
                      $content =    file_get_contents( $link );
//echo 'P:::'.$content;
                    preg_match_all('~<a.*?href="(.*?)".*?>~', $content, $sublink);
                    if (!in_array($sublink , $done) && !in_array($sublink , $queue)  ) {
                           $queue[] = $sublink;
                    }
                }
            } else {
                    $result=array();
                    $return = array();
                    // flatten multi dimensional array of URLs to one dimensional.
                    while(count($link)) {
                         $value = array_shift($link);
                         if(is_array($value))
                             foreach($value as $sub)
                                $link[] = $sub;
                         else
                               $return[] = $value;
                     }
                     // now loop over one dimensional array.
                     foreach($return as $link) {
                                // echo 'L::'.$link;
                                // url may be in form <a href.. so extract what's in the href bit.
                                preg_match_all('/<a[^>]+href=([\'"])(?<href>.+?)\1[^>]*>/i', $link, $result);
                                if ( isset( $result['href'][0] )) { $link = $result['href'][0]; }
                                // add the new URL to the queue.
                                if( (!strstr( $link , "http")) && (!in_array($base_url.$link , $done)) && (!in_array($base_url.$link , $queue)) ) {
                                     $queue[]=$base_url.$link;
                                } else {
                                    if ( (strstr( $link , $base_url  ))  && (!in_array($base_url.$link , $done)) && (!in_array($base_url.$link , $queue)) ) {
                                         $queue[] = $link;
                                    }
                                }
                      }
            }
    }


    return $found_urls;
}    


    $base_url       =   'https://www.houseofcheese.co.uk/';
    $search_urls    =   array(  $base_url.'acatalog/' );
    $done = spider( $base_url  , $search_urls  );

    //
    // RESULT
    //
    //
    echo '<br /><br />';
    echo 'RESULT:::';
    foreach(  $done as $r )  {
        echo 'URL:::'.$r.'<br />';
    }

PHP, MySQL error: Column count doesn't match value count at row 1

Your query has 8 or possibly even 9 variables, ie. Name, Description etc. But the values, these things ---> '', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", only total 7, the number of variables have to be the same as the values.

I had the same problem but I figured it out. Hopefully it will also work for you.

Python-Requests close http connection

please use response.close() to close to avoid "too many open files" error

for example:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd'))
....
r.close()

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

Catch a thread's exception in the caller thread in Python

pygolang provides sync.WorkGroup which, in particular, propagates exception from spawned worker threads to the main thread. For example:

#!/usr/bin/env python
"""This program demostrates how with sync.WorkGroup an exception raised in
spawned thread is propagated into main thread which spawned the worker."""

from __future__ import print_function
from golang import sync, context

def T1(ctx, *argv):
    print('T1: run ... %r' % (argv,))
    raise RuntimeError('T1: problem')

def T2(ctx):
    print('T2: ran ok')

def main():
    wg = sync.WorkGroup(context.background())
    wg.go(T1, [1,2,3])
    wg.go(T2)

    try:
        wg.wait()
    except Exception as e:
        print('Tmain: caught exception: %r\n' %e)
        # reraising to see full traceback
        raise

if __name__ == '__main__':
    main()

gives the following when run:

T1: run ... ([1, 2, 3],)
T2: ran ok
Tmain: caught exception: RuntimeError('T1: problem',)

Traceback (most recent call last):
  File "./x.py", line 28, in <module>
    main()
  File "./x.py", line 21, in main
    wg.wait()
  File "golang/_sync.pyx", line 198, in golang._sync.PyWorkGroup.wait
    pyerr_reraise(pyerr)
  File "golang/_sync.pyx", line 178, in golang._sync.PyWorkGroup.go.pyrunf
    f(pywg._pyctx, *argv, **kw)
  File "./x.py", line 10, in T1
    raise RuntimeError('T1: problem')
RuntimeError: T1: problem

The original code from the question would be just:

    wg = sync.WorkGroup(context.background())

    def _(ctx):
        shul.copytree(sourceFolder, destFolder)
    wg.go(_)

    # waits for spawned worker to complete and, on error, reraises
    # its exception on the main thread.
    wg.wait()

Is iterating ConcurrentHashMap values thread safe?

You may use this class to test two accessing threads and one mutating the shared instance of ConcurrentHashMap:

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Map<String, String> map;

    public Accessor(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (Map.Entry<String, String> entry : this.map.entrySet())
      {
        System.out.println(
            Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']'
        );
      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Map<String, String> map;
    private final Random random = new Random();

    public Mutator(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (int i = 0; i < 100; i++)
      {
        this.map.remove("key" + random.nextInt(MAP_SIZE));
        this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
        System.out.println(Thread.currentThread().getName() + ": " + i);
      }
    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.map);
    Accessor a2 = new Accessor(this.map);
    Mutator m = new Mutator(this.map);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

No exception will be thrown.

Sharing the same iterator between accessor threads can lead to deadlock:

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();
  private final Iterator<Map.Entry<String, String>> iterator;

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
    this.iterator = this.map.entrySet().iterator();
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Iterator<Map.Entry<String, String>> iterator;

    public Accessor(Iterator<Map.Entry<String, String>> iterator)
    {
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while(iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        try
        {
          String st = Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
        } catch (Exception e)
        {
          e.printStackTrace();
        }

      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Map<String, String> map;
    private final Random random = new Random();

    public Mutator(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (int i = 0; i < 100; i++)
      {
        this.map.remove("key" + random.nextInt(MAP_SIZE));
        this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
      }
    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.iterator);
    Accessor a2 = new Accessor(this.iterator);
    Mutator m = new Mutator(this.map);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

As soon as you start sharing the same Iterator<Map.Entry<String, String>> among accessor and mutator threads java.lang.IllegalStateExceptions will start popping up.

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();
  private final Iterator<Map.Entry<String, String>> iterator;

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
    this.iterator = this.map.entrySet().iterator();
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Iterator<Map.Entry<String, String>> iterator;

    public Accessor(Iterator<Map.Entry<String, String>> iterator)
    {
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while (iterator.hasNext())
      {
        Map.Entry<String, String> entry = iterator.next();
        try
        {
          String st =
              Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
        } catch (Exception e)
        {
          e.printStackTrace();
        }

      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Random random = new Random();

    private final Iterator<Map.Entry<String, String>> iterator;

    private final Map<String, String> map;

    public Mutator(Map<String, String> map, Iterator<Map.Entry<String, String>> iterator)
    {
      this.map = map;
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while (iterator.hasNext())
      {
        try
        {
          iterator.remove();
          this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
        } catch (Exception ex)
        {
          ex.printStackTrace();
        }
      }

    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.iterator);
    Accessor a2 = new Accessor(this.iterator);
    Mutator m = new Mutator(map, this.iterator);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

How to use a jQuery plugin inside Vue

Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.

npm install jquery --save

Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.

// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;

// You can use it now
$('body').css('background-color', 'orange');

// Here you can add the code for different plugins

Refresh a page using JavaScript or HTML

Here are 535 ways to reload a page using javascript, very cool:

Here are the first 20:

location = location
location = location.href
location = window.location
location = self.location
location = window.location.href
location = self.location.href
location = location['href']
location = window['location']
location = window['location'].href
location = window['location']['href']
location = window.location['href']
location = self['location']
location = self['location'].href
location = self['location']['href']
location = self.location['href']
location.assign(location)
location.replace(location)
window.location.assign(location)
window.location.replace(location)
self.location.assign(location)

and the last 10:

self['location']['replace'](self.location['href'])
location.reload()
location['reload']()
window.location.reload()
window['location'].reload()
window.location['reload']()
window['location']['reload']()
self.location.reload()
self['location'].reload()
self.location['reload']()
self['location']['reload']()

Original Article

How to remove empty lines with or without whitespace in Python

Using regex:

if re.match(r'^\s*$', line):
    # line is empty (has only the following: \t\n\r and whitespace)

Using regex + filter():

filtered = filter(lambda x: not re.match(r'^\s*$', x), original)

As seen on codepad.

Is it possible to get only the first character of a String?

Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.

              String mob=edit_mobile.getText().toString();
                    if (mob.length() >= 10) {
                        if (mob.contains("+91")) {
                            mob= mob.substring(3, 13);
                        }
                        if (mob.substring(0, 1).contains("0")) {
                            mob= mob.substring(1, 11);
                        }
                        if (mob.contains("+")) {
                            mob= mob.replace("+", "");
                        }
                        mob= mob.substring(0, 10);
                        Log.i("mob", mob);

                    }

Interface vs Abstract Class (general OO)

Though this question is quite old, I would like to add one other point in favor of interfaces:

Interfaces can be injected using any Dependency Injection tools where as Abstract class injection supported by very few.

How do I fix twitter-bootstrap on IE?

I had the same problem and none of the other answers worked. My problem was a weird one where IE9 wasn't able to connect to any https sites, therefore since I was using the online maxcdn bootstrap files like,

https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css

none of that css and js was being applied. Going into the Advanced tab of Internet Explorer options I verified that not having "use TLS 1.0" checked caused the problem with https sites and files, and once checked my bootstrap page was formatted as expected.

As others have noted use the proper doctype below (maybe a valid html4 doctype will work, but if you're starting anew might as well use html5.)

The respond js and html5 shim (if using that) are for IE8. IE9 doesn't need that. The code below uses the standard method of targeting ie8 and below.

--Art

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<!-- content -->
</body>
</html>

Rails Object to hash

If you are looking for only attributes, then you can get them by:

@post.attributes

Note that this calls ActiveModel::AttributeSet.to_hash every time you invoke it, so if you need to access the hash multiple times you should cache it in a local variable:

attribs = @post.attributes

npm ERR! network getaddrinfo ENOTFOUND

I also faced this error but I was not working behind a proxy server at the moment so using npm config set proxy=http://address:8080 couldn't help and ~/.npmrc didn't contain any proxy setting either. The solution in my case was just to restart my computer.

SQLException : String or binary data would be truncated

In general, there isn't a way to determine which particular statement caused the error. If you're running several, you could watch profiler and look at the last completed statement and see what the statement after that might be, though I have no idea if that approach is feasible for you.

In any event, one of your parameter variables (and the data inside it) is too large for the field it's trying to store data in. Check your parameter sizes against column sizes and the field(s) in question should be evident pretty quickly.

Is it possible to center text in select box?

Yes, it is possible. You can use text-align-last

text-align-last: center;

Reading serial data in realtime in Python

You can use inWaiting() to get the amount of bytes available at the input queue.

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)

How can I make Bootstrap columns all the same height?

From official documentation. Maybe you can use it in your case.

When you need equal height, add .h-100 to the cards.

<div class="row row-cols-1 row-cols-md-3 g-4">
  <div class="col">
   <div class="card h-100">
     <div>.....</div>
  </div>
  <div class="col">
   <div class="card h-100">
     <div>.....</div>
  </div>

Is there a standardized method to swap two variables in Python?

I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ y
y = y ^ x
x = x ^ y

Or concisely,

x ^= y
y ^= x
x ^= y

Temporary variable

w = x
x = y
y = w
del w

Tuple swap

x, y = y, x

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Android Imagebutton change Image OnClick

That is because imgButton is null. Try this instead:

findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);

or much easier to read:

imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);

then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);

Promise Error: Objects are not valid as a React child

You can't do this: {this.state.arrayFromJson} As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map to do that.

I am pasting a link from where you can learn how to render elements from an array with React.

http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/

Hope it helps!

What does 'synchronized' mean?

Here is an explanation from The Java Tutorials.

Consider the following code:

public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}

if count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:

  • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
  • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

vertical divider between two columns in bootstrap

Well what I did was remove the gutter between the respective spans then drawing a left border for the left span and a right border for the right span in such a way that their borders overlapped just to give a single line. This way the visible line will just be one of borders.

CSS

.leftspan
{
padding-right:20px;
border-right: 1px solid #ccc;
}

.row-fluid .rightspan {
margin-left: -0.138297872340425%;
*margin-left: -0.13191489361702%;
padding-left:20px;
border-left: 1px solid #ccc;
}

.row-fluid .rightspan:first-child {
margin-left: -0.11063829787234%;
*margin-left: -0.104255319148938%;
}

HTML

  <div class="row-fluid" >
      <div class="span8 leftspan" >
      </div>

      <div class="span4 rightspan"  >
      </div>
 </div>

Try this it works for me

Fixing broken UTF-8 encoding

In my case, I found out by using "mb_convert_encoding" that the previous encoding was iso-8859-1 (which is latin1) then I fixed my problem by using an sql query :

UPDATE myDB.myTable SET myColumn = CAST(CAST(CONVERT(myColumn USING latin1) AS binary) AS CHAR)

However, it is stated in the mysql documentations that conversion may be lossy if the column contains characters that are not in both character sets.

Factory Pattern. When to use factory methods?

One situation where I personally find separate Factory classes to make sense is when the final object you are trying to create relies on several other objects. E.g, in PHP: Suppose you have a House object, which in turn has a Kitchen and a LivingRoom object, and the LivingRoom object has a TV object inside as well.

The simplest method to achieve this is having each object create their children on their construct method, but if the properties are relatively nested, when your House fails creating you will probably spend some time trying to isolate exactly what is failing.

The alternative is to do the following (dependency injection, if you like the fancy term):

$TVObj = new TV($param1, $param2, $param3);
$LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
$KitchenroomObj = new Kitchen($param1, $param2);
$HouseObj = new House($LivingroomObj, $KitchenroomObj);

Here if the process of creating a House fails there is only one place to look, but having to use this chunk every time one wants a new House is far from convenient. Enter the Factories:

class HouseFactory {
    public function create() {
        $TVObj = new TV($param1, $param2, $param3);
        $LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
        $KitchenroomObj = new Kitchen($param1, $param2);
        $HouseObj = new House($LivingroomObj, $KitchenroomObj);

        return $HouseObj;
    }
}

$houseFactory = new HouseFactory();
$HouseObj = $houseFactory->create();

Thanks to the factory here the process of creating a House is abstracted (in that you don't need to create and set up every single dependency when you just want to create a House) and at the same time centralized which makes it easier to maintain. There are other reasons why using separate Factories can be beneficial (e.g. testability) but I find this specific use case to illustrate best how Factory classes can be useful.

Exact difference between CharSequence and String in java

other than the fact that String implements CharSequence and that String is a sequence of character.

Several things happen in your code:

CharSequence obj = "hello";

That creates a String literal, "hello", which is a String object. Being a String, which implements CharSequence, it is also a CharSequence. (you can read this post about coding to interface for example).

The next line:

String str = "hello";

is a little more complex. String literals in Java are held in a pool (interned) so the "hello" on this line is the same object (identity) as the "hello" on the first line. Therefore, this line only assigns the same String literal to str.

At this point, both obj and str are references to the String literal "hello" and are therefore equals, == and they are both a String and a CharSequence.

I suggest you test this code, showing in action what I just wrote:

public static void main(String[] args) {
    CharSequence obj = "hello";
    String str = "hello";
    System.out.println("Type of obj: " + obj.getClass().getSimpleName());
    System.out.println("Type of str: " + str.getClass().getSimpleName());
    System.out.println("Value of obj: " + obj);
    System.out.println("Value of str: " + str);
    System.out.println("Is obj a String? " + (obj instanceof String));
    System.out.println("Is obj a CharSequence? " + (obj instanceof CharSequence));
    System.out.println("Is str a String? " + (str instanceof String));
    System.out.println("Is str a CharSequence? " + (str instanceof CharSequence));
    System.out.println("Is \"hello\" a String? " + ("hello" instanceof String));
    System.out.println("Is \"hello\" a CharSequence? " + ("hello" instanceof CharSequence));
    System.out.println("str.equals(obj)? " + str.equals(obj));
    System.out.println("(str == obj)? " + (str == obj));
}

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

How to create a horizontal loading progress bar?

Worked for me , can try with the same

<ProgressBar
    android:id="@+id/determinateBar"
    android:indeterminateOnly="true"
    android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"
    android:indeterminateDuration="10"
    android:indeterminateBehavior="repeat"
    android:progressBackgroundTint="#208afa"
    android:progressBackgroundTintMode="multiply"
    android:minHeight="24dip"
    android:maxHeight="24dip"
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:visibility="visible"/>

Spring @ContextConfiguration how to put the right location for the xml

Simple solution is

@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml" })

from spring forum

What is a .NET developer?

Though I consider myself a .NET developer, I don't prefer calling it that way. c# developer sounds much better and is a much clearer message: it says that I understand both C# and .NET (because C# and .NET are tied together). I could call myself a VB.NET developer, same story there.

What is a .NET developer? I don't know, because you cannot develop with .NET, if develop is a synonym for programming. .NET is the environment, the libraries, the languages, the CLR, the CLI, JIT, the LR, the BCL, the IDE and the IL. I find it a poor job description, but it may also mean that they don't really care: either you are an F#, a C#, an IronPython or a VB.NET developer, they're all implicitly and secretly .NET developers.

What do you need? A solid understanding why ".NET" is a poor job description and ask for a more precise one. Nobody can know everything of .NET, it is simply too wide. Orientate yourself to all sides of it and do both ASP.NET and WinForms. Don't forget Silverlight, WPF etc and two or three .NET languages.

In other words: know the forest by knowing what trees and flowers it habitats and specialize in knowing a few beautiful and common ones well.

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

How to get value in the session in jQuery

Sessions are stored on the server and are set from server side code, not client side code such as JavaScript.

What you want is a cookie, someone's given a brilliant explanation in this Stack Overflow question here: How do I set/unset cookie with jQuery?

You could potentially use sessions and set/retrieve them with jQuery and AJAX, but it's complete overkill if Cookies will do the trick.

new Date() is working in Chrome but not Firefox

If you still want to create date using dashes, you can use this format:

var date = new Date('2013-08-31T17:00:00Z')

But bear in mind, that it creates time according to UTC. Meaning, if you live in GMT+3 (3 hours ahead of GMT) timezone, it will add this timezone offset to the time. So the above example will have this value, if GMT+3 (note that it is hour 20:00 and not 17:00):

Sat Aug 31 2013 20:00:00 GMT+0300 (FLE Standard Time)

Be sure to add 'Z' letter at the end, because otherwise Chrome and Firefox will parse the string differently (one will add time offset and the other won't).

Python extending with - using super() Python 3 vs Python 2

In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__. So if you don't define it in your class, you will get the one from the base.

Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__, your class will inherit the first one only.

In such cases, you should really use super if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).

If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super):

class A:
    def __init__(self):
        print('A')
        super().__init__()

class B:
    def __init__(self):
        print('B')
        super().__init__()

class C(A, B):
    pass

C()
#prints:
#A
#B

Notice how both base classes use super even though they don't have their own base classes.

What super does is: it calls the method from the next class in MRO (method resolution order). The MRO for C is: (C, A, B, object). You can print C.__mro__ to see it.

So, C inherits __init__ from A and super in A.__init__ calls B.__init__ (B follows A in MRO).

So by doing nothing in C, you end up calling both, which is what you want.

Now if you were not using super, you would end up inheriting A.__init__ (as before) but this time there's nothing that would call B.__init__ for you.

class A:
    def __init__(self):
        print('A')

class B:
    def __init__(self):
        print('B')

class C(A, B):
    pass

C()
#prints:
#A

To fix that you have to define C.__init__:

class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

The problem with that is that in more complicated MI trees, __init__ methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.

max(length(field)) in mysql

I suppose you could use a solution such as this one :

select name, length(name)
from users
where id = (
    select id
    from users
    order by length(name) desc
    limit 1
);

Might not be the optimal solution, though... But seems to work.

Getting the absolute path of the executable, using C#?

using System.Reflection;

string myExeDir = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.ToString();

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

maybe whole database + tables + fields should have the same charset??!

i.e.

CREATE TABLE `politicas` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Nombre` varchar(250) CHARACTER SET utf8 NOT NULL,
  -------------------------------------^here!!!!!!!!!!!
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
  -------------------------------------------------^here!!!!!!!!!

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

I'm unsing ubuntu 14.04

Below command solved this problem for me.

sudo apt-get install php-mysql

In my case, after updating my php version from 5.5.9 to 7.0.8 i received this error including two other errors.

errors:

  1. laravel/framework v5.2.14 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.

  2. phpunit/phpunit 4.8.22 requires ext-dom * -> the requested PHP extension dom is missing from your system.

  3. [PDOException]
    could not find driver

Solutions:

I installed this packages and my problems are gone.

sudo apt-get install php-mbstring

sudo apt-get install php-xml

sudo apt-get install php-mysql

How can I print the contents of an array horizontally?

public static void Main(string[] args)
{
    int[] numbers = new int[10];

    Console.Write("index ");

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = i;
        Console.Write(numbers[i] + " ");
    }

    Console.WriteLine("");
    Console.WriteLine("");
    Console.Write("value ");

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = numbers.Length - i;
        Console.Write(numbers[i] + " ");
    }

    Console.ReadKey();
}

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

_x000D_
_x000D_
console.log(String(5).padStart(2, '0'));
_x000D_
_x000D_
_x000D_

How to compare two lists in python?

From your post I gather that you want to compare dates, not arrays. If this is the case, then use the appropriate object: a datetime object.

Please check the documentation for the datetime module. Dates are a tough cookie. Use reliable algorithms.

How do I center an SVG in a div?

Put your code in between this div if you are using bootstrap:

  <div class="text-center ">
  <i class="fa fa-twitter" style="font-size:36px "></i>
  <i class="fa fa-pinterest" style="font-size:36px"></i>
  <i class="fa fa-dribbble" style="font-size:36px"></i>
  <i class="fa fa-instagram" style="font-size:36px"></i>
  </div>

How to get span tag inside a div in jQuery and assign a text?

Try this:

$("#message span").text("hello world!");

See it in your code!

function Errormessage(txt) {
    var m = $("#message");

    // set text before displaying message
    m.children("span").text(txt);

    // bind close listener
    m.children("a.close-notify").click(function(){
      m.fadeOut("slow");
    });

    // display message
    m.fadeIn("slow");
}

How to add border around linear layout except at the bottom?

Save this xml and add as a background for the linear layout....

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <stroke android:width="4dp" android:color="#FF00FF00" /> 
    <solid android:color="#ffffff" /> 
    <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
    <corners android:radius="4dp" /> 
</shape>

Hope this helps! :)

How do a LDAP search/authenticate against this LDAP in Java

try {
    LdapContext ctx = new InitialLdapContext(env, null);
    ctx.setRequestControls(null);
    NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
    while (namingEnum.hasMore ()) {
        SearchResult result = (SearchResult) namingEnum.next ();    
        Attributes attrs = result.getAttributes ();
        System.out.println(attrs.get("cn"));

    } 
    namingEnum.close();
} catch (Exception e) {
    e.printStackTrace();
}

private SearchControls getSimpleSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setTimeLimit(30000);
    //String[] attrIDs = {"objectGUID"};
    //searchControls.setReturningAttributes(attrIDs);
    return searchControls;
}

How to print to console using swift playground?

for displaying variables only in playground, just mention the variable name without anything

let stat = 100

stat // this outputs the value of stat on playground right window

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

Since Stack Overflow’s broken RSS just resurrected this question for me, here’s my almost-general solution: JAValueToString

This lets you write JA_DUMP(cgPoint) and get cgPoint = {0, 0} logged.

Android SQLite: Update Statement

The SQLiteDatabase object depends on the type of operation on the database.

More information, visit the official website:

https://developer.android.com/training/basics/data-storage/databases.html#UpdateDbRow

It explains how to manipulate consultations on the SQLite database.

INSERT ROW

Gets the data repository in write mode

SQLiteDatabase db = mDbHelper.getWritableDatabase();

Create a new map of values, where column names are the keys

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

Insert the new row, returning the primary key value of the new row

long newRowId;
newRowId = db.insert(
     FeedEntry.TABLE_NAME,
     FeedEntry.COLUMN_NAME_NULLABLE,
     values);

UPDATE ROW

Define 'where' part of query.

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";

Specify arguments in placeholder order.

String[] selectionArgs = { String.valueOf(rowId) };


SQLiteDatabase db = mDbHelper.getReadableDatabase();

New value for one column

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);

Which row to update, based on the ID

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
    int count = db.update(
    FeedReaderDbHelper.FeedEntry.TABLE_NAME,
    values,
    selection,
    selectionArgs);

T-SQL and the WHERE LIKE %Parameter% clause

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

Postgresql : syntax error at or near "-"

Wrap it in double quotes

alter user "dell-sys" with password 'Pass@133';

Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys" then you will have to issue exact the same whenever you refer to that user.

I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.

css background image in a different folder from css

you can use this

body{ background-image: url('../img/bg.png'); }


I tried this on my project where I need to set the background image of a div so I used this and it worked!

Why am I getting AttributeError: Object has no attribute

Your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.

Winforms TableLayoutPanel adding rows programmatically

This works perfectly for adding rows and controls in a TableLayoutPanel.

Define a blank Tablelayoutpanel with 3 columns in the design page

    Dim TableLayoutPanel3 As New TableLayoutPanel()

    TableLayoutPanel3.Name = "TableLayoutPanel3"

    TableLayoutPanel3.Location = New System.Drawing.Point(32, 287)

    TableLayoutPanel3.AutoSize = True

    TableLayoutPanel3.Size = New System.Drawing.Size(620, 20)

    TableLayoutPanel3.ColumnCount = 3

    TableLayoutPanel3.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single

    TableLayoutPanel3.BackColor = System.Drawing.Color.Transparent

    TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 26.34146!))

    TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 73.65854!))

    TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 85.0!))

    Controls.Add(TableLayoutPanel3)

Create a button btnAddRow to add rows on each click

     Private Sub btnAddRow_Click(sender As System.Object, e As System.EventArgs) Handles btnAddRow.Click

          TableLayoutPanel3.GrowStyle = TableLayoutPanelGrowStyle.AddRows

          TableLayoutPanel3.RowStyles.Add(New RowStyle(SizeType.Absolute, 20))

          TableLayoutPanel3.SuspendLayout()

          TableLayoutPanel3.RowCount += 1

          Dim tb1 As New TextBox()

          Dim tb2 As New TextBox()

          Dim tb3 As New TextBox()

          TableLayoutPanel3.Controls.Add(tb1 , 0, TableLayoutPanel3.RowCount - 1)

          TableLayoutPanel3.Controls.Add(tb2, 1, TableLayoutPanel3.RowCount - 1)

          TableLayoutPanel3.Controls.Add(tb3, 2, TableLayoutPanel3.RowCount - 1)

          TableLayoutPanel3.ResumeLayout()

          tb1.Focus()

 End Sub

How to add a Hint in spinner in XML

For Kotlin

What will you get:

Gray color if the hint is selected

Drop down list with gray color of the hint

Black color if something else than the hint is selected

I have added 5. step what changes the color of the text in the spinner depending on the selected item, because I couldn't find it here. In this case it is needed to change the text color to gray when the first item is selected in order to it looks like a hint.

  1. Define a spinner in your activity_layout.xml

    <Spinner
        android:id="@+id/mySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    
  2. Define the string array in string.xml where the first item will be a hint.

    <string-array name="your_string_array">
        <item>Hint...</item>
        <item>Item1</item>
        <item>Item2</item>
        <item>Item3</item>
    </string-array>
    
  3. Set up the spinner in the onCreate method in your Activity.kt

    Get string array from resources

        val items= resources.getStringArray(R.array.your_string_array)
    

    Create spinner adapter

        val spinnerAdapter= object : ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, items) {
    
        override fun isEnabled(position: Int): Boolean {
            // Disable the first item from Spinner
            // First item will be use for hint
            return position != 0
        }
    
        override fun getDropDownView(
            position: Int,
            convertView: View?,
            parent: ViewGroup
        ): View {
            val view: TextView = super.getDropDownView(position, convertView, parent) as TextView
            //set the color of first item in the drop down list to gray
            if(position == 0) {
                view.setTextColor(Color.GRAY)
            } else {
                //here is it possible to define color for other items by
                //view.setTextColor(Color.RED)
            }
            return view
        }
    
    }
    
  4. Set drop down view resource and attach the adapter to your spinner.

    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)     
    mySpinner.adapter = spinnerAdapter
    
  5. Change the color of the text in the spinner depending on the selected item

    mySpinner.onItemSelectedListener = object: AdapterView.OnItemSelectedListener{
        override fun onNothingSelected(parent: AdapterView<*>?) {
        }
    
        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {
            val value = parent!!.getItemAtPosition(position).toString()
            if(value == items[0]){
                (view as TextView).setTextColor(Color.GRAY)
            }
        }
    
    }
    

A project with an Output Type of Class Library cannot be started directly

The project you've downloaded is a class library, not an executable assembly. This means you need to import that library into your own project instead of trying to run it directly.

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

Docker error: invalid reference format: repository name must be lowercase

Indeed, the docker registry as of today (sha 2e2f252f3c88679f1207d87d57c07af6819a1a17e22573bcef32804122d2f305) does not handle paths containing upper-case characters. This is obviously a poor design choice, probably due to wanting to maintain compatible with certain operating systems that do not distinguish case at the file level (ie, windows).

If one authenticates for a scope and tries to fetch a non-existing repository with all lowercase, the output is

(auth step not shown)
curl -s -H "Authorization: Bearer $TOKEN" -X GET https://$LOCALREGISTRY/v2/test/someproject/tags/list
{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":[{"Type":"repository","Class":"","Name":"test/someproject","Action":"pull"}]}]}

However, if one tries to do this with an uppercase component, only 404 is returned:

(authorization step done but not shown here)
$ curl -s -H "Authorization: Bearer $TOKEN" -X GET https://docker.uibk.ac.at:443/v2/test/Someproject/tags/list

404 page not found

File Not Found when running PHP with Nginx

For me, problem was Typo in location path.

Maybe first thing to check out for this kind of problem

Is path to project.

Password masking console application

Reading console input is hard, you need to handle special keys like Ctrl, Alt, also cursor keys and Backspace/Delete. On some keyboard layouts, like Swedish Ctrl is even needed to enter keys that exist directly on US keyboard. I believe that trying to handle this using the "low-level" Console.ReadKey(true) is just very hard, so the easiest and most robust way is to just to disable "console input echo" during entering password using a bit of WINAPI.

The sample below is based on answer to Read a password from std::cin question.

    private enum StdHandle
    {
        Input = -10,
        Output = -11,
        Error = -12,
    }

    private enum ConsoleMode
    {
        ENABLE_ECHO_INPUT = 4
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr GetStdHandle(StdHandle nStdHandle);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out int lpMode);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetConsoleMode(IntPtr hConsoleHandle, int dwMode);

    public static string ReadPassword()
    {
        IntPtr stdInputHandle = GetStdHandle(StdHandle.Input);
        if (stdInputHandle == IntPtr.Zero)
        {
            throw new InvalidOperationException("No console input");
        }

        int previousConsoleMode;
        if (!GetConsoleMode(stdInputHandle , out previousConsoleMode))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not get console mode.");
        }

        // disable console input echo
        if (!SetConsoleMode(stdInputHandle , previousConsoleMode & ~(int)ConsoleMode.ENABLE_ECHO_INPUT))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not disable console input echo.");
        }

        // just read the password using standard Console.ReadLine()
        string password = Console.ReadLine();

        // reset console mode to previous
        if (!SetConsoleMode(stdInputHandle , previousConsoleMode))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not reset console mode.");
        }

        return password;
    }

How to find foreign key dependencies in SQL Server?

Just a note for @"John Sansom" answer,

If the foreign key dependencies are sought, I think that the PT Where clause should be:

i1.CONSTRAINT_TYPE = 'FOREIGN KEY'  -- instead of 'PRIMARY KEY'

and its the ON condition:

ON PT.TABLE_NAME = FK.TABLE_NAME – instead of PK.TABLE_NAME

As commonly is used the primary key of the foreign table, I think this issue has not been noticed before.

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

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

public List<string> GetJsonValues(string filePath, string propertyName)
{
  List<string> values = new List<string>();
  string read = string.Empty;
  using (StreamReader r = new StreamReader(filePath))
  {
    var json = r.ReadToEnd();
    var jObj = JObject.Parse(json);
    foreach (var j in jObj.Properties())
    {
      if (j.Name.Equals(propertyName))
      {
        var value = jObj[j.Name] as JArray;
        return values = value.ToObject<List<string>>();
      }
    }
    return values;
  }
}

How to spawn a process and capture its STDOUT in .NET?

I just tried this very thing and the following worked for me:

StringBuilder outputBuilder;
ProcessStartInfo processStartInfo;
Process process;

outputBuilder = new StringBuilder();

processStartInfo = new ProcessStartInfo();
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.Arguments = "<insert command line arguments here>";
processStartInfo.FileName = "<insert tool path here>";

process = new Process();
process.StartInfo = processStartInfo;
// enable raising events because Process does not raise events by default
process.EnableRaisingEvents = true;
// attach the event handler for OutputDataReceived before starting the process
process.OutputDataReceived += new DataReceivedEventHandler
(
    delegate(object sender, DataReceivedEventArgs e)
    {
        // append the new data to the data already read-in
        outputBuilder.Append(e.Data);
    }
);
// start the process
// then begin asynchronously reading the output
// then wait for the process to exit
// then cancel asynchronously reading the output
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.CancelOutputRead();

// use the output
string output = outputBuilder.ToString();

Insert auto increment primary key to existing table

suppose you don't have column for auto increment like id, no, then you can add using following query:

ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST

If you've column, then alter to auto increment using following query:

 ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY

Verify host key with pysftp

Do not set cnopts.hostkeys = None (as the second most upvoted answer shows), unless you do not care about security. You lose a protection against Man-in-the-middle attacks by doing so.


Use CnOpts.hostkeys (returns HostKeys) to manage trusted host keys.

cnopts = pysftp.CnOpts(knownhosts='known_hosts')

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

where the known_hosts contains a server public key(s)] in a format like:

example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

If you do not want to use an external file, you can also use

from base64 import decodebytes
# ...

keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add('example.com', 'ssh-rsa', key)

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

Though as of pysftp 0.2.9, this approach will issue a warning, what seems like a bug:
"Failed to load HostKeys" warning while connecting to SFTP server with pysftp


An easy way to retrieve the host key in the needed format is using OpenSSH ssh-keyscan:

$ ssh-keyscan example.com
# example.com SSH-2.0-OpenSSH_5.3
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

(due to a bug in pysftp, this does not work, if the server uses non-standard port – the entry starts with [example.com]:port + beware of redirecting ssh-keyscan to a file in PowerShell)

You can also make the application do the same automatically:
Use Paramiko AutoAddPolicy with pysftp
(It will automatically add host keys of new hosts to known_hosts, but for known host keys, it will not accept a changed key)


Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

See my article Where do I get SSH host key fingerprint to authorize the server?
It's for my WinSCP SFTP client, but most information there is valid in general.


If you need to verify the host key using its fingerprint only, see Python - pysftp / paramiko - Verify host key using its fingerprint.

AssertContains on strings in jUnit

Use the new assertThat syntax together with Hamcrest.

It is available starting with JUnit 4.4.

Resizing an image in an HTML5 canvas

Fast and simple Javascript image resizer:

https://github.com/calvintwr/blitz-hermite-resize

const blitz = Blitz.create()

/* Promise */
blitz({
    source: DOM Image/DOM Canvas/jQuery/DataURL/File,
    width: 400,
    height: 600
}).then(output => {
    // handle output
})catch(error => {
    // handle error
})

/* Await */
let resized = await blizt({...})

/* Old school callback */
const blitz = Blitz.create('callback')
blitz({...}, function(output) {
    // run your callback.
})

History

This is really after many rounds of research, reading and trying.

The resizer algorithm uses @ViliusL's Hermite script (Hermite resizer is really the fastest and gives reasonably good output). Extended with features you need.

Forks 1 worker to do the resizing so that it doesn't freeze your browser when resizing, unlike all other JS resizers out there.

SUM of grouped COUNT in SQL Query

For Sql server you can try this one.

SELECT ISNULL([NAME],'SUM'),Count([NAME]) AS COUNT
FROM TABLENAME
GROUP BY [NAME] WITH CUBE

How to access the value of a promise?

promiseA(pram).then(
     result => { 
     //make sure promiseA function allready success and response
     //do something here
}).catch(err => console.log(err)) => {
     // handle error with try catch
}

What is the reason behind "non-static method cannot be referenced from a static context"?

You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.

Make $JAVA_HOME easily changable in Ubuntu

Try these steps.

--We are going to edit "etc\profile". The environment variables are to be input at the bottom of the file. Since Ubuntu does not give access to root folder, we will have to use a few commands in the terminal

Step1: Start Terminal. Type in command: gksudo gedit /etc/profile

Step2: The profile text file will open. Enter the environment variables at the bottom of the page........... Eg: export JAVA_HOME=/home/alex/jdk1.6.0_22/bin/java

export PATH=/home/alex/jdk1.6.0_22/bin:$PATH

step3: save and close the file. Check if the environment variables are set by using echo command........ Eg echo $PATH

Phone Number Validation MVC

Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:

$(".phone").keyup(function () {
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));

There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

how do I initialize a float to its max/min value?

May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?

Kubernetes Pod fails with CrashLoopBackOff

Pod is not started due to problem coming after initialization of POD.

Check and use command to get docker container of pod

docker ps -a | grep private-reg

Output will be information of docker container with id.

See docker logs:

docker logs -f <container id>

Get the time difference between two datetimes

This should work fine.

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);

console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());

encapsulation vs abstraction real world example

Abstraction

It is used to manage complexities of OOPs. By using this property we can provide essential features of an object to the user without including its background explanations. For example, when sending message to a friend we simply write the message, say "hiiii" and press "send" and the message gets delivered to its destination (her,friend). Here we see abstraction at work, ie we are less concerned with the internal working of mobile that is responsible for sending and receiving message

How to copy a map?

I'd use recursion just in case so you can deep copy the map and avoid bad surprises in case you were to change a map element that is a map itself.

Here's an example in a utils.go:

package utils

func CopyMap(m map[string]interface{}) map[string]interface{} {
    cp := make(map[string]interface{})
    for k, v := range m {
        vm, ok := v.(map[string]interface{})
        if ok {
            cp[k] = CopyMap(vm)
        } else {
            cp[k] = v
        }
    }

    return cp
}

And its test file (i.e. utils_test.go):

package utils

import (
    "testing"

    "github.com/stretchr/testify/require"
)

func TestCopyMap(t *testing.T) {
    m1 := map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
    }

    m2 := CopyMap(m1)

    m1["a"] = "zzz"
    delete(m1, "b")

    require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
    require.Equal(t, map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
    }, m2)
}

It should easy enough to adapt if you need the map key to be something else instead of a string.

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

Starting with Sql Server 2012: string concatenation function CONCAT converts to string implicitly. Therefore, another option is

SELECT Id AS 'PatientId',
       CONCAT(ParentId,'') AS 'ParentId'
FROM Patients

CONCAT converts null values to empty strings.

Some will consider this hacky, because it merely exploits a side effect of a function while the function itself isn't required for the task in hand.

How to coerce a list object to type 'double'

If your list as multiple elements that need to be converted to numeric, you can achieve this with lapply(a, as.numeric).

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Are you missing any maven build.

Apart from above JRE changes.I still faced similar issue.I was missing JUnit dependency after adding it is working fine.

Hope this will help.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

This was caused because of something like this in my case:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <include-prelude>/headerfooter/header.jsp</include-prelude>
        <include-coda>/headerfooter/footer.jsp</include-coda>
    </jsp-property-group>
</jsp-config>

The problem was actually I did not have header.jsp in my project. However the error message was still saying index_jsp was not found.

XML shape drawable not rendering desired color

I had a similar problem and found that if you remove the size definition, it works for some reason.

Remove:

<size
    android:width="60dp"
    android:height="40dp" />

from the shape.

Let me know if this works!

Update query with PDO and MySQL

Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

$sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";

How to "log in" to a website using Python's Requests module?

Find out the name of the inputs used on the websites form for usernames <...name=username.../> and passwords <...name=password../> and replace them in the script below. Also replace the URL to point at the desired site to log into.

login.py

#!/usr/bin/env python

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
payload = { 'username': '[email protected]', 'password': 'blahblahsecretpassw0rd' }
url = 'https://website.com/login.html'
requests.post(url, data=payload, verify=False)

The use of disable_warnings(InsecureRequestWarning) will silence any output from the script when trying to log into sites with unverified SSL certificates.

Extra:

To run this script from the command line on a UNIX based system place it in a directory, i.e. home/scripts and add this directory to your path in ~/.bash_profile or a similar file used by the terminal.

# Custom scripts
export CUSTOM_SCRIPTS=home/scripts
export PATH=$CUSTOM_SCRIPTS:$PATH

Then create a link to this python script inside home/scripts/login.py

ln -s ~/home/scripts/login.py ~/home/scripts/login

Close your terminal, start a new one, run login

Insert into a MySQL table or update if exists

Try this:

INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'

Note:
Here if id is the primary key then after first insertion with id='1' every time attempt to insert id='1' will update name and age and previous name age will change.

Why do I need to override the equals and hashCode methods in Java?

In the example below, if you comment out the override for equals or hashcode in the Person class, this code will fail to look up Tom's order. Using the default implementation of hashcode can cause failures in hashtable lookups.

What I have below is a simplified code that pulls up people's order by Person. Person is being used as a key in the hashtable.

public class Person {
    String name;
    int age;
    String socialSecurityNumber;

    public Person(String name, int age, String socialSecurityNumber) {
        this.name = name;
        this.age = age;
        this.socialSecurityNumber = socialSecurityNumber;
    }

    @Override
    public boolean equals(Object p) {
        //Person is same if social security number is same

        if ((p instanceof Person) && this.socialSecurityNumber.equals(((Person) p).socialSecurityNumber)) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    public int hashCode() {        //I am using a hashing function in String.java instead of writing my own.
        return socialSecurityNumber.hashCode();
    }
}


public class Order {
    String[]  items;

    public void insertOrder(String[]  items)
    {
        this.items=items;
    }

}



import java.util.Hashtable;

public class Main {

    public static void main(String[] args) {

       Person p1=new Person("Tom",32,"548-56-4412");
        Person p2=new Person("Jerry",60,"456-74-4125");
        Person p3=new Person("Sherry",38,"418-55-1235");

        Order order1=new Order();
        order1.insertOrder(new String[]{"mouse","car charger"});

        Order order2=new Order();
        order2.insertOrder(new String[]{"Multi vitamin"});

        Order order3=new Order();
        order3.insertOrder(new String[]{"handbag", "iPod"});

        Hashtable<Person,Order> hashtable=new Hashtable<Person,Order>();
        hashtable.put(p1,order1);
        hashtable.put(p2,order2);
        hashtable.put(p3,order3);

       //The line below will fail if Person class does not override hashCode()
       Order tomOrder= hashtable.get(new Person("Tom", 32, "548-56-4412"));
        for(String item:tomOrder.items)
        {
            System.out.println(item);
        }
    }
}

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

How can I make an entire HTML form "readonly"?

Another simple way that's supported by all browsers would be:

HTML:

<form class="disabled">
  <input type="text" name="name" />
  <input type="radio" name="gender" value="male">
  <input type="radio" name="gender" value="female">
  <input type="checkbox" name="vegetarian">
</form>

CSS:

.disabled {
  pointer-events: none;
  opacity: .4;
}

But be aware, that the tabbing still works with this approach and the elements with focus can still be manipulated by the user.

Add directives from directive in AngularJS

A simple solution that could work in some cases is to create and $compile a wrapper and then append your original element to it.

Something like...

link: function(scope, elem, attr){
    var wrapper = angular.element('<div tooltip></div>');
    elem.before(wrapper);
    $compile(wrapper)(scope);
    wrapper.append(elem);
}

This solution has the advantage that it keeps things simple by not recompiling the original element.

This wouldn't work if any of the added directive's require any of the original element's directives or if the original element has absolute positioning.

How to display an error message in an ASP.NET Web Application

The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}

Turning multi-line string into single comma-separated

You can use awk and sed:

awk -vORS=, '{ print $2 }' file.txt | sed 's/,$/\n/'

Or if you want to use a pipe:

echo "data" | awk -vORS=, '{ print $2 }' | sed 's/,$/\n/'

To break it down:

  • awk is great at handling data broken down into fields
  • -vORS=, sets the "output record separator" to ,, which is what you wanted
  • { print $2 } tells awk to print the second field for every record (line)
  • file.txt is your filename
  • sed just gets rid of the trailing , and turns it into a newline (if you want no newline, you can do s/,$//)

Show Error on the tip of the Edit Text Android

if(TextUtils.isEmpty(firstName.getText().toString()){
      firstName.setError("TEXT ERROR HERE");
}

Or you can also use TextInputLayout which has some useful method and some user friendly animation

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

Indeed, the 9th byte indicates the check state of the button, but the answers above don't take into account the checkbox which enables manual configuration. This check state value is also present in this ninth byte. The real answer should thus be:

Byte value

00001001 = Manual proxy is checked

00000101 = Use automatic configuration script is checked

00000011 = Automatically detect settings is checked

When multiple checkboxes are checked, the value of the 9th byte is the result of the bitwise OR operation on the values for which the checkbox is checked.

Running the new Intel emulator for Android

If all else fails. Simply try to download the Intel HAXM zip manually, extract and install. check here

Remember this only works for an Intel cpu that supports Intel Virtualization Technology. And you MUST enable virtulization in your bios.

It's a fairly decent and very noticeable improvement to the android emulator if you ask me.

Excel Reference To Current Cell

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

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

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

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

If you want THIS to work in Conditional Formatting formulas:

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

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

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

Google access token expiration time

Since there is no accepted answer I will try to answer this one:

[s] - seconds

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

If you are not using Conda but vanilla Python, 'brew install graphviz' works.

How does paintComponent work?

Calling object.paintComponent(g) is an error.

Instead this method is called automatically when the panel is created. The paintComponent() method can also be called explicitly by the repaint() method defined in Component class.

The effect of calling repaint() is that Swing automatically clears the graphic on the panel and executes the paintComponent method to redraw the graphics on this panel.

Change table header color using bootstrap

Try This:

table.table tr th{background-color:blue !important; font-color:white !important;}

hope this helps..

Where is svcutil.exe in Windows 7?

To find any file location

  1. In windows start menu Search box
  2. type in svcutil.exe
  3. Wait for results to populate
  4. Right click on svcutil.exe and Select 'Open file location'
  5. Copy Windows explorer path

jQuery Refresh/Reload Page if Ajax Success after time

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

I tried everything but nothing worked. So I just used : chmod -R 777 to htdocs. At least it's only in my local.

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

How to convert a hex string to hex number

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

print hex(new_int)[2:]

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

How to make a loop in x86 assembly language?

You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:

gcd_alg:
    subl    %ecx, %eax      /* a = a - c */
    cmpl    $0, %eax        /* if a == 0 */
    je      gcd_done        /* jump to end */
    cmpl    %ecx, %eax      /* if a < c */
    jl      gcd_preswap     /* swap and start over */
    jmp     gcd_alg         /* keep subtracting */

Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.

As for clearing the screen, that depends on the system you're using.

TypeError: object of type 'int' has no len() error assistance needed

Abstract:

The reason why you are getting this error message is because you are trying to call a method on an int type of a variable. This would work if would have called len() function on a list type of a variable. Let's examin the two cases:

Fail:

num = 10

print(len(num))

The above will produce an error similar to yours due to calling len() function on an int type of a variable;

Success:

data = [0, 4, 8, 9, 12]

print(len(data))

The above will work since you are calling a function on a list type of a variable;

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

Plotting using a CSV file

This should get you started:

set datafile separator ","
plot 'infile' using 0:1

Oracle 12c Installation failed to access the temporary location

This error could caused by a username with Chinese characters.

  1. Create a new local windows user with an English username. Make sure there are no spaces in the username.
  2. Install Oracle using the user you just created.

How to access JSON Object name/value?

I think you should mention dataType: 'json' in ajax config and to access that value:

data[0].name

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

In response to

Don't hardcode /sdcard/

Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.

Known types: HTC One X and Samsung S3.

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

How can I disable a button on a jQuery UI dialog?

Looks like anyone, even in this linked question, have proposed this solution, similar to the first part of the answer given by Nick Craver:

$("#dialog").dialog({
    width: 480,
    height: "auto",
    buttons: [
        {
            id: "button-cancel",
            text: "Cancel",
            click: function() {
                $(this).dialog("close");
            }
        },
        {
            id: "button-ok",
            text: "Ok",
            click: function() {
                $(this).dialog("close");
            }
        }
    ]
});

Then, elsewhere, you should be able to use the API for the jquery UI button:

$("#button-ok").button("disable");

How might I force a floating DIV to match the height of another floating DIV?

Having had the same sort of problem as well, requiring three divs next to each other with different content, with right-borders to 'seperate' them, the only solution that worked was a slightly modified version of the jQuery option in another answer. Remember you also need the script found here.

Below is my slightly modified version of the script, which just allows for a true min-height setting (as I needed my boxes to be at least a certain height).

/*--------------------------------------------------------------------
 * JQuery Plugin: "EqualHeights"
 * by:    Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description:   Compares the heights or widths of the top-level children of a provided element
                  and sets their min-height to the tallest height (or width to widest width). Sets in em units
                  by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method    (article:
                  http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)
 * Usage Example: $(element).equalHeights();
                  Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
                  Optional: to specify an actual min-height (in px), pass an integer value, regardless of previous parameter: $(element).equalHeights(false,150);
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeights = function(px,minheightval) {
    $(this).each(function(){
        if (minheightval != undefined) { 
            var currentTallest = minheightval;    
        } 
        else { 
            var currentTallest = 0;
        }
        $(this).children().each(function(i){
            if ($(this).height() > currentTallest) { 
                currentTallest = $(this).height();
            }
        });
        if (!px || !Number.prototype.pxToEm) 
            currentTallest = currentTallest.pxToEm(); //Use ems unless px is specified.
        // For Internet Explorer 6, set height since min-height isn't supported.
        if ($.browser.msie && $.browser.version == 6.0) { 
            $(this).children().css({'height': currentTallest});
        }
        $(this).children().css({'min-height': currentTallest});
    });
    return this;
};

It works like a charm and doesn't slow anything down :)

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

All you need to do is make sure that the checkbox shown below is checked.

enter image description here

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0]