Programs & Examples On #Glossary

What is declarative programming?

It may sound odd, but I'd add Excel (or any spreadsheet really) to the list of declarative systems. A good example of this is given here.

What is a 'Closure'?

Currying : It allows you to partially evaluate a function by only passing in a subset of its arguments. Consider this:

function multiply (x, y) {
  return x * y;
}

const double = multiply.bind(null, 2);

const eight = double(4);

eight == 8;

Closure: A closure is nothing more than accessing a variable outside of a function's scope. It is important to remember that a function inside a function or a nested function isn't a closure. Closures are always used when need to access the variables outside the function scope.

function apple(x){
   function google(y,z) {
    console.log(x*y);
   }
   google(7,2);
}

apple(3);

// the answer here will be 21

What is the difference between procedural programming and functional programming?

To expand on Konrad's comment:

As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined;

Because of this, functional code is generally easier to parallelize. Since there are (generally) no side effects of the functions, and they (generally) just act on their arguments, a lot of concurrency issues go away.

Functional programming is also used when you need to be capable of proving your code is correct. This is much harder to do with procedural programming (not easy with functional, but still easier).

Disclaimer: I haven't used functional programming in years, and only recently started looking at it again, so I might not be completely correct here. :)

Abstraction VS Information Hiding VS Encapsulation

Abstraction simply means the technique in which only essential details of software is made visible to the user to help the user to use or operate with software, thus implementation details of that software are not shown(are made invisible). Encapsulation is the technique that have package that hold one or more items and hence some of information (particularly program details) became visible and some not visible to the user, so encapsulation is achieved through information hiding. In summary. Abstraction is for observable behavior (externally) and encapsulation is for invisibility (internally) but these two are really complementary.

What are the differences between delegates and events?

To define about event in simple way:

Event is a REFERENCE to a delegate with two restrictions

  1. Cannot be invoked directly
  2. Cannot be assigned values directly (e.g eventObj = delegateMethod)

Above two are the weak points for delegates and it is addressed in event. Complete code sample to show the difference in fiddler is here https://dotnetfiddle.net/5iR3fB .

Toggle the comment between Event and Delegate and client code that invokes/assign values to delegate to understand the difference

Here is the inline code.

 /*
This is working program in Visual Studio.  It is not running in fiddler because of infinite loop in code.
This code demonstrates the difference between event and delegate
        Event is an delegate reference with two restrictions for increased protection

            1. Cannot be invoked directly
            2. Cannot assign value to delegate reference directly

Toggle between Event vs Delegate in the code by commenting/un commenting the relevant lines
*/

public class RoomTemperatureController
{
    private int _roomTemperature = 25;//Default/Starting room Temperature
    private bool _isAirConditionTurnedOn = false;//Default AC is Off
    private bool _isHeatTurnedOn = false;//Default Heat is Off
    private bool _tempSimulator = false;
    public  delegate void OnRoomTemperatureChange(int roomTemperature); //OnRoomTemperatureChange is a type of Delegate (Check next line for proof)
    // public  OnRoomTemperatureChange WhenRoomTemperatureChange;// { get; set; }//Exposing the delegate to outside world, cannot directly expose the delegate (line above), 
    public  event OnRoomTemperatureChange WhenRoomTemperatureChange;// { get; set; }//Exposing the delegate to outside world, cannot directly expose the delegate (line above), 

    public RoomTemperatureController()
    {
        WhenRoomTemperatureChange += InternalRoomTemperatuerHandler;
    }
    private void InternalRoomTemperatuerHandler(int roomTemp)
    {
        System.Console.WriteLine("Internal Room Temperature Handler - Mandatory to handle/ Should not be removed by external consumer of ths class: Note, if it is delegate this can be removed, if event cannot be removed");
    }

    //User cannot directly asign values to delegate (e.g. roomTempControllerObj.OnRoomTemperatureChange = delegateMethod (System will throw error)
    public bool TurnRoomTeperatureSimulator
    {
        set
        {
            _tempSimulator = value;
            if (value)
            {
                SimulateRoomTemperature(); //Turn on Simulator              
            }
        }
        get { return _tempSimulator; }
    }
    public void TurnAirCondition(bool val)
    {
        _isAirConditionTurnedOn = val;
        _isHeatTurnedOn = !val;//Binary switch If Heat is ON - AC will turned off automatically (binary)
        System.Console.WriteLine("Aircondition :" + _isAirConditionTurnedOn);
        System.Console.WriteLine("Heat :" + _isHeatTurnedOn);

    }
    public void TurnHeat(bool val)
    {
        _isHeatTurnedOn = val;
        _isAirConditionTurnedOn = !val;//Binary switch If Heat is ON - AC will turned off automatically (binary)
        System.Console.WriteLine("Aircondition :" + _isAirConditionTurnedOn);
        System.Console.WriteLine("Heat :" + _isHeatTurnedOn);

    }

    public async void SimulateRoomTemperature()
    {
        while (_tempSimulator)
        {
            if (_isAirConditionTurnedOn)
                _roomTemperature--;//Decrease Room Temperature if AC is turned On
            if (_isHeatTurnedOn)
                _roomTemperature++;//Decrease Room Temperature if AC is turned On
            System.Console.WriteLine("Temperature :" + _roomTemperature);
            if (WhenRoomTemperatureChange != null)
                WhenRoomTemperatureChange(_roomTemperature);
            System.Threading.Thread.Sleep(500);//Every second Temperature changes based on AC/Heat Status
        }
    }

}

public class MySweetHome
{
    RoomTemperatureController roomController = null;
    public MySweetHome()
    {
        roomController = new RoomTemperatureController();
        roomController.WhenRoomTemperatureChange += TurnHeatOrACBasedOnTemp;
        //roomController.WhenRoomTemperatureChange = null; //Setting NULL to delegate reference is possible where as for Event it is not possible.
        //roomController.WhenRoomTemperatureChange.DynamicInvoke();//Dynamic Invoke is possible for Delgate and not possible with Event
        roomController.SimulateRoomTemperature();
        System.Threading.Thread.Sleep(5000);
        roomController.TurnAirCondition (true);
        roomController.TurnRoomTeperatureSimulator = true;

    }
    public void TurnHeatOrACBasedOnTemp(int temp)
    {
        if (temp >= 30)
            roomController.TurnAirCondition(true);
        if (temp <= 15)
            roomController.TurnHeat(true);

    }
    public static void Main(string []args)
    {
        MySweetHome home = new MySweetHome();
    }


}

Setting up maven dependency for SQL Server

There is also an alternative: you could use the open-source jTDS driver for MS-SQL Server, which is compatible although not made by Microsoft. For that driver, there is a maven artifact that you can use:

http://jtds.sourceforge.net/

From http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds :

<dependency>
    <groupId>net.sourceforge.jtds</groupId>
    <artifactId>jtds</artifactId>
    <version>1.3.1</version>
</dependency>

UPDATE nov 2016, Microsoft now published its MSSQL JDBC driver on github and it's also available on maven now:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre8</version>
</dependency>

Python pip install fails: invalid command egg_info

try the following command:

pip install setuptools==28.8.0

how to remove the bold from a headline?

<h1><span style="font-weight:bold;">THIS IS</span> A HEADLINE</h1>

But be sure that h1 is marked with

font-weight:normal;

You can also set the style with a id or class attribute.

Bitwise and in place of modulus operator

In this specific case (mod 7), we still can replace %7 with bitwise operators:

// Return X%7 for X >= 0.
int mod7(int x)
{
  while (x > 7) x = (x&7) + (x>>3);
  return (x == 7)?0:x;
}

It works because 8%7 = 1. Obviously, this code is probably less efficient than a simple x%7, and certainly less readable.

fetch in git doesn't get all branches

The problem can be seen when checking the remote.origin.fetch setting
(The lines starting with $ are bash prompts with the commands I typed. The other lines are the resulting output)

$ git config --get remote.origin.fetch
+refs/heads/master:refs/remotes/origin/master

As you can see, in my case, the remote was set to fetch the master branch specifically and only. I fixed it as per below, including the second command to check the results.

$ git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
$ git config --get remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*

The wildcard * of course means everything under that path.

Unfortunately I saw this comment after I had already dug through and found the answer by trial and error.

How to get Month Name from Calendar?

This code has language support. I had used them in Android App.

String[] mons = new DateFormatSymbols().getShortMonths();//Jan,Feb,Mar,... 

String[] months = new DateFormatSymbols().getMonths();//January,Februaty,March,...

Differentiate between function overloading and function overriding

In addition to the existing answers, Overridden functions are in different scopes; whereas overloaded functions are in same scope.

Specified cast is not valid?

Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();                
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }

Finding length of char array

sizeof returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7] which is 7 * sizeof(char). Since sizeof(char) = 1, the result is 7.

Expanding this to another example:

int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));

would yield 5 * sizeof(int), so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int) might differ)

To return to your problem:

It seems like, that what you want to know is the length of the string which is contained inside your array and not the total array size.

By definition C-Strings have to be terminated with a trailing '\0' (0-Byte). So to get the appropriate length of the string contained within your array, you have to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.

All standard functions build upon this definition, so if you call strlen to retrieve the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.

Another thing you might need to know that only because you don't fill the remaining elements of your char[7] with a value, they actually do contain random undefined values.

Hope that helped.

Should methods in a Java interface be declared with or without a public access modifier?

With the introduction of private, static, default modifiers for interface methods in Java 8/9, things get more complicated and I tend to think that full declarations are more readable (needs Java 9 to compile):

public interface MyInterface {

    //minimal
    int CONST00 = 0;
    void method00();
    static void method01() {}
    default void method02() {}
    private static void method03() {}
    private void method04() {}

    //full
    public static final int CONST10 = 0;
    public abstract void method10();
    public static void method11() {}
    public default void method12() {}
    private static void method13() {}
    private void method14() {}

}

Missing artifact com.sun:tools:jar

I got this problem and it turns out that JBossDevStudio 9.1 on Windows is a 32-bit program. Eclipse, and thus the JBossDevStudio, does not work with the wrong type of JVM. 64-bit eclipse needs a 64-bit JVM, 32-bit eclipse needs a 32-bit JVM. Thus configuring Eclipse to run with my installed 64-bit JDK did not work.

Installing a 32 bit JDK and running Eclipse from that solved the problem.

At least for one of my projects, an other where I had tried to configure a runtime JDK in the Eclipse project properties is still broken.

What's the difference between process.cwd() vs __dirname?

Knowing the scope of each can make things easier to remember.

process is node's global object, and .cwd() returns where node is running.

__dirname is module's property, and represents the file path of the module. In node, one module resides in one file.

Similarly, __filename is another module's property, which holds the file name of the module.

Modifying location.hash without page scrolling

Adding this here because the more relevant questions have all been marked as duplicates pointing here…

My situation is simpler:

  • user clicks the link (a[href='#something'])
  • click handler does: e.preventDefault()
  • smoothscroll function: $("html,body").stop(true,true).animate({ "scrollTop": linkoffset.top }, scrollspeed, "swing" );
  • then window.location = link;

This way, the scroll occurs, and there's no jump when the location is updated.

What's the console.log() of java?

The Log class:

API for sending log output.

Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e() methods.

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

Outside of Android, System.out.println(String msg) is used.

Swift - How to hide back button in navigation item?

This is also found in the UINavigationController class documentation:

navigationItem.hidesBackButton = true

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

java.net.BindException: Address already in use: JVM_Bind <null>:80

I do a goofy mistake and It take me 2 hour to solve It.I mentioned it here for other persons may be help them.The mistake was I enable ssl connector and changed both https and http ports to same number .

Jquery to get SelectedText from dropdown

Get text from a dropdown multiple

var texts = [];
$('#list :selected').each(function(){
    texts.push($(this).text());
});

texts now contains a list of selected text

Count the number of items in my array list

You want to count the number of itemids in your array. Simply use:

int counter=list.size();

Less code increases efficiency. Do not re-invent the wheel...

How to deploy a Java Web Application (.war) on tomcat?

As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webappdirectory.

Now, if Tomcat is installed and running on bilgin.ath.cx (as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80 on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk?, mod_proxy?). You should either give us more details or discuss this with your hosting provider.

Update: As expected, the bilgin.ath.cx is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties file to configure the workers and the httpd.conf for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount directive in Apache httpd.conf for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.

1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

Understanding dispatch_async

Swift version

This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.

DispatchQueue.global(qos: .background).async {
    
    // Background Thread
    
    DispatchQueue.main.async {
        // Run UI Updates
    }
}

Upload files with FTP using PowerShell

I am not sure you can 100% bullet proof the script from not hanging or crashing, as there are things outside your control (what if the server loses power mid-upload?) - but this should provide a solid foundation for getting you started:

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()

Create a hidden field in JavaScript

You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true.

You can also add multiple hidden fields. Use this way:

CustomizePPT.setHiddenFields( 
    { 
        "hidden" : 
        {
            'fieldinFORM' : 'thisdata201' , 
            'fieldinFORM2' : 'this3' //multiple hidden fields
            .
            .
            .
            .
            .
            'nNoOfFields' : 'nthData'
        },
    "form" : 
    {
        "status" : "true",
        "formID" : "form3"
    } 
} );

_x000D_
_x000D_
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
    var request = [];_x000D_
 var container = '';_x000D_
 console.log(arguments);_x000D_
 request = arguments[0].hidden;_x000D_
    console.log(arguments[0].hasOwnProperty('form'));_x000D_
 if(arguments[0].hasOwnProperty('form') == true)_x000D_
 {_x000D_
  if(arguments[0].form.status == 'true'){_x000D_
   var parent = document.getElementById("container");_x000D_
   container = document.createElement('form');_x000D_
   parent.appendChild(container);_x000D_
   Object.assign(container, {'id':arguments[0].form.formID});_x000D_
  }_x000D_
 }_x000D_
 else{_x000D_
   container = document.getElementById("container");_x000D_
 }_x000D_
 _x000D_
 //var container = document.getElementById("container");_x000D_
 Object.keys(request).forEach(function(elem)_x000D_
 {_x000D_
  if($('#'+elem).length <= 0){_x000D_
   console.log("Hidden Field created");_x000D_
   var input = document.createElement('input');_x000D_
   Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
   container.appendChild(input);_x000D_
  }else{_x000D_
   console.log("Hidden Field Exists and value is below" );_x000D_
   $('#'+elem).val(request[elem]);_x000D_
  }_x000D_
 });_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Generating a unique machine id

I hate to be the guy who says, "you're just doing it wrong" (I always hate that guy ;) but...

Does it have to be repeatably generated for the unique machine? Could you just assign the identifier or do a public/private key? Maybe if you could generate and store the value, you could access it from both OS installs on the same disk?

You've probably explored these options and they doesn't work for you, but if not, it's something to consider.

If it's not a matter of user trust, you could just use MAC addresses.

Using CSS in Laravel views?

put your css in public folder, then

add this in you blade file

<link rel="stylesheet" type="text/css" href="{{ asset('mystyle.css') }}">

HTML img onclick Javascript

Developers also take care about accessibility.

Do not use onClick on images without defining the ARIA role.

Non-interactive HTML elements and non-interactive ARIA roles indicate content and containers in the user interface. A non-interactive element does not support event handlers (mouse and key handlers).

The developer and designers are responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support. More info see WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets.

tldr; this is how it should be done:

  <img
    src="pond1.jpg"
    alt="pic id code"
    onClick="window.open(this.src)"
    role="button"
    tabIndex="0"
  />

Determine path of the executing script

I have wrapped up and extended the answers to this question into a new function thisfile() in rprojroot. Also works for knitting with knitr.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

HashSet vs LinkedHashSet

I suggest you to use LinkedHashSet most of the time, because it has better performance overall):

  1. Predictable iteration order LinkedHashSet (Oracle)
  2. LinkedHashSet is more expensive for insertions than HashSet;
  3. In general slightly better performance than HashMap, because the most of the time we use Set structures for iterating.

Performance tests:

------------- TreeSet -------------
 size       add  contains   iterate
   10       746       173        89
  100       501       264        68
 1000       714       410        69
10000      1975       552        69
------------- HashSet -------------
 size       add  contains   iterate
   10       308        91        94
  100       178        75        73
 1000       216       110        72
10000       711       215       100
---------- LinkedHashSet ----------
 size       add  contains   iterate
   10       350        65        83
  100       270        74        55
 1000       303       111        54
10000      1615       256        58

You can see source test page here: The Final Performance Testing Example

How do I create a timer in WPF?

In WPF, you use a DispatcherTimer.

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();


private void dispatcherTimer_Tick(object sender, EventArgs e)
{
  // code goes here
}

Password encryption/decryption code in .NET

 string clearText = txtPassword.Text;
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

In may case, I nedded to copy the gacutil.exe, gacutil.exe.config AND ALSO the gacutlrc.dll (from the 1033 directory)

Creating a JSON dynamically with each input value using jquery

I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

In your case:

var array = [];
$("input[class=email]").each(function() {
    array.push({
        title: $(this).attr("title"),
        email: $(this).val()
    });
});
// then to get the JSON string
var jsonString = JSON.stringify(array);

iOS start Background Thread

Well that's pretty easy actually with GCD. A typical workflow would be something like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        // Perform async operation
        // Call your method/function here
        // Example:
        // NSString *result = [anObject calculateSomething];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update UI
                    // Example:
                    // self.myLabel.text = result;
                });
    });

For more on GCD you can take a look into Apple's documentation here

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

How to log as much information as possible for a Java Exception?

The java.util.logging package is standard in Java SE. Its Logger includes an overloaded log method that accepts Throwable objects. It will log stacktraces of exceptions and their cause for you.

For example:

import java.util.logging.Level;
import java.util.logging.Logger;

[...]

Logger logger = Logger.getAnonymousLogger();
Exception e1 = new Exception();
Exception e2 = new Exception(e1);
logger.log(Level.SEVERE, "an exception was thrown", e2);

Will log:

SEVERE: an exception was thrown
java.lang.Exception: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:21)
Caused by: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:20)

Internally, this does exactly what @philipp-wendler suggests, by the way. See the source code for SimpleFormatter.java. This is just a higher level interface.

How do I put my website's logo to be the icon image in browser tabs?

It is called 'favicon' and you need to add below code to the header section of your website.

Simply add this to the <head> section.

<link rel="icon" href="/your_path_to_image/favicon.jpg">

JRE installation directory in Windows

Following on from my other comment, here's a batch file which displays the current JRE or JDK based on the registry values.

It's different from the other solutions in instances where java is installed, but not on the PATH.

@ECHO off

SET KIT=JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=Wow6432Node\JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=Wow6432Node\JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

ECHO Failed to find Java
GOTO :EOF

:FoundJRE
call:ReadRegValue JAVAPATH "HKLM\Software\%KIT%\%VER%" "JavaHome"
ECHO %JAVAPATH%
GOTO :EOF

:ReadRegValue
SET key=%2%
SET name=%3%
SET "%~1="
SET reg=reg
IF DEFINED ProgramFiles(x86) (
  IF EXIST %WINDIR%\sysnative\reg.exe SET reg=%WINDIR%\sysnative\reg.exe
)
FOR /F "usebackq tokens=3* skip=1" %%A IN (`%reg% QUERY %key% /v %name% 2^>NUL`) DO SET "%~1=%%A %%B"
GOTO :EOF

How can I order a List<string>?

ListaServizi = ListaServizi.OrderBy(q => q).ToList();

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

how to get program files x86 env variable?

On a Windows 64 bit machine, echo %programfiles(x86)% does print C:\Program Files (x86)

How to remove gaps between subplots in matplotlib?

The problem is the use of aspect='equal', which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.

Normally, this would work:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])

plt.subplots_adjust(wspace=0, hspace=0)

The result is this:

However, with aspect='equal', as in the following code:

import matplotlib.pyplot as plt

ax = [plt.subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

plt.subplots_adjust(wspace=0, hspace=0)

This is what we get:

The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using aspect='equal' forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.

To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]

for a in ax:
    a.set_xticklabels([])
    a.set_yticklabels([])
    a.set_aspect('equal')

fig.subplots_adjust(wspace=0, hspace=0)

Here's the result:

How do I split an int into its digits?

A simple answer to this question can be:

  1. Read A Number "n" From The User.
  2. Using While Loop Make Sure Its Not Zero.
  3. Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
  4. Then Divide The Number "n" By 10..This Removes The Last Digit of Number "n" since in int decimal part is omitted.
  5. Display Out The Number.

I Think It Will Help. I Used Simple Code Like:

#include <iostream>
using namespace std;
int main()
{int n,r;

    cout<<"Enter Your Number:";
    cin>>n;


    while(n!=0)
    {
               r=n%10;
               n=n/10;

               cout<<r;
    }
    cout<<endl;

    system("PAUSE");
    return 0;
}

How to fix a collation conflict in a SQL Server query?

You can resolve the issue by forcing the collation used in a query to be a particular collation, e.g. SQL_Latin1_General_CP1_CI_AS or DATABASE_DEFAULT. For example:

SELECT MyColumn
FROM FirstTable a
INNER JOIN SecondTable b
ON a.MyID COLLATE SQL_Latin1_General_CP1_CI_AS = 
b.YourID COLLATE SQL_Latin1_General_CP1_CI_AS

In the above query, a.MyID and b.YourID would be columns with a text-based data type. Using COLLATE will force the query to ignore the default collation on the database and instead use the provided collation, in this case SQL_Latin1_General_CP1_CI_AS.

Basically what's going on here is that each database has its own collation which "provides sorting rules, case, and accent sensitivity properties for your data" (from http://technet.microsoft.com/en-us/library/ms143726.aspx) and applies to columns with textual data types, e.g. VARCHAR, CHAR, NVARCHAR, etc. When two databases have differing collations, you cannot compare text columns with an operator like equals (=) without addressing the conflict between the two disparate collations.

Not showing placeholder for input type="date" field

As of today (2016), I have successfully used those 2 snippets (plus they work great with Bootstrap4).

Input data on the left, placeholder on the left

input[type=date] {
  text-align: right;
}

input[type="date"]:before {
  color: lightgrey;
  content: attr(placeholder) !important;
  margin-right: 0.5em;
}

Placeholder disappear when clicking

input[type="date"]:before {
  color: lightgrey;
  content: attr(placeholder) !important;
  margin-right: 0.5em;
}
input[type="date"]:focus:before {
  content: '' !important;
}

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

I get the same error when using Gulp. The solution is to switch to Gulp version 3.9.1, both for the local version and the CLI version.

sudo npm install -g [email protected]

Run in the project's folder

npm install [email protected]

How do you find all subclasses of a given class in Java?

Add them to a static map inside (this.getClass().getName()) the parent classes constructor (or create a default one) but this will get updated in runtime. If lazy initialization is an option you can try this approach.

css - position div to bottom of containing div

.outside {
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Needs to be

.outside {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.

Convert or extract TTC font to TTF - how to?

You don't need any tool. Only a few clicks.

Windows 10 can handle ttc files with no problem.

You can double click the file and install it like any ttf. Then if you nead the individual ttf files you can go to C:\Windows\Fonts\Font Name and there you will findit. If you cant do this i suspect you have a corupt file.

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

I came up with this:

My scenario included more popovers on the same page, and hiding them just made them invisible and because of that, clicking on items behind the popover was not possible. The idea is to mark the specific popover-link as 'active' and then you can simply 'toggle' the active popover. Doing so will close the popover completely.

$('.popover-link').popover({ html : true, container: 'body' })

$('.popover-link').popover().on 'shown.bs.popover', ->
  $(this).addClass('toggled')

$('.popover-link').popover().on 'hidden.bs.popover', ->
  $(this).removeClass('toggled')

$("body").on "click", (e) ->
  $openedPopoverLink = $(".popover-link.toggled")
  if $openedPopoverLink.has(e.target).length == 0
    $openedPopoverLink.popover "toggle"
    $openedPopoverLink.removeClass "toggled"

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

Import Excel Data into PostgreSQL 9.3

A method that I use is to load the table into R as a data.frame, then use dbWriteTable to push it to PostgreSQL. These two steps are shown below.

Load Excel data into R

R's data.frame objects are database-like, where named columns have explicit types, such as text or numbers. There are several ways to get a spreadsheet into R, such as XLConnect. However, a really simple method is to select the range of the Excel table (including the header), copy it (i.e. CTRL+C), then in R use this command to get it from the clipboard:

d <- read.table("clipboard", header=TRUE, sep="\t", quote="\"", na.strings="", as.is=TRUE)

If you have RStudio, you can easily view the d object to make sure it is as expected.

Push it to PostgreSQL

Ensure you have RPostgreSQL installed from CRAN, then make a connection and send the data.frame to the database:

library(RPostgreSQL)
conn <- dbConnect(PostgreSQL(), dbname="mydb")

dbWriteTable(conn, "some_table_name", d)

Now some_table_name should appear in the database.

Some common clean-up steps can be done from pgAdmin or psql:

ALTER TABLE some_table_name RENAME "row.names" TO id;
ALTER TABLE some_table_name ALTER COLUMN id TYPE integer USING id::integer;
ALTER TABLE some_table_name ADD PRIMARY KEY (id);

"&" meaning after variable type

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

How to JSON decode array elements in JavaScript?

Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -

echo json_encode($iniData);

In Javascript, use the following :

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "ajaxCalls.php",
            data: "dataType=ini",
            success: function(msg)
            {
                var x = eval('(' + msg + ')');
                $('#allowed').html(x.allowed);              // these are the fields which you can now easily access..
                $('#completed').html(x.completed);
                $('#running').html(x.running);
                $('#expired').html(x.expired);
                $('#balance').html(x.balance);
            }
        });
    });
</script>

Is it possible to declare two variables of different types in a for loop?

See "Is there a way to define variables of two types in for loop?" for another way involving nesting multiple for loops. The advantage of the other way over Georg's "struct trick" is that it (1) allows you to have a mixture of static and non-static local variables and (2) it allows you to have non-copyable variables. The downside is that it is far less readable and may be less efficient.

Transparent ARGB hex value

BE AWARE

In HTML/CSS (browser code) the format is #RRGGBBAA with the alpha channel as last two hexadecimal digits.

GitLab git user password

My problem was that I had a DNS entry for gitlab.example.com to point to my load balancer. So when I tried command ssh [email protected] I was really connecting to the wrong machine.

I made an entry in my ~/.ssh/config file:

Host gitlab.example.com
    Hostname 192.168.1.50

That wasted a lot of time...

Enum Naming Convention - Plural

On the other thread C# naming convention for enum and matching property someone pointed out what I think is a very good idea:

"I know my suggestion goes against the .NET Naming conventions, but I personally prefix enums with 'E' and enum flags with 'F' (similar to how we prefix Interfaces with 'I')."

Multi-gradient shapes

Have you tried to overlay one gradient with a nearly-transparent opacity for the highlight on top of another image with an opaque opacity for the green gradient?

c# dictionary one key many values

Take a look at MultiValueDictionary from Microsoft.

Example Code:

MultiValueDictionary<string, string> Parameters = new MultiValueDictionary<string, string>();

Parameters.Add("Malik", "Ali");
Parameters.Add("Malik", "Hamza");
Parameters.Add("Malik", "Danish");

//Parameters["Malik"] now contains the values Ali, Hamza, and Danish

CS0234: Mvc does not exist in the System.Web namespace

I had this problem, but all the applications in IIS were broken when they had been working previously. None of the marked solutions helped me. The problem ended up being an extra copy of web.config had been introduced to my root directory. I removed that file and problem solved.

How do you delete an ActiveRecord object?

If you are using Rails 5 and above, the following solution will work.

#delete based on id
user_id = 50
User.find(id: user_id).delete_all

#delete based on condition
threshold_age = 20
User.where(age: threshold_age).delete_all

https://www.rubydoc.info/docs/rails/ActiveRecord%2FNullRelation:delete_all

How do I get ruby to print a full backtrace instead of a truncated one?

Almost everybody answered this. My version of printing any rails exception into logs would be:

begin
    some_statement
rescue => e
    puts "Exception Occurred #{e}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
    Rails.logger.error "Exception Occurred #{e}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
end

Passing arrays as parameters in bash

With a few tricks you can actually pass named parameters to functions, along with arrays.

The method I developed allows you to access parameters passed to a function like this:

testPassingParams() {

    @var hello
    l=4 @array anArrayWithFourElements
    l=2 @array anotherArrayWithTwo
    @var anotherSingle
    @reference table   # references only work in bash >=4.3
    @params anArrayOfVariedSize

    test "$hello" = "$1" && echo correct
    #
    test "${anArrayWithFourElements[0]}" = "$2" && echo correct
    test "${anArrayWithFourElements[1]}" = "$3" && echo correct
    test "${anArrayWithFourElements[2]}" = "$4" && echo correct
    # etc...
    #
    test "${anotherArrayWithTwo[0]}" = "$6" && echo correct
    test "${anotherArrayWithTwo[1]}" = "$7" && echo correct
    #
    test "$anotherSingle" = "$8" && echo correct
    #
    test "${table[test]}" = "works"
    table[inside]="adding a new value"
    #
    # I'm using * just in this example:
    test "${anArrayOfVariedSize[*]}" = "${*:10}" && echo correct
}

fourElements=( a1 a2 "a3 with spaces" a4 )
twoElements=( b1 b2 )
declare -A assocArray
assocArray[test]="works"

testPassingParams "first" "${fourElements[@]}" "${twoElements[@]}" "single with spaces" assocArray "and more... " "even more..."

test "${assocArray[inside]}" = "adding a new value"

In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1 (and others).

The code that makes this work is pretty light and works both in bash 3 and bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below was developed for that purpose.

Function.AssignParamLocally() {
    local commandWithArgs=( $1 )
    local command="${commandWithArgs[0]}"

    shift

    if [[ "$command" == "trap" || "$command" == "l="* || "$command" == "_type="* ]]
    then
        paramNo+=-1
        return 0
    fi

    if [[ "$command" != "local" ]]
    then
        assignNormalCodeStarted=true
    fi

    local varDeclaration="${commandWithArgs[1]}"
    if [[ $varDeclaration == '-n' ]]
    then
        varDeclaration="${commandWithArgs[2]}"
    fi
    local varName="${varDeclaration%%=*}"

    # var value is only important if making an object later on from it
    local varValue="${varDeclaration#*=}"

    if [[ ! -z $assignVarType ]]
    then
        local previousParamNo=$(expr $paramNo - 1)

        if [[ "$assignVarType" == "array" ]]
        then
            # passing array:
            execute="$assignVarName=( \"\${@:$previousParamNo:$assignArrLength}\" )"
            eval "$execute"
            paramNo+=$(expr $assignArrLength - 1)

            unset assignArrLength
        elif [[ "$assignVarType" == "params" ]]
        then
            execute="$assignVarName=( \"\${@:$previousParamNo}\" )"
            eval "$execute"
        elif [[ "$assignVarType" == "reference" ]]
        then
            execute="$assignVarName=\"\$$previousParamNo\""
            eval "$execute"
        elif [[ ! -z "${!previousParamNo}" ]]
        then
            execute="$assignVarName=\"\$$previousParamNo\""
            eval "$execute"
        fi
    fi

    assignVarType="$__capture_type"
    assignVarName="$varName"
    assignArrLength="$__capture_arrLength"
}

Function.CaptureParams() {
    __capture_type="$_type"
    __capture_arrLength="$l"
}

alias @trapAssign='Function.CaptureParams; trap "declare -i \"paramNo+=1\"; Function.AssignParamLocally \"\$BASH_COMMAND\" \"\$@\"; [[ \$assignNormalCodeStarted = true ]] && trap - DEBUG && unset assignVarType && unset assignVarName && unset assignNormalCodeStarted && unset paramNo" DEBUG; '
alias @param='@trapAssign local'
alias @reference='_type=reference @trapAssign local -n'
alias @var='_type=var @param'
alias @params='_type=params @param'
alias @array='_type=array @param'

Fixing Segmentation faults in C++

  1. Compile your application with -g, then you'll have debug symbols in the binary file.

  2. Use gdb to open the gdb console.

  3. Use file and pass it your application's binary file in the console.

  4. Use run and pass in any arguments your application needs to start.

  5. Do something to cause a Segmentation Fault.

  6. Type bt in the gdb console to get a stack trace of the Segmentation Fault.

fill an array in C#

You could try something like this:

I have initialzed the array for having value 5, you could put your number similarly.

int[] arr = new int[10]; // your initial array

arr = arr.Select(i => 5).ToArray(); // array initialized to 5.

Why do we assign a parent reference to the child object in Java?

First, a clarification of terminology: we are assigning a Child object to a variable of type Parent. Parent is a reference to an object that happens to be a subtype of Parent, a Child.

It is only useful in a more complicated example. Imagine you add getEmployeeDetails to the class Parent:

public String getEmployeeDetails() {
    return "Name: " + name;
}

We could override that method in Child to provide more details:

@Override
public String getEmployeeDetails() {
    return "Name: " + name + " Salary: " + salary;
}

Now you can write one line of code that gets whatever details are available, whether the object is a Parent or Child:

parent.getEmployeeDetails();

The following code:

Parent parent = new Parent();
parent.name = 1;
Child child = new Child();
child.name = 2;
child.salary = 2000;
Parent[] employees = new Parent[] { parent, child };
for (Parent employee : employees) {
    employee.getEmployeeDetails();
}

Will result in the output:

Name: 1
Name: 2 Salary: 2000

We used a Child as a Parent. It had specialized behavior unique to the Child class, but when we called getEmployeeDetails() we could ignore the difference and focus on how Parent and Child are similar. This is called subtype polymorphism.

Your updated question asks why Child.salary is not accessible when the Childobject is stored in a Parent reference. The answer is the intersection of "polymorphism" and "static typing". Because Java is statically typed at compile time you get certain guarantees from the compiler but you are forced to follow rules in exchange or the code won't compile. Here, the relevant guarantee is that every instance of a subtype (e.g. Child) can be used as an instance of its supertype (e.g. Parent). For instance, you are guaranteed that when you access employee.getEmployeeDetails or employee.name the method or field is defined on any non-null object that could be assigned to a variable employee of type Parent. To make this guarantee, the compiler considers only that static type (basically, the type of the variable reference, Parent) when deciding what you can access. So you cannot access any members that are defined on the runtime type of the object, Child.

When you truly want to use a Child as a Parent this is an easy restriction to live with and your code will be usable for Parent and all its subtypes. When that is not acceptable, make the type of the reference Child.

Python: Find in list

Finding the first occurrence

There's a recipe for that in itertools:

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

For example, the following code finds the first odd number in a list:

>>> first_true([2,3,4,5], None, lambda x: x%2==1)
3  

FontAwesome icons not showing. Why?

You need a font importer.| try

<style> 
@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css););
</style>

What's the difference between a mock & stub?

This slide explain the main differences very good.

enter image description here

*From CSE 403 Lecture 16 , University of Washington (slide created by "Marty Stepp")

Concatenation of strings in Lua

Strings can be joined together using the concatenation operator ".."

this is the same for variables I think

Jenkins fails when running "service start jenkins"

rm -rf /var/log/jenkins too big the log

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

How do you change the character encoding of a postgres database?

# dump into file
pg_dump myDB > /tmp/myDB.sql

# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'

# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql

# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";' 
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'

# see the result
psql myDB -c "SHOW LC_COLLATE"   

Delete all rows in a table based on another table

This will delete all rows in Table1 that match the criteria:

DELETE Table1 
FROM Table2 
WHERE Table1.JoinColumn = Table2.JoinColumn And Table1.SomeStuff = 'SomeStuff'

What is the purpose of Node.js module.exports and how do you use it?

When dividing your program code over multiple files, module.exports is used to publish variables and functions to the consumer of a module. The require() call in your source file is replaced with corresponding module.exports loaded from the module.

Remember when writing modules

  • Module loads are cached, only initial call evaluates JavaScript.
  • It's possible to use local variables and functions inside a module, not everything needs to be exported.
  • The module.exports object is also available as exports shorthand. But when returning a sole function, always use module.exports.

module exports diagram

According to: "Modules Part 2 - Writing modules".

Disable and later enable all table indexes in Oracle

From here: http://forums.oracle.com/forums/thread.jspa?messageID=2354075

alter session set skip_unusable_indexes = true;

alter index your_index unusable;

do import...

alter index your_index rebuild [online];

How to find indices of all occurrences of one string in another in JavaScript?

Check this solution which will able to find same character string too, let me know if something missing or not right.

_x000D_
_x000D_
function indexes(source, find) {_x000D_
    if (!source) {_x000D_
      return [];_x000D_
    }_x000D_
    if (!find) {_x000D_
        return source.split('').map(function(_, i) { return i; });_x000D_
    }_x000D_
    source = source.toLowerCase();_x000D_
    find = find.toLowerCase();_x000D_
    var result = [];_x000D_
    var i = 0;_x000D_
    while(i < source.length) {_x000D_
      if (source.substring(i, i + find.length) == find)_x000D_
        result.push(i++);_x000D_
      else_x000D_
        i++_x000D_
    }_x000D_
    return result;_x000D_
  }_x000D_
  console.log(indexes('aaaaaaaa', 'aaaaaa'))_x000D_
  console.log(indexes('aeeaaaaadjfhfnaaaaadjddjaa', 'aaaa'))_x000D_
  console.log(indexes('wordgoodwordgoodgoodbestword', 'wordgood'))_x000D_
  console.log(indexes('I learned to play the Ukulele in Lebanon.', 'le'))
_x000D_
_x000D_
_x000D_

How can I use a for each loop on an array?

Element needs to be a variant, so you can't declare it as a string. Your function should accept a variant if it is a string though as long as you pass it ByVal.

Public Sub example()
    Dim sArray(4) As string
    Dim element As variant

    For Each element In sArray
        do_something (element)
    Next element
End Sub


Sub do_something(ByVal e As String)

End Sub

The other option is to convert the variant to a string before passing it.

  do_something CStr(element)

IntelliJ shortcut to show a popup of methods in a class that can be searched

If you are running on Linux (I tested in Ubuntu 10.04), the shortcut is Ctrl + F12 (same of Windows)

How to validate an email address using a regular expression?

I know this question is about RegEx, but guessing that 90% of all developers reading these solutions are trying to validate an E-Mail address in an HTML form displayed in a browser.

If this is the case, I'd suggest checking out the new HTML5 <input type="email"> form element:

HTML5:

 <input type="email" required />

CSS3:

 input:required {
      background-color: rgba(255,0,0,0.2);
 }

 input:focus:invalid { 
     box-shadow: 0 0 1em red;
     border-color: red;
 }

 input:focus:valid { 
     box-shadow: 0 0 1em green;
     border-color: green;
 }

http://jsfiddle.net/mYRe7/1

This has a couple of advantages:

  1. Automatic validation, no custom solution needed: simple and easy to implement
  2. No JavaScript, no problems if JS has been disabled
  3. No server has to calculate anything for that
  4. The user has an immediate feedback
  5. Old browser should automatically fallback to input type "text"
  6. Mobile browsers can display a specialized keyboard (@-Keyboard)
  7. Form validation feedback is very easy with CSS3

The apparent downside might be missing validation for old browsers, but that'll change over time. I'd prefer this over any of these insane RegEx masterpieces.

also see:

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I had the same problem with a different and simple solution.

Problem

I installed PHP 5.6 following the accepted answer to this question on Ask Ubuntu. After using Virtualmin to switch a particular virtual server from PHP 5.5 to PHP 5.6, I received a 500 Internal Server Error and had the same entries in the apache error log:

[Tue Jul 03 16:15:22.131051 2018] [fcgid:warn] [pid 24262] (104)Connection reset by peer: [client 10.20.30.40:23700] mod_fcgid: error reading data from FastCGI server
[Tue Jul 03 16:15:22.131101 2018] [core:error] [pid 24262] [client 10.20.30.40:23700] End of script output before headers: index.php

Cause

Simple: I didn't install the php5.6-cgi packet.

Fix

Installing the packet and reloading apache solved the problem:

  • sudo apt-get install php5.6-cgi if you are using PHP 5.6

  • sudo apt-get install php5-cgi if you are using a different PHP 5 version

  • sudo apt-get install php7.0-cgi if you are using PHP 7

Then use service apache2 reload to apply the configuration.

Python Requests library redirect new url

You are looking for the request history.

The response.history attribute is a list of responses that led to the final URL, which can be found in response.url.

response = requests.get(someurl)
if response.history:
    print("Request was redirected")
    for resp in response.history:
        print(resp.status_code, resp.url)
    print("Final destination:")
    print(response.status_code, response.url)
else:
    print("Request was not redirected")

Demo:

>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
...     print(resp.status_code, resp.url)
... 
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                String header = dataGridView1.Columns[i].HeaderText;
                //String cellText = row.Cells[i].Text;
                DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column 
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
                int colWidth = column.Width; // store columns width after auto resize           
                colWidth += 50; // add 30 pixels to what 'colWidth' already is
                this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
            }
        }

AngularJS - Create a directive that uses ng-model

This is a little late answer, but I found this awesome post about NgModelController, which I think is exactly what you were looking for.

TL;DR - you can use require: 'ngModel' and then add NgModelController to your linking function:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}

This way, no hacks needed - you are using Angular's built-in ng-model

how to implement Interfaces in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

class Interface
{
public:
    Interface(){}
    virtual ~Interface(){}
    virtual void method1() = 0;    // "= 0" part makes this method pure virtual, and
                                   // also makes this class abstract.
    virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
    int myMember;

public:
    Concrete(){}
    ~Concrete(){}
    void method1();
    void method2();
};

// Provide implementation for the first method
void Concrete::method1()
{
    // Your implementation
}

// Provide implementation for the second method
void Concrete::method2()
{
    // Your implementation
}

int main(void)
{
    Interface *f = new Concrete();

    f->method1();
    f->method2();

    delete f;

    return 0;
}

MySQL combine two columns and add into a new column

Create the column:

ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50);

Update the current values:

UPDATE yourtable SET combined = CONCAT(zipcode, ' - ', city, ', ', state);

Update all future values automatically:

CREATE TRIGGER insert_trigger
BEFORE INSERT ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);

CREATE TRIGGER update_trigger
BEFORE UPDATE ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);

How do I detect IE 8 with jQuery?

document.documentMode is undefined if the browser is not IE8,

it returns 8 for standards mode and 7 for 'compatable to IE7'

If it is running as IE7 there are a lot of css and dom features that won't be supported.

IOError: [Errno 32] Broken pipe: Python

The top answer (if e.errno == errno.EPIPE:) here didn't really work for me. I got:

AttributeError: 'BrokenPipeError' object has no attribute 'EPIPE'

However, this ought to work if all you care about is ignoring broken pipes on specific writes. I think it's safer than trapping SIGPIPE:

try:
    # writing, flushing, whatever goes here
except BrokenPipeError:
    exit( 0 )

You obviously have to make a decision as to whether your code is really, truly done if you hit the broken pipe, but for most purposes I think that's usually going to be true. (Don't forget to close file handles, etc.)

How to convert a date String to a Date or Calendar object?

The DateFormat class has a parse method.

See DateFormat for more information.

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

wp_nav_menu change sub-menu class name?

You don't need to extend the Walker. This will do:

function overrideSubmenuClasses( $classes ) {
    $classes[] = 'myclass1';
    $classes[] = 'myclass2';

    return $classes;
}
add_action('nav_menu_submenu_css_class', 'overrideSubmenuClasses');

Declare Variable for a Query String

It's possible, but it requires using dynamic SQL.
I recommend reading The curse and blessings of dynamic SQL before continuing...

DECLARE @theDate varchar(60)
SET @theDate = '''2010-01-01'' AND ''2010-08-31 23:59:59'''

DECLARE @SQL VARCHAR(MAX)  
SET @SQL = 'SELECT AdministratorCode, 
                   SUM(Total) as theTotal, 
                   SUM(WOD.Quantity) as theQty, 
                   AVG(Total) as avgTotal, 
                  (SELECT SUM(tblWOD.Amount)
                     FROM tblWOD
                     JOIN tblWO on tblWOD.OrderID = tblWO.ID
                    WHERE tblWO.Approved = ''1''
                      AND tblWO.AdministratorCode = tblWO.AdministratorCode
                      AND tblWO.OrderDate BETWEEN '+ @theDate +')'

EXEC(@SQL)

Dynamic SQL is just a SQL statement, composed as a string before being executed. So the usual string concatenation occurs. Dynamic SQL is required whenever you want to do something in SQL syntax that isn't allowed, like:

  • a single parameter to represent comma separated list of values for an IN clause
  • a variable to represent both value and SQL syntax (IE: the example you provided)

EXEC sp_executesql allows you to use bind/preparedstatement parameters so you don't have to concern yourself with escaping single quotes/etc for SQL injection attacks.

How to remove the default arrow icon from a dropdown list (select element)?

Try this it works for me,

_x000D_
_x000D_
<style>_x000D_
    select{_x000D_
        border: 0 !important;  /*Removes border*/_x000D_
        -webkit-appearance: none;_x000D_
        -moz-appearance: none;_x000D_
        appearance: none;_x000D_
        text-overflow:'';_x000D_
        text-indent: 0.01px; /* Removes default arrow from firefox*/_x000D_
        text-overflow: "";  /*Removes default arrow from firefox*/_x000D_
    }_x000D_
    select::-ms-expand {_x000D_
        display: none;_x000D_
    }_x000D_
    .select-wrapper_x000D_
    {_x000D_
        padding-left:0px;_x000D_
        overflow:hidden;_x000D_
    }_x000D_
</style>_x000D_
    _x000D_
<div class="select-wrapper">_x000D_
     <select> ... </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can not hide but using overflow hidden you can actually make it disappear.

Rails has_many with alias name

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

How to get JavaScript variable value in PHP

You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.

Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.

If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.

<script type="text/javascript>
    var foo = <?php echo json_encode($somePhpVar); ?>
</script>

Using Tempdata in ASP.NET MVC - Best practice

TempData is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.

To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.

Hope this helps.

How to convert a number to string and vice versa in C++

Update for C++11

As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).

string to numeric

float              stof(const string& str, size_t *idx = 0);
double             stod(const string& str, size_t *idx = 0);
long double        stold(const string& str, size_t *idx = 0);
int                stoi(const string& str, size_t *idx = 0, int base = 10);
long               stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long      stoul(const string& str, size_t *idx = 0, int base = 10);
long long          stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument or std::out_of_range).

If conversion succeeded and idx is not 0, idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.

Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10 until z=35). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.

Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.

numeric to string

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.

As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.

There are also similar functions defined that are named to_wstring, these will return a std::wstring.

java: run a function after a specific number of seconds

new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {
                // your code here
            }
        }, 
        5000 
);

EDIT:

javadoc says:

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.

Format ints into string of hex

Example with some beautifying, similar to the sep option available in python 3.8

def prettyhex(nums, sep=''):
    return sep.join(f'{a:02x}' for a in nums)

numbers = [0, 1, 2, 3, 127, 200, 255]
print(prettyhex(numbers,'-'))

output

00-01-02-03-7f-c8-ff

Align printf output in Java

A simple solution that springs to mind is to have a String block of spaces:

String indent = "                  "; // 20 spaces.

When printing out a string, compute the actual indent and add it to the end:

String output = "Newspaper";
output += indent.substring(0, indent.length - output.length);

This will mediate the number of spaces to the string, and put them all in the same column.

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this:

Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine
End Sub
Sub OtherSubRoutine()
    MsgBox wbA.Name, vbInformation
End Sub

Alternately, you can pass variables between subroutines:

Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
    MsgBox wb1.Name, vbInformation
    MsgBox wb2.Name, vbInformation
End Sub

Or use Functions to return values:

Sub MySubroutine()
    Dim i as Long
    i = MyFunction()
    MsgBox i
End Sub
Function MyFunction()
    'Lots of code that does something
    Dim x As Integer, y as Double
    For x = 1 to 1000
        'Lots of code that does something
    Next
    MyFunction = y
End Function

In the second method, within the scope of OtherSubRoutine you refer to them by their parameter names wb1 and wb2. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.

A Note About User Forms

Personally I would recommend keeping Option Explicit in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn when you meant lCount etc., among other reasons).

If you're using Option Explicit (which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public scoped variables, as these are not "public" in the same sense. For instance, i is undefined, though it's Public in the scope of UserForm1:

enter image description here

You can refer to it as UserForm1.i to avoid the compile error, or since forms are New-able, you can create a variable object to contain reference to your form, and refer to it that way:

enter image description here

NB: In the above screenshots x is declared Public x as Long in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x to avoid ambiguity and possible shadowing in case you re-use variable names...

How to securely save username/password (local)?

If you are just going to verify/validate the entered user name and password, use the Rfc2898DerivedBytes class (also known as Password Based Key Derivation Function 2 or PBKDF2). This is more secure than using encryption like Triple DES or AES because there is no practical way to go from the result of RFC2898DerivedBytes back to the password. You can only go from a password to the result. See Is it ok to use SHA1 hash of password as a salt when deriving encryption key and IV from password string? for an example and discussion for .Net or String encrypt / decrypt with password c# Metro Style for WinRT/Metro.

If you are storing the password for reuse, such as supplying it to a third party, use the Windows Data Protection API (DPAPI). This uses operating system generated and protected keys and the Triple DES encryption algorithm to encrypt and decrypt information. This means your application does not have to worry about generating and protecting the encryption keys, a major concern when using cryptography.

In C#, use the System.Security.Cryptography.ProtectedData class. For example, to encrypt a piece of data, use ProtectedData.Protect():

// Data to protect. Convert a string to a byte[] using Encoding.UTF8.GetBytes().
byte[] plaintext; 

// Generate additional entropy (will be used as the Initialization vector)
byte[] entropy = new byte[20];
using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
    rng.GetBytes(entropy);
}

byte[] ciphertext = ProtectedData.Protect(plaintext, entropy,
    DataProtectionScope.CurrentUser);

Store the entropy and ciphertext securely, such as in a file or registry key with permissions set so only the current user can read it. To get access to the original data, use ProtectedData.Unprotect():

byte[] plaintext= ProtectedData.Unprotect(ciphertext, entropy,
    DataProtectionScope.CurrentUser);

Note that there are additional security considerations. For example, avoid storing secrets like passwords as a string. Strings are immutable, being they cannot be notified in memory so someone looking at the application's memory or a memory dump may see the password. Use SecureString or a byte[] instead and remember to dispose or zero them as soon as the password is no longer needed.

How to [recursively] Zip a directory in PHP?

Here is a simple function that can compress any file or directory recursively, only needs the zip extension to be loaded.

function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

Call it like this:

Zip('/folder/to/compress/', './compressed.zip');

How to completely uninstall Visual Studio 2010?

Update April 2016 - for VS2013+

Microsoft started to address the issue in late 2015 by releasing VisualStudioUninstaller.

They abandoned the solution for a while; however work has begun again again as of April 2016.

There has finally been an official release for this uninstaller in April 2016 which is described as being "designed to cleanup/scorch all Preview/RC/RTM releases of Visual Studio 2013, Visual Studio 2015 and Visual Studio vNext".


Original Answer - for VS2010, VS2012

Note that the following two solutions still leave traces (such as registry files) and can't really be considered a 'clean' uninstall (see the final section of the answer for a completely clean solution).


Solution 1 - for: VS 2010

There's an uninstaller provided by Microsoft called the Visual Studio 2010 Uninstall Utility. It comes with three options:

  1. Default (VS2010_Uninstall-RTM.ENU.exe)
  2. Full (VS2010_Uninstall-RTM.ENU.exe /full)
  3. Complete (VS2010_Uninstall-RTM.ENU.exe /full /netfx)

The above link explains the uninstaller in greater detail - I recommend reading the comments on the article before using it as some have noted problems (and workarounds) when service packs are installed. Afterwards, use something like CCleaner to remove the leftover registry files.

Here is the link to the download page of the VS2010 UU.


Solution 2 - for: VS 2010, VS 2012

Microsoft provide an uninstall /force feature that removes most remnants of either VS2010 or VS2012 from your computer.

MSDN: How to uninstall Visual Studio 2010/2012. From the link:

Warning: Running this command may remove some packages even if they are still in use like those listed in Optional shared packages.

  1. Download the setup application you used to originally install Visual Studio 2012. If you installed from media, please insert that media.
  2. Open a command prompt. Click Run on the Start menu (Start + R). Type cmd and press OK (Enter).
  3. Type in the full path to the setup application and pass the following command line switches: /uninstall /force Example: D:\vs_ultimate.exe /uninstall /force
  4. Click the Uninstall button and follow the prompts.

Afterwards, use something like CCleaner to remove the leftover registry files.


A completely clean uninstall?

Sadly, the only (current) way to achieve this is to follow dnLL's advice in their answer and perform a complete operating system reinstall. Then, in future, you could use Visual Studio inside a Virtual Machine instead and not have to worry about these issues again.

Express.js Response Timeout

There is already a Connect Middleware for Timeout support:

var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4

app.use(timeout(120000));
app.use(haltOnTimedout);

function haltOnTimedout(req, res, next){
  if (!req.timedout) next();
}

If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.

Side Note:

Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:

The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.

How do I change the number of open files limit in Linux?

You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit

Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.

set rlim_fd_max = 166384
set rlim_fd_cur = 8192

On OS X, this same data must be set in /etc/sysctl.conf.

kern.maxfilesperproc=166384
kern.maxfiles=8192

Under Linux, these settings are often in /etc/security/limits.conf.

There are two kinds of limits:

  • soft limits are simply the currently enforced limits
  • hard limits mark the maximum value which cannot be exceeded by setting a soft limit

Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.

There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

change image captcha refresh

html:

 <img id="captcha_img" src="http://localhost/captcha.php" /> 

jquery:

$("#captcha_img").click(function()
    {
        var capt_rand=Math.floor((Math.random() * 9999) + 1);
        $("#captcha_img").attr("src","http://localhost/captcha.php?" + capt_rand);
    });

How to word wrap text in HTML?

Example from CSS Tricks:

div {
    -ms-word-break: break-all;

    /* Be VERY careful with this, breaks normal words wh_erever */
    word-break: break-all;

    /* Non standard for webkit */
    word-break: break-word;

    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    hyphens: auto;
}

More examples here.

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

This can also be caused if you include bootstrap.js before jquery.js.

Others might have the same problem I did.

Include jQuery before bootstrap.

jQuery & CSS - Remove/Add display:none

To hide the div

$('.news').hide();

or

$('.news').css('display','none');

and to show the div:

$('.news').show();

or

$('.news').css('display','block');

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

You can use it like this, I hope you wont get outdated message now.

  <td valign="top" style="white-space:nowrap" width="237">

As pointed by @ThiefMaster it is recommended to put width and valign to CSS (note: CSS calls it vertical-align).

1)

<td style="white-space:nowrap; width:237px; vertical-align:top;">

2) We can make a CSS class like this, it is more elegant way

In style section

.td-some-name
{
  white-space:nowrap;
  width:237px;
  vertical-align:top;
}

In HTML section

<td class="td-some-name">

Token based authentication in Web API without any user interface

I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.

You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.

Here's some client side C# code to get a token:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //string token = GetToken("https://localhost:<port>/", userName, password);

    static string GetToken(string url, string userName, string password) {
        var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
        var content = new FormUrlEncodedContent(pairs);
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            var response = client.PostAsync(url + "Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

In order to use the token add it to the header of the request:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //var result = CallApi("https://localhost:<port>/something", token);

    static string CallApi(string url, string token) {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            if (!string.IsNullOrWhiteSpace(token)) {
                var t = JsonConvert.DeserializeObject<Token>(token);

                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
            }
            var response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

Where Token is:

//using Newtonsoft.Json;

class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

Now for the server side:

In Startup.Auth.cs

        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // https
            AllowInsecureHttp = false
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);

And in ApplicationOAuthProvider.cs the code that actually grants or denies access:

//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public ApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await userManager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
        var properties = new AuthenticationProperties(propertyDictionary);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        // Token is validated.
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
            context.Validated();

        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == _publicClientId)
        {
            var expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                context.Validated();
        }
        return Task.FromResult<object>(null);
    }

}

As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.

Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.

You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

I had such problem. In my case problem was in data - my column 'information' contained 1 unique value and it caused error

UPDATE: to correct work 'pivot' pairs (id_user,information) cannot have duplicates

It works:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phon','phon','phone','phone1','phone','phone1','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

it doesn't work:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phone','phone','phone','phone','phone','phone','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

source: https://stackoverflow.com/a/37021196/6088984

Removing items from a list

//first find out the removed ones

List removedList = new ArrayList();
for(Object a: list){
    if(a.getXXX().equalsIgnoreCase("AAA")){
        logger.info("this is AAA........should be removed from the list ");
        removedList.add(a);

    }
}

list.removeAll(removedList);

How do I limit the number of rows returned by an Oracle query after ordering?

I did some performance testing for the following approaches:

Asktom

select * from (
  select a.*, ROWNUM rnum from (
    <select statement with order by clause>
  ) a where rownum <= MAX_ROW
) where rnum >= MIN_ROW

Analytical

select * from (
  <select statement with order by clause>
) where myrow between MIN_ROW and MAX_ROW

Short Alternative

select * from (
  select statement, rownum as RN with order by clause
) where a.rn >= MIN_ROW and a.rn <= MAX_ROW

Results

Table had 10 million records, sort was on an unindexed datetime row:

  • Explain plan showed same value for all three selects (323168)
  • But the winner is AskTom (with analytic following close behind)

Selecting first 10 rows took:

  • AskTom: 28-30 seconds
  • Analytical: 33-37 seconds
  • Short alternative: 110-140 seconds

Selecting rows between 100,000 and 100,010:

  • AskTom: 60 seconds
  • Analytical: 100 seconds

Selecting rows between 9,000,000 and 9,000,010:

  • AskTom: 130 seconds
  • Analytical: 150 seconds

How do I set the selenium webdriver get timeout?

I find that the timeout calls are not reliable enough in real life, particularly for internet explorer , however the following solutions may be of help:

  1. You can timeout the complete test by using @Test(timeout=10000) in the junit test that you are running the selenium process from. This will free up the main thread for executing the other tests, instead of blocking up the whole show. However even this does not work at times.

  2. Anyway by timing out you do not intend to salvage the test case, because timing out even a single operation might leave the entire test sequence in inconsistent state. You might just want to proceed with the other testcases without blocking (or perhaps retry the same test again). In such a case a fool-proof method would be to write a poller that polls processes of Webdriver (eg. IEDriverServer.exe, Phantomjs.exe) running for more than say 10 min and kill them. An example could be found at Automatically identify (and kill) processes with long processing time

How to publish a website made by Node.js to Github Pages?

I was able to set up github actions to automatically commit the results of a node build command (yarn build in my case but it should work with npm too) to the gh-pages branch whenever a new commit is pushed to master.

While not completely ideal as i'd like to avoid committing the built files, it seems like this is currently the only way to publish to github pages.

I based my workflow off of this guide for a different react library, and had to make the following changes to get it to work for me:

  • updated the "setup node" step to use the version found here since the one from the sample i was basing it off of was throwing errors because it could not find the correct action.
  • remove the line containing yarn export because that command does not exist and it doesn't seem to add anything helpful (you may also want to change the build line above it to suit your needs)
  • I also added an env directive to the yarn build step so that I can include the SHA hash of the commit that generated the build inside my app, but this is optional

Here is my full github action:

name: github pages

on:
    push:
        branches:
        - master

jobs:
    deploy:
        runs-on: ubuntu-18.04
        steps:
        - uses: actions/checkout@v2

        - name: Setup Node
            uses: actions/setup-node@v2-beta
            with:
            node-version: '12'

        - name: Get yarn cache
            id: yarn-cache
            run: echo "::set-output name=dir::$(yarn cache dir)"

        - name: Cache dependencies
            uses: actions/cache@v2
            with:
            path: ${{ steps.yarn-cache.outputs.dir }}
            key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
            restore-keys: |
                ${{ runner.os }}-yarn-
        - run: yarn install --frozen-lockfile
        - run: yarn build
            env:
            REACT_APP_GIT_SHA: ${{ github.SHA }}

        - name: Deploy
            uses: peaceiris/actions-gh-pages@v3
            with:
            github_token: ${{ secrets.GITHUB_TOKEN }}
            publish_dir: ./build

Alternative solution

The docs for next.js also provides instructions for setting up with Vercel which appears to be a hosting service for node.js apps similar to github pages. I have not tried this though and so cannot speak to how well it works.

Spring cannot find bean xml configuration file when it does exist

Try this:

new ClassPathXmlApplicationContext("file:src/main/resources/beans.xml");

file: preffix point to file system resources, not classpath.

file path can be relative or system (/home/user/Work/src...)

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

initialize a vector to zeros C++/C++11

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);

Extracting the top 5 maximum values in excel

Given a data setup like this:

Top 5 by criteria

The formula in cell D2 and copied down is:

=INDEX($B$2:$B$28,MATCH(1,INDEX(($A$2:$A$28=LARGE($A$2:$A$28,ROWS(D$1:D1)))*(COUNTIF(D$1:D1,$B$2:$B$28)=0),),0))

This formula will work even if there are tied OPS scores among players.

How do I replace text in a selection?

As @JOPLOmacedo stated, ctrl + F is what you need, but if you can't use that shortcut you can check in menu:

  • Find -> Find..

    and there you have it.
    You can also set a custom keybind for Find going in:

  • Preferences -> Key Bindings - User

    As your request for the selection only request, there is a button right next to the search field where you can opt-in for "in selection".

  • How to determine if a String has non-alphanumeric characters?

    string.matches("^\\W*$"); should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$"); does match whitespace as well.

    Replace words in a string - Ruby

    sentence.sub! 'Robert', 'Joe'
    

    Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

    How to replace all instances?

    The above replaces only the first instance of "Robert".

    To replace all instances use gsub/gsub! (ie. "global substitution"):

    sentence.gsub! 'Robert', 'Joe'
    

    The above will replace all instances of Robert with Joe.

    What is the difference between 'typedef' and 'using' in C++11?

    Both keywords are equivalent, but there are a few caveats. One is that declaring a function pointer with using T = int (*)(int, int); is clearer than with typedef int (*T)(int, int);. Second is that template alias form is not possible with typedef. Third is that exposing C API would require typedef in public headers.

    How to create the pom.xml for a Java project with Eclipse

    Right click on Project -> Add FrameWork Support -> Maven

    IN Clause with NULL or IS NULL

    SELECT *
    FROM tbl_name
    WHERE coalesce(id_field,'unik_null_value') 
    IN ('value1', 'value2', 'value3', 'unik_null_value')
    

    So that you eliminate the null from the check. Given a null value in id_field, the coalesce function would instead of null return 'unik_null_value', and by adding 'unik_null_value to the IN-list, the query would return posts where id_field is value1-3 or null.

    Plot inline or a separate window using Matplotlib in Spyder IDE

    Go to Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"

    Reset the kernel at the console, and the plot will appear in a separate window

    How to convert an array of strings to an array of floats in numpy?

    Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings)) (or equivalently, use a list comprehension). (In Python 3, you'll need to call list on the map return value if you use map, since map returns an iterator now.)

    However, if it's already a numpy array of strings, there's a better way. Use astype().

    import numpy as np
    x = np.array(['1.1', '2.2', '3.3'])
    y = x.astype(np.float)
    

    What do I do when my program crashes with exception 0xc0000005 at address 0?

    Exception code 0xc0000005 is an Access Violation. An AV at fault offset 0x00000000 means that something in your service's code is accessing a nil pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.

    Calendar date to yyyy-MM-dd format in java

    A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.

    When you use something like System.out.println(date), Java uses Date.toString() to print the contents.

    The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).

    Java 8+

    LocalDateTime ldt = LocalDateTime.now().plusDays(1);
    DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
    System.out.println(ldt);
    // Output "2018-05-12T17:21:53.658"
    
    String formatter = formmat1.format(ldt);
    System.out.println(formatter);
    // 2018-05-12
    

    Prior to Java 8

    You should be making use of the ThreeTen Backport

    The following is maintained for historical purposes (as the original answer)

    What you can do, is format the date.

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 1);
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(cal.getTime());
    // Output "Wed Sep 26 14:23:28 EST 2012"
    
    String formatted = format1.format(cal.getTime());
    System.out.println(formatted);
    // Output "2012-09-26"
    
    System.out.println(format1.parse(formatted));
    // Output "Wed Sep 26 00:00:00 EST 2012"
    

    These are actually the same date, represented differently.

    Use of alloc init instead of new

    One Short Answere is:

    1. Both are same. But
    2. 'new' only works with the basic 'init' initializer, and will not work with other initializers (eg initWithString:).

    C#: New line and tab characters in strings

    Use:

    sb.AppendLine();
    sb.Append("\t");
    

    for better portability. Environment.NewLine may not necessarily be \n; Windows uses \r\n, for example.

    Should import statements always be at the top of a module?

    It's a tradeoff, that only the programmer can decide to make.

    Case 1 saves some memory and startup time by not importing the datetime module (and doing whatever initialization it might require) until needed. Note that doing the import 'only when called' also means doing it 'every time when called', so each call after the first one is still incurring the additional overhead of doing the import.

    Case 2 save some execution time and latency by importing datetime beforehand so that not_often_called() will return more quickly when it is called, and also by not incurring the overhead of an import on every call.

    Besides efficiency, it's easier to see module dependencies up front if the import statements are ... up front. Hiding them down in the code can make it more difficult to easily find what modules something depends on.

    Personally I generally follow the PEP except for things like unit tests and such that I don't want always loaded because I know they aren't going to be used except for test code.

    How to detect query which holds the lock in Postgres?

    Since 9.6 this is a lot easier as it introduced the function pg_blocking_pids() to find the sessions that are blocking another session.

    So you can use something like this:

    select pid, 
           usename, 
           pg_blocking_pids(pid) as blocked_by, 
           query as blocked_query
    from pg_stat_activity
    where cardinality(pg_blocking_pids(pid)) > 0;
    

    .Net picking wrong referenced assembly version

    Try:

    • cleaning temporary project files
    • cleaning build and obj files
    • cleaning old versions installed at C:\Users\USERNAME\.nuget\packages\

    That worked for me.

    How do I declare a global variable in VBA?

    A good way to create Public/Global variables is to treat the Form like a class object and declare properties and use Public Property Get [variable] to access property/method. Also you might need to reference or pass a Reference to the instantiated Form module. You will get errors if you call methods to forms/reports that are closed.
    Example: pass Me.Form.Module.Parent into sub/function not inside form.

    Option Compare Database 
    Option Explicit
    ''***********************************''
    ' Name: Date: Created Date Author: Name 
    ' Current Version: 1.0
    ' Called by: 
    ''***********************************''
    ' Notes: Explain Who what when why... 
    ' This code Example requires properties to be filled in 
    ''***********************************''
    ' Global Variables
    Public GlobalData As Variant
    ''***********************************''
    ' Private Variables
    Private ObjectReference As Object
    Private ExampleVariable As Variant
    Private ExampleData As Variant
    ''***********************************''
    ' Public properties
    Public Property Get ObjectVariable() As Object
       Set ObjectVariable = ObjectReference
    End Property 
    Public Property Get Variable1() As Variant 
      'Recommend using variants to avoid data errors
      Variable1 = ExampleVariable
    End property
    ''***********************************''
    ' Public Functions that return values
    Public Function DataReturn (Input As Variant) As Variant
       DataReturn = ExampleData + Input
    End Function 
    ''***********************************''
    ' Public Sub Routines
    Public Sub GlobalMethod() 
       'call local Functions/Subs outside of form
       Me.Form.Refresh
    End Sub
    ''***********************************''
    ' Private Functions/Subs used not visible outside 
    ''***********************************''
    End Code
    

    So in the other module you would be able to access:

    Public Sub Method1(objForm as Object)
       'read/write data value
       objForm.GlobalData
       'Get object reference (need to add Public Property Set to change reference object)
       objForm.ObjectVariable
       'read only (needs Public property Let to change value)
       objForm.Variable1
       'Gets result of function with input
       objForm.DataReturn([Input])
       'runs sub/function from outside of normal scope
       objForm.GlobalMethod
    End Sub
    

    If you use Late Binding like I do always check for Null values and objects that are Nothing before attempting to do any processing.

    Check whether specific radio button is checked

    WHy bother with all of the fancy selectors? If you're using those id="" attributes properly, then 'test2' must be the only tag with that id on the page, then the .checked boolean property will tell you if it's checked or not:

    if ($('test2').checked) {
        ....
    }
    

    You've also not set any values for those radio buttons, so no matter which button you select, you'll just get a blank "testGroup=" submitted to the server.

    How can I convert an image into a Base64 string?

    Here is the encoding and decoding code in Kotlin:

     fun encode(imageUri: Uri): String {
        val input = activity.getContentResolver().openInputStream(imageUri)
        val image = BitmapFactory.decodeStream(input , null, null)
    
        // Encode image to base64 string
        val baos = ByteArrayOutputStream()
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        var imageBytes = baos.toByteArray()
        val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
        return imageString
    }
    
    fun decode(imageString: String) {
    
        // Decode base64 string to image
        val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
        val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
    
        imageview.setImageBitmap(decodedImage)
    }
    

    Best way to integrate Python and JavaScript?

    If your just interested in sharing complex data types between javascript and python, check out jsonpickle. It wraps the standard Python JSON libraries, but has some smarts in serializing and deserializing Python classes and other data types.

    Quite a few Google App Engine projects have used this library. Joose and FirePython both incorporate jsonpickle.

    MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

    Here is some SQL that actually make sense:

    SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL
    

    Simple is always better.

    Calling a Sub in VBA

    Try -

    Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)
    

    As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

    You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

    Compare a date string to datetime in SQL Server?

    DECLARE @Dat
    
    SELECT * 
    FROM Jai
    WHERE                                                                                                          
    CONVERT(VARCHAR(2),DATEPART("dd",Date)) +'/'+                                                              
                 CONVERT(VARCHAR(2),DATEPART("mm",Date)) +'/'+              
                         CONVERT(VARCHAR(4), DATEPART("yy",Date)) = @Dat
    

    Open popup and refresh parent page on close popup

    on your child page, put these:

    <script type="text/javascript">
        function refreshAndClose() {
            window.opener.location.reload(true);
            window.close();
        }
    </script>
    

    and

    <body onbeforeunload="refreshAndClose();">
    

    but as a good UI design, you should use a Close button because it's more user friendly. see code below.

    <script type="text/javascript">
        $(document).ready(function () {
            $('#btn').click(function () {
                window.opener.location.reload(true);
                window.close();
            });
        });
    </script>
    
    <input type='button' id='btn' value='Close' />
    

    What is the difference between Trap and Interrupt?

    A Trap can be identified as a transfer of control, which is initiated by the programmer. The term Trap is used interchangeably with the term Exception (which is an automatically occurring software interrupt). But some may argue that a trap is simply a special subroutine call. So they fall in to the category of software-invoked interrupts. For example, in 80×86 machines, a programmer can use the int instruction to initiate a trap. Because a trap is always unconditional the control will always be transferred to the subroutine associated with the trap. The exact instruction, which invokes the routine for handling the trap is easily identified because an explicit instruction is used to specify a trap.

    What are all the different ways to create an object in Java?

    We can create an objects in 5 ways:

    1. by new operator
    2. by reflection (e.g. Class.forName() followed by Class.newInstance())
    3. by factory method
    4. by cloning
    5. by reflection api

    Https Connection Android

    Probably you can try something like this. This helped me

        SslContextFactory sec = new SslContextFactory();
        sec.setValidateCerts(false);
        sec.setTrustAll(true);
    
        org.eclipse.jetty.websocket.client.WebSocketClient client = new WebSocketClient(sec);
    

    How does the class_weight parameter in scikit-learn work?

    First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

    For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

    For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

    How to catch an Exception from a thread

    This explains the state transition of threads dependening on whether an exceptions occured or not:

    Threads and Exception Handling

    Source : http://www-public.imtbs-tsp.eu/~gibson/Teaching/CSC7322/L8-ExceptionsAndThreads.pdf

    Add rows to CSV File in powershell

    Create a new custom object and add it to the object array that Import-Csv creates.

    $fileContent = Import-csv $file -header "Date", "Description"
    $newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
    $fileContent += $newRow
    

    Is it ok to run docker from inside docker?

    It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.

    The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.

    The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).

    I wrote a blog describing the pros/cons of DinD vs DooD here.

    Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.

    \n or \n in php echo not print

    Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:

    echo '<p>' . $unit1 . "</p>\n";
    

    PS: One clarification, single quotes strings do accept two escape sequences:

    • \' when you want to use single quote inside single quoted strings
    • \\ when you want to use backslash literally

    string.split - by multiple character delimiter

    To show both string.Split and Regex usage:

    string input = "abc][rfd][5][,][.";
    string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
    string[] parts2 = Regex.Split(input, @"\]\[");
    

    Backup/Restore a dockerized PostgreSQL database

    The below command can be used to take dump from docker postgress container

    docker exec -t <postgres-container-name> pg_dump --no-owner -U <db-username> <db-name> > file-name-to-backup-to.sql
    

    How to use an array list in Java?

    The following snippet gives an example that shows how to get an element from a List at a specified index, and also how to use the advanced for-each loop to iterate through all elements:

        import java.util.*;
    
        //...
    
        List<String> list = new ArrayList<String>();
        list.add("Hello!");
        list.add("How are you?");
    
        System.out.println(list.get(0)); // prints "Hello!"
    
        for (String s : list) {
            System.out.println(s);
        } // prints "Hello!", "How are you?"
    

    Note the following:

    • Generic List<String> and ArrayList<String> types are used instead of raw ArrayList type.
    • Variable names starts with lowercase
    • list is declared as List<String>, i.e. the interface type instead of implementation type ArrayList<String>.

    References

    API:

    Don't use raw types

    • JLS 4.8 Raw Types

      The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

    • Effective Java 2nd Edition: Item 23: Don't use raw types in new code

      If you use raw types, you lose all the safety and expressiveness benefits of generics.

    Prefer interfaces to implementation classes in type declarations

    • Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces

      [...] you should favor the use of interfaces rather than classes to refer to objects. If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types.

    Naming conventions

    Variables: Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.

    what's the default value of char?

    The default char is the character with an int value of 0 (zero).

    char NULLCHAR = (char) 0;

    char NULLCHAR = '\0';

    NSOperation vs Grand Central Dispatch

    In line with my answer to a related question, I'm going to disagree with BJ and suggest you first look at GCD over NSOperation / NSOperationQueue, unless the latter provides something you need that GCD doesn't.

    Before GCD, I used a lot of NSOperations / NSOperationQueues within my applications for managing concurrency. However, since I started using GCD on a regular basis, I've almost entirely replaced NSOperations and NSOperationQueues with blocks and dispatch queues. This has come from how I've used both technologies in practice, and from the profiling I've performed on them.

    First, there is a nontrivial amount of overhead when using NSOperations and NSOperationQueues. These are Cocoa objects, and they need to be allocated and deallocated. In an iOS application that I wrote which renders a 3-D scene at 60 FPS, I was using NSOperations to encapsulate each rendered frame. When I profiled this, the creation and teardown of these NSOperations was accounting for a significant portion of the CPU cycles in the running application, and was slowing things down. I replaced these with simple blocks and a GCD serial queue, and that overhead disappeared, leading to noticeably better rendering performance. This wasn't the only place where I noticed overhead from using NSOperations, and I've seen this on both Mac and iOS.

    Second, there's an elegance to block-based dispatch code that is hard to match when using NSOperations. It's so incredibly convenient to wrap a few lines of code in a block and dispatch it to be performed on a serial or concurrent queue, where creating a custom NSOperation or NSInvocationOperation to do this requires a lot more supporting code. I know that you can use an NSBlockOperation, but you might as well be dispatching something to GCD then. Wrapping this code in blocks inline with related processing in your application leads in my opinion to better code organization than having separate methods or custom NSOperations which encapsulate these tasks.

    NSOperations and NSOperationQueues still have very good uses. GCD has no real concept of dependencies, where NSOperationQueues can set up pretty complex dependency graphs. I use NSOperationQueues for this in a handful of cases.

    Overall, while I usually advocate for using the highest level of abstraction that accomplishes the task, this is one case where I argue for the lower-level API of GCD. Among the iOS and Mac developers I've talked with about this, the vast majority choose to use GCD over NSOperations unless they are targeting OS versions without support for it (those before iOS 4.0 and Snow Leopard).

    SFTP file transfer using Java JSch

    The most trivial way to upload a file over SFTP with JSch is:

    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host);
    session.setPassword(password);
    session.connect();
    
    ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
    sftpChannel.connect();
    
    sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
    

    Similarly for a download:

    sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
    

    You may need to deal with UnknownHostKey exception.

    Set Focus on EditText

    If using requestFocus() in onCreate() introduces the issue of keyboard not showing on tap, use BindingAdapter using a SingleLiveEvent and request the focus inside that.

    Here's how to do it:

    BindingAdapter

    @BindingAdapter("requestFocus")
    fun bindRequestFocus(editText: EditText, event: Event<Boolean>?) {
        event?.getContentIfNotHandled()?.let {
            if (it) editText.requestFocus()
        }
    }
    

    Adding an item to an associative array

    You can simply do this

    $data += array($category => $question);
    

    If your're running on php 5.4+

    $data += [$category => $question];
    

    MySql sum elements of a column

    Try this:

    select sum(a), sum(b), sum(c)
    from your_table
    

    What does the @ symbol before a variable name mean in C#?

    The @ symbol serves 2 purposes in C#:

    Firstly, it allows you to use a reserved keyword as a variable like this:

    int @int = 15;
    

    The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:

    var myString = "c:\\myfolder\\myfile.txt"
    

    alternatively you can do this:

    var myString = @"c:\myFolder\myfile.txt"
    

    How to change the default background color white to something else in twitter bootstrap

    Its not recommended to overwrite bootstrap file, just in your local style.css use

    body{background: your color !important;

    here !important declaration overwrite bootstrap value.

    What is deserialize and serialize in JSON?

    Explanation of Serialize and Deserialize using Python

    In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.

    Serialization using pickle

    import pickle
    
    #the object to serialize
    example_dic={1:"6",2:"2",3:"f"}
    
    #where the bytes after serializing end up at, wb stands for write byte
    pickle_out=open("dict.pickle","wb")
    #Time to dump
    pickle.dump(example_dic,pickle_out)
    #whatever you open, you must close
    pickle_out.close()
    

    The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):

    €}q (KX 6qKX 2qKX fqu.

    Deserialization using pickle

    import pickle
    
    pickle_in=open("dict.pickle","rb")
    get_deserialized_data_back=pickle.load(pickle_in)
    
    print(get_deserialized_data_back)
    

    Output:

    {1: '6', 2: '2', 3: 'f'}

    Java 8 forEach with index

    Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

    IntStream.range(0, params.size())
      .forEach(idx ->
        query.bind(
          idx,
          params.get(idx)
        )
      )
    ;
    

    The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

    Controller 'ngModel', required by directive '...', can't be found

    As described here: Angular NgModelController, you should provide the <input with the required controller ngModel

    <input submit-required="true" ng-model="user.Name"></input>
    

    How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

    I just came across this problem when I replaced a failing disk. I had copied over the system files to the new disk, and was good about replacing the old disk's UUID entry with the new disk's UUID in fstab.

    However I had not replaced the UUID in the grub.conf (sometimes menu.lst) file in /boot/grub. So check your grub.conf file, and if the "kernel" line has something like

    kernel ... root=UUID=906eaa97-f66a-4d39-a39d-5091c7095987 
    

    it likely has the old disk's UUID. Replace it with the new disk's UUID and run grub-install (if you're in a live CD rescue you may need to chroot or specify the grub directory).

    jQuery: serialize() form and other parameters

    Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:

    var data = form.serialize() + '&' + $.param(object)
    

    See http://api.jquery.com/jQuery.param for further reference.

    ASP.NET MVC Custom Error Handling Application_Error Global.asax?

    Perhaps a better way of handling errors in MVC is to apply the HandleError attribute to your controller or action and update the Shared/Error.aspx file to do what you want. The Model object on that page includes an Exception property as well as ControllerName and ActionName.

    how to evenly distribute elements in a div next to each other?

    In the 'old days' you'd use a table and your menu items would be evenly spaced without having to explicitly state the width for the number of items.

    If it wasn't for IE 6 and 7 (if that is of concern) then you can do the same in CSS.

    <div class="demo">
        <span>Span 1</span>
        <span>Span 2</span>
        <span>Span 3</span>
    </div>
    

    CSS:

    div.demo {
        display: table;
        width: 100%;
        table-layout: fixed;    /* For cells of equal size */
    }
    div.demo span {
        display: table-cell;
        text-align: center;
    }
    

    Without having to adjust for the number of items.

    Example without table-layout:fixed - the cells are evenly distributed across the full width, but they are not necessarily of equal size since their width is determined by their contents.

    Example with table-layout:fixed - the cells are of equal size, regardless of their contents. (Thanks to @DavidHerse in comments for this addition.)

    If you want the first and last menu elements to be left and right justified, then you can add the following CSS:

    div.demo span:first-child {
        text-align: left;
    }
    div.demo span:last-child {
        text-align: right;
    }
    

    ImportError: No module named apiclient.discovery

    This can also happen if the interpreter on your IDE is pointing to the wrong virtual environment. In VSCODE I've set it manually to the correct interpreter and my problem was solved.

    How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

    I had this problem and for me, I had a space in one of my ID values for one of my controls. I took the space out and the designer file regenerated itself.

    Android : change button text and background color

    add below line in styles.xml

    <style name="AppTheme.Gray" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorButtonNormal">@color/colorGray</item>
        </style>
    

    in button, add android:theme="@style/AppTheme.Gray", example:

    <Button
                android:theme="@style/AppTheme.Gray"
                android:textColor="@color/colorWhite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@android:string/cancel"/>
    

    jQuery AJAX Character Encoding

    <script type="text/javascript">
      function GetContent(idUser){ 
        $.ajaxSetup({
          url: 'ping.php'
        });
    
        $.ajax({
          type: "POST",
          url: "blablabla.php",
          dataType: "text",
          data: ({ParamUserID:idUser}),// here we def wich variabe is assiciated
          contentType: "application/x-www-form-urlencoded; charset=iso-8859-1",
          success: function(html) {
            $('#user_specified_content').html(html);
          }
        });     
      }
    </script> 
    

    This is the script from which I get my content from the blabla.php page.

    When I receive my data on success my accents don't appear.

    I have found a super good working solution by my own for fetching data with accents on the fetched data from .success function

    On my blabla page. I did this to bring a solution to my problem:

    I use utf8_encode(place your data here) in my php file. See it in action below:

    while( $row = sqlsrv_fetch_array($recordset) )
    {                           
        <option value="<?php echo $row["xyz"]; ?>"><?php echo utf8_encode($row["gName"]) . ' | ' . utf8_encode($row["gManagerName"]); ?></option>                           
    }
    

    Javascript: how to validate dates in format MM-DD-YYYY?

    what isn't working about it? here's a tested version:

    String.prototype.isValidDate = function()   {
    
        const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
        if (!match || match.length !== 4) {
            return false
        }
    
        const test = new Date(match[3], match[1] - 1, match[2]);
    
        return (
            (test.getMonth() == match[1] - 1) &&
            (test.getDate() == match[2]) &&
            (test.getFullYear() == match[3])
        );
    }
    
    var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
    alert(date.isValidDate() ); // true
    

    Fragment MyFragment not attached to Activity

    I faced similar issues when the application settings activity with the loaded preferences was visible. If I would change one of the preferences and then make the display content rotate and change the preference again, it would crash with a message that the fragment (my Preferences class) was not attached to an activity.

    When debugging it looked like the onCreate() Method of the PreferencesFragment was being called twice when the display content rotated. That was strange enough already. Then I added the isAdded() check outside of the block where it would indicate the crash and it solved the issue.

    Here is the code of the listener that updates the preferences summary to show the new entry. It is located in the onCreate() method of my Preferences class which extends the PreferenceFragment class:

    public static class Preferences extends PreferenceFragment {
        SharedPreferences.OnSharedPreferenceChangeListener listener;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            // ...
            listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                    // check if the fragment has been added to the activity yet (necessary to avoid crashes)
                    if (isAdded()) {
                        // for the preferences of type "list" set the summary to be the entry of the selected item
                        if (key.equals(getString(R.string.pref_fileviewer_textsize))) {
                            ListPreference listPref = (ListPreference) findPreference(key);
                            listPref.setSummary("Display file content with a text size of " + listPref.getEntry());
                        } else if (key.equals(getString(R.string.pref_fileviewer_segmentsize))) {
                            ListPreference listPref = (ListPreference) findPreference(key);
                            listPref.setSummary("Show " + listPref.getEntry() + " bytes of a file at once");
                        }
                    }
                }
            };
            // ...
        }
    

    I hope this will help others!

    Fetch first element which matches criteria

    This might be what you are looking for:

    yourStream
        .filter(/* your criteria */)
        .findFirst()
        .get();
    

    And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

    yourStream
        .filter(/* your criteria */)
        .findFirst()
        .orElse(null); /* You could also create a default object here */
    


    An example:
    public static void main(String[] args) {
        class Stop {
            private final String stationName;
            private final int    passengerCount;
    
            Stop(final String stationName, final int passengerCount) {
                this.stationName    = stationName;
                this.passengerCount = passengerCount;
            }
        }
    
        List<Stop> stops = new LinkedList<>();
    
        stops.add(new Stop("Station1", 250));
        stops.add(new Stop("Station2", 275));
        stops.add(new Stop("Station3", 390));
        stops.add(new Stop("Station2", 210));
        stops.add(new Stop("Station1", 190));
    
        Stop firstStopAtStation1 = stops.stream()
                .filter(e -> e.stationName.equals("Station1"))
                .findFirst()
                .orElse(null);
    
        System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
    }
    

    Output is:

    At the first stop at Station1 there were 250 passengers in the train.
    

    npm install Error: rollbackFailedOptional

    Seem this bug is not fixed yet [1]. Some people get worked, some people not. I also get not worked.

    I tried clear cache with command: npm cache verify then run install command again. I got worked.

    [1]. https://github.com/npm/npm/issues/17246

    How to determine if a point is in a 2D triangle?

    Supposedly high-performance code which I adapted in JavaScript (article below):

    function pointInTriangle (p, p0, p1, p2) {
      return (((p1.y - p0.y) * (p.x - p0.x) - (p1.x - p0.x) * (p.y - p0.y)) | ((p2.y - p1.y) * (p.x - p1.x) - (p2.x - p1.x) * (p.y - p1.y)) | ((p0.y - p2.y) * (p.x - p2.x) - (p0.x - p2.x) * (p.y - p2.y))) >= 0;
    }
    
    • pointInTriangle(p, p0, p1, p2) - for counter-clockwise triangles
    • pointInTriangle(p, p0, p1, p2) - for clockwise triangles

    Look in jsFiddle (performance test included), there's also winding checking in a separate function. Or press "Run code snippet" below

    _x000D_
    _x000D_
    var ctx = $("canvas")[0].getContext("2d");_x000D_
    var W = 500;_x000D_
    var H = 500;_x000D_
    _x000D_
    var point = { x: W / 2, y: H / 2 };_x000D_
    var triangle = randomTriangle();_x000D_
    _x000D_
    $("canvas").click(function(evt) {_x000D_
        point.x = evt.pageX - $(this).offset().left;_x000D_
        point.y = evt.pageY - $(this).offset().top;_x000D_
        test();_x000D_
    });_x000D_
    _x000D_
    $("canvas").dblclick(function(evt) {_x000D_
        triangle = randomTriangle();_x000D_
        test();_x000D_
    });_x000D_
    _x000D_
    document.querySelector('#performance').addEventListener('click', _testPerformance);_x000D_
    _x000D_
    test();_x000D_
    _x000D_
    function test() {_x000D_
        var result = checkClockwise(triangle.a, triangle.b, triangle.c) ? pointInTriangle(point, triangle.a, triangle.c, triangle.b) : pointInTriangle(point, triangle.a, triangle.b, triangle.c);_x000D_
        _x000D_
        var info = "point = (" + point.x + "," + point.y + ")\n";_x000D_
        info += "triangle.a = (" + triangle.a.x + "," + triangle.a.y + ")\n";_x000D_
        info += "triangle.b = (" + triangle.b.x + "," + triangle.b.y + ")\n";_x000D_
        info += "triangle.c = (" + triangle.c.x + "," + triangle.c.y + ")\n";_x000D_
        info += "result = " + (result ? "true" : "false");_x000D_
    _x000D_
        $("#result").text(info);_x000D_
        render();_x000D_
    }_x000D_
    _x000D_
    function _testPerformance () {_x000D_
     var px = [], py = [], p0x = [], p0y = [], p1x = [], p1y = [], p2x = [], p2y = [], p = [], p0 = [], p1 = [], p2 = [];_x000D_
        _x000D_
     for(var i = 0; i < 1000000; i++) {_x000D_
        p[i] = {x: Math.random() * 100, y: Math.random() * 100};_x000D_
        p0[i] = {x: Math.random() * 100, y: Math.random() * 100};_x000D_
        p1[i] = {x: Math.random() * 100, y: Math.random() * 100};_x000D_
        p2[i] = {x: Math.random() * 100, y: Math.random() * 100};_x000D_
      }_x000D_
      console.time('optimal: pointInTriangle');_x000D_
      for(var i = 0; i < 1000000; i++) {_x000D_
        pointInTriangle(p[i], p0[i], p1[i], p2[i]);_x000D_
      }_x000D_
      console.timeEnd('optimal: pointInTriangle');_x000D_
    _x000D_
      console.time('original: ptInTriangle');_x000D_
      for(var i = 0; i < 1000000; i++) {_x000D_
       ptInTriangle(p[i], p0[i], p1[i], p2[i]);_x000D_
      }_x000D_
      console.timeEnd('original: ptInTriangle');_x000D_
    }_x000D_
    _x000D_
    function pointInTriangle (p, p0, p1, p2) {_x000D_
     return (((p1.y - p0.y) * (p.x - p0.x) - (p1.x - p0.x) * (p.y - p0.y)) | ((p2.y - p1.y) * (p.x - p1.x) - (p2.x - p1.x) * (p.y - p1.y)) | ((p0.y - p2.y) * (p.x - p2.x) - (p0.x - p2.x) * (p.y - p2.y))) >= 0;_x000D_
    }_x000D_
    _x000D_
    function ptInTriangle(p, p0, p1, p2) {_x000D_
        var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y);_x000D_
        var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y);_x000D_
    _x000D_
        if (s <= 0 || t <= 0) return false;_x000D_
    _x000D_
        var A = (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);_x000D_
        return (s + t) < A;_x000D_
    }_x000D_
    _x000D_
    function render() {_x000D_
        ctx.fillStyle = "#CCC";_x000D_
        ctx.fillRect(0, 0, 500, 500);_x000D_
        drawTriangle(triangle.a, triangle.b, triangle.c);_x000D_
        drawPoint(point);_x000D_
    }_x000D_
    _x000D_
    function checkClockwise(p0, p1, p2) {_x000D_
        var A = (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);_x000D_
        return A > 0;_x000D_
    }_x000D_
    _x000D_
    function drawTriangle(p0, p1, p2) {_x000D_
        ctx.fillStyle = "#999";_x000D_
        ctx.beginPath();_x000D_
        ctx.moveTo(p0.x, p0.y);_x000D_
        ctx.lineTo(p1.x, p1.y);_x000D_
        ctx.lineTo(p2.x, p2.y);_x000D_
        ctx.closePath();_x000D_
        ctx.fill();_x000D_
        ctx.fillStyle = "#000";_x000D_
        ctx.font = "12px monospace";_x000D_
        ctx.fillText("1", p0.x, p0.y);_x000D_
        ctx.fillText("2", p1.x, p1.y);_x000D_
        ctx.fillText("3", p2.x, p2.y);_x000D_
    }_x000D_
    _x000D_
    function drawPoint(p) {_x000D_
        ctx.fillStyle = "#F00";_x000D_
        ctx.beginPath();_x000D_
        ctx.arc(p.x, p.y, 5, 0, 2 * Math.PI);_x000D_
        ctx.fill();_x000D_
    }_x000D_
    _x000D_
    function rand(min, max) {_x000D_
     return Math.floor(Math.random() * (max - min + 1)) + min;_x000D_
    }_x000D_
    _x000D_
    function randomTriangle() {_x000D_
        return {_x000D_
            a: { x: rand(0, W), y: rand(0, H) },_x000D_
            b: { x: rand(0, W), y: rand(0, H) },_x000D_
            c: { x: rand(0, W), y: rand(0, H) }_x000D_
        };_x000D_
    }
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
    <button id="performance">Run performance test (open console)</button>_x000D_
    <pre>Click: place the point._x000D_
    Double click: random triangle.</pre>_x000D_
    <pre id="result"></pre>_x000D_
    <canvas width="500" height="500"></canvas>
    _x000D_
    _x000D_
    _x000D_

    Inspired by this: http://www.phatcode.net/articles.php?id=459

    How to manually include external aar package using new Gradle Android Build System

    If you use Gradle Kotlin DSL, you need to add a file in your module directory.

    For example: libs/someAndroidArchive.aar

    After just write this in your module build.gradle.kts in the dependency block:

    implementation(files("libs/someAndroidArchive.aar"))
    

    How to pass data between fragments

    getParentFragmentManager().setFragmentResultListener is the 2020 way of doing this. Your only limitation is to use a bundle to pass the data. Check out the docs for more info and examples.

    Some other ways

    • Call to getActivity() and cast it to the shared activity between your fragments, then use it as a bridge to pass the data. This solution is highly not recommended because of the cupelling it requires between the activity and the fragments, but it used to be the popular way of doing this back in the KitKat days...
    • Use callbacks. Any events mechanism will do. This would be a Java vanilla solution. The benefit over FragmentManager is that it's not limited to Bundles. The downside, however, is that you may run into edge cases bugs where you mess up the activity life cycle and get exceptions like IllegalStateException when the fragment manager is in the middle of saving state or the activity were destroyed. Also, it does not support cross-processing communication.

    What does <a href="#" class="view"> mean?

    Javascript may be hooking up to the click-event of the anchor, rather than injecting any href.

    For example, jQuery:

    $('a.view').click(function() { Alert('anchor without a href was clicked');});
    

    Of course, the javascript can do anything it wants with the click event--such as navigate to some other page (in which case the href is never set, but the anchor still behaves as though it were)

    base_url() function not working in codeigniter

    First of all load URL helper. you can load in "config/autoload.php" file and add following code $autoload['helper'] = array('url');

    or in controller add following code

    $this->load->helper('url');
    

    then go to config.php in cofig folder and set

    $config['base_url'] = 'http://urlbaseurl.com/';
    

    hope this will help thanks

    BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

    You're comparing apples to oranges here:

    • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

    • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

    So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

    Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

    • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

    • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

    For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

    How to convert string to Title Case in Python?

    Why not use title Right from the docs:

    >>> "they're bill's friends from the UK".title()
    "They'Re Bill'S Friends From The Uk"
    

    If you really wanted PascalCase you can use this:

    >>> ''.join(x for x in 'make IT pascal CaSe'.title() if not x.isspace())
    'MakeItPascalCase'
    

    How to convert a String to Bytearray

    Inspired by @hgoebl's answer. His code is for UTF-16 and I needed something for US-ASCII. So here's a more complete answer covering US-ASCII, UTF-16, and UTF-32.

    /**@returns {Array} bytes of US-ASCII*/
    function stringToAsciiByteArray(str)
    {
        var bytes = [];
       for (var i = 0; i < str.length; ++i)
       {
           var charCode = str.charCodeAt(i);
          if (charCode > 0xFF)  // char > 1 byte since charCodeAt returns the UTF-16 value
          {
              throw new Error('Character ' + String.fromCharCode(charCode) + ' can\'t be represented by a US-ASCII byte.');
          }
           bytes.push(charCode);
       }
        return bytes;
    }
    /**@returns {Array} bytes of UTF-16 Big Endian without BOM*/
    function stringToUtf16ByteArray(str)
    {
        var bytes = [];
        //currently the function returns without BOM. Uncomment the next line to change that.
        //bytes.push(254, 255);  //Big Endian Byte Order Marks
       for (var i = 0; i < str.length; ++i)
       {
           var charCode = str.charCodeAt(i);
           //char > 2 bytes is impossible since charCodeAt can only return 2 bytes
           bytes.push((charCode & 0xFF00) >>> 8);  //high byte (might be 0)
           bytes.push(charCode & 0xFF);  //low byte
       }
        return bytes;
    }
    /**@returns {Array} bytes of UTF-32 Big Endian without BOM*/
    function stringToUtf32ByteArray(str)
    {
        var bytes = [];
        //currently the function returns without BOM. Uncomment the next line to change that.
        //bytes.push(0, 0, 254, 255);  //Big Endian Byte Order Marks
       for (var i = 0; i < str.length; i+=2)
       {
           var charPoint = str.codePointAt(i);
           //char > 4 bytes is impossible since codePointAt can only return 4 bytes
           bytes.push((charPoint & 0xFF000000) >>> 24);
           bytes.push((charPoint & 0xFF0000) >>> 16);
           bytes.push((charPoint & 0xFF00) >>> 8);
           bytes.push(charPoint & 0xFF);
       }
        return bytes;
    }
    

    UTF-8 is variable length and isn't included because I would have to write the encoding myself. UTF-8 and UTF-16 are variable length. UTF-8, UTF-16, and UTF-32 have a minimum number of bits as their name indicates. If a UTF-32 character has a code point of 65 then that means there are 3 leading 0s. But the same code for UTF-16 has only 1 leading 0. US-ASCII on the other hand is fixed width 8-bits which means it can be directly translated to bytes.

    String.prototype.charCodeAt returns a maximum number of 2 bytes and matches UTF-16 exactly. However for UTF-32 String.prototype.codePointAt is needed which is part of the ECMAScript 6 (Harmony) proposal. Because charCodeAt returns 2 bytes which is more possible characters than US-ASCII can represent, the function stringToAsciiByteArray will throw in such cases instead of splitting the character in half and taking either or both bytes.

    Note that this answer is non-trivial because character encoding is non-trivial. What kind of byte array you want depends on what character encoding you want those bytes to represent.

    javascript has the option of internally using either UTF-16 or UCS-2 but since it has methods that act like it is UTF-16 I don't see why any browser would use UCS-2. Also see: https://mathiasbynens.be/notes/javascript-encoding

    Yes I know the question is 4 years old but I needed this answer for myself.

    Reorder HTML table rows using drag-and-drop

    I working well with it

    <script>
        $(function () {
    
            $("#catalog tbody tr").draggable({
                appendTo:"body",
                helper:"clone"
            });
            $("#cart tbody").droppable({
                activeClass:"ui-state-default",
                hoverClass:"ui-state-hover",
                accept:":not(.ui-sortable-helper)",
                drop:function (event, ui) {
                    $('.placeholder').remove();
                    row = ui.draggable;
                    $(this).append(row);
                }
            });
        });
    </script>
    

    Split a string by another string in C#

    The easiest way is to use String.Replace:

    string myString = "THExxQUICKxxBROWNxxFOX";
    mystring = mystring.Replace("xx", ", ");
    

    Or more simply:

    string myString = "THExxQUICKxxBROWNxxFOX".Replace("xx", ", ");
    

    How to read from input until newline is found using scanf()?

    I am too late, but you can try this approach as well.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int i=0, j=0, arr[100];
        char temp;
        while(scanf("%d%c", &arr[i], &temp)){
            i++;
            if(temp=='\n'){
                break;
            }
        }
        for(j=0; j<i; j++) {
            printf("%d ", arr[j]);
        }
    
        return 0;
    }
    

    How to edit log message already committed in Subversion?

    On Windows, using Tortoise SVN client:

    1. right click in your project folder and choose "Show log"
    2. in the Log Messages window, right click on a revision and choose "Edit log message"

    If it doesn't work it might because of the way SVN on server is setup, read other responses here.