Programs & Examples On #Ccl

Clozure CL (CCL) is a Common Lisp implementation.

How to download Visual Studio 2017 Community Edition for offline installation?

The command above worked for me

C:\Users\marcelo\Downloads\vs_community.exe --lang en-en --layout C:\VisualStudio2017 --all

Default property value in React component using TypeScript

With Typescript 2.1+, use Partial < T > instead of making your interface properties optional.

export interface Props {
    obj: Model,
    a: boolean
    b: boolean
}

public static defaultProps: Partial<Props> = {
    a: true
};

How to set TLS version on apache HttpClient

The solution is:

SSLContext sslContext = SSLContexts.custom()
    .useTLS()
    .build();

SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(
    sslContext,
    new String[]{"TLSv1", "TLSv1.1"},   
    null,
    BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

httpClient = HttpClients.custom()
    .setSSLSocketFactory(f)
    .build();

This requires org.apache.httpcomponents.httpclient 4.3.x though.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I faced the same issue: The db I was trying to connect did not exist. I used jpa.database=default (which I guess means it will try to connect to the database and then auto select the dialect). Once I started the database, it worked fine without any change.

There is already an object named in the database

The below steps worked for me for the same issue:

Scenario:

I was trying to add 2 new fields to my existing model for Email functionality. The new fields are "IsEmailVerified" and "ActivationCode"

Steps i have followed:

1.Deleted old migration files under "Migrations" folder which are prevented me to do Update-Database 2.Reverted all my recent changes that i have did on the model

3.Run the below command:

Add-Migration -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=Custom;Persist Security Info=True;User ID=sa;password=****"

4.Deleted the contents from Up() and Down() methods from migration file and left the methods empty

5.Run the below command:

Update-Database -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=Custom;Persist Security Info=True;User ID=sa;password="***

  1. After executes the above step, model and DB looks sync.

  2. Now, i added the new properties in the model

         public bool IsEmailVerified { get; set; }
         public Guid ActivationCode { get; set; }
    
  3. Run the below command:

Add-Migration -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=Custom;Persist Security Info=True;User ID=sa;password="***

  1. Now the migration file contains only my recent changes as below:

       public override void Up()
         {
             AddColumn("dbo.UserAccounts", "IsEmailVerified", c => c.Boolean(nullable: false));
             AddColumn("dbo.UserAccounts", "ActivationCode", c => c.Guid(nullable: false));
         }        
         public override void Down()
         {
             DropColumn("dbo.UserAccounts", "ActivationCode");
             DropColumn("dbo.UserAccounts", "IsEmailVerified");
         }
    
  2. Run the below command: Update-Database -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=Custom;Persist Security Info=True;User ID=sa;password="***

11.Now i successfully updated the database with additional columns.

The below is updated table after the recent changes:

Table after the update migration

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Check you routes, the update on 9/28/2014 impacted us. We had to adjust our older servers and add new routes. Here is the article http://www.rackspace.com/knowledge_center/article/updating-servicenet-routes-on-cloud-servers-created-before-june-3-2013

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

System.Data.SqlClient.SqlException: Login failed for user

Just set Integrated Security=False and it will work ,according to a comment difference between True and False is:

True ignores User ID and Password if provided and uses those of the running process, SSPI(Security Support Provider Interface ) it will use them if provided which is why MS prefers this. They are equivalent in that they use the same security mechanism to authenticate but that is it.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

Problem solved! I'm using Ctrl + Alt + E to open Exception Window, and I checked all throw checkbox. So the debuger can stop at the exactly the error code.

Cannot deserialize the current JSON array (e.g. [1,2,3])

This could be You

Before trying to consume your json object with another object just check that the api is returning raw json via the browser api/rootobject, for my case i found out that the underlying data provider mssqlserver was not running and throw an unhanded exception !

as simple as that :)

OWIN Security - How to Implement OAuth2 Refresh Tokens

Just implemented my OWIN Service with Bearer (called access_token in the following) and Refresh Tokens. My insight into this is that you can use different flows. So it depends on the flow you want to use how you set your access_token and refresh_token expiration times.

I will describe two flows A and B in the follwing (I suggest what you want to have is flow B):

A) expiration time of access_token and refresh_token are the same as it is per default 1200 seconds or 20 minutes. This flow needs your client first to send client_id and client_secret with login data to get an access_token, refresh_token and expiration_time. With the refresh_token it is now possible to get a new access_token for 20 minutes (or whatever you set the AccessTokenExpireTimeSpan in the OAuthAuthorizationServerOptions to). For the reason that the expiration time of access_token and refresh_token are the same, your client is responsible to get a new access_token before the expiration time! E.g. your client could send a refresh POST call to your token endpoint with the body (remark: you should use https in production)

grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxx

to get a new token after e.g. 19 minutes to prevent the tokens from expiration.

B) in this flow you want to have a short term expiration for your access_token and a long term expiration for your refresh_token. Lets assume for test purpose you set the access_token to expire in 10 seconds (AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10)) and the refresh_token to 5 Minutes. Now it comes to the interesting part setting the expiration time of refresh_token: You do this in your createAsync function in SimpleRefreshTokenProvider class like this:

var guid = Guid.NewGuid().ToString();


        //copy properties and set the desired lifetime of refresh token
        var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
        {
            IssuedUtc = context.Ticket.Properties.IssuedUtc,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
            //ExpiresUtc = DateTime.UtcNow.AddMonths(3) 
        };
        /*CREATE A NEW TICKET WITH EXPIRATION TIME OF 5 MINUTES 
         *INCLUDING THE VALUES OF THE CONTEXT TICKET: SO ALL WE 
         *DO HERE IS TO ADD THE PROPERTIES IssuedUtc and 
         *ExpiredUtc to the TICKET*/
        var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

        //saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
        // consider storing only the hash of the handle
        RefreshTokens.TryAdd(guid, refreshTokenTicket);            
        context.SetToken(guid);

Now your client is able to send a POST call with a refresh_token to your token endpoint when the access_token is expired. The body part of the call may look like this: grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xx

One important thing is that you may want to use this code not only in your CreateAsync function but also in your Create function. So you should consider to use your own function (e.g. called CreateTokenInternal) for the above code. Here you can find implementations of different flows including refresh_token flow(but without setting the expiration time of the refresh_token)

Here is one sample implementation of IAuthenticationTokenProvider on github (with setting the expiration time of the refresh_token)

I am sorry that I can't help out with further materials than the OAuth Specs and the Microsoft API Documentation. I would post the links here but my reputation doesn't let me post more than 2 links....

I hope this may help some others to spare time when trying to implement OAuth2.0 with refresh_token expiration time different to access_token expiration time. I couldn't find an example implementation on the web (except the one of thinktecture linked above) and it took me some hours of investigation until it worked for me.

New info: In my case I have two different possibilities to receive tokens. One is to receive a valid access_token. There I have to send a POST call with a String body in format application/x-www-form-urlencoded with the following data

client_id=YOURCLIENTID&grant_type=password&username=YOURUSERNAME&password=YOURPASSWORD

Second is if access_token is not valid anymore we can try the refresh_token by sending a POST call with a String body in format application/x-www-form-urlencoded with the following data grant_type=refresh_token&client_id=YOURCLIENTID&refresh_token=YOURREFRESHTOKENGUID

"The system cannot find the file specified"

I got this error when starting my ASP.NET application and in my case the problem was that the SQL Server service was not running. Starting that cleared it up.

Excel VBA Run-time Error '32809' - Trying to Understand it

Ok, this might be weird. Anyway one of my colleagues had this error and we tried the edit VBA compile whatever. But the thing is, just copy the excel file to the desktop. And it worked. The Excel file was originally in a network drive. This worked, this is my answer to this issue.

Win32Exception (0x80004005): The wait operation timed out

If you're using Entity Framework, you can extend the default timeout (to give a long-running query more time to complete) by doing:

myDbContext.Database.CommandTimeout = 300;

Where myDbContext is your DbContext instance, and 300 is the timeout value in seconds.

(Syntax current as of Entity Framework 6.)

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

TypeScript static classes

I was searching for something similar and came accross something called the Singleton Pattern.

Reference: Singleton Pattern

I am working on a BulkLoader class to load different types of files and wanted to use the Singleton pattern for it. This way I can load files from my main application class and retrieve the loaded files easily from other classes.

Below is a simple example how you can make a score manager for a game with TypeScript and the Singleton pattern.

class SingletonClass {

private static _instance:SingletonClass = new SingletonClass();

private _score:number = 0;

constructor() {
    if(SingletonClass._instance){
        throw new Error("Error: Instantiation failed: Use SingletonDemo.getInstance() instead of new.");
    }
    SingletonClass._instance = this;
}

public static getInstance():SingletonClass
{
    return SingletonClass._instance;
}

public setScore(value:number):void
{
    this._score = value;
}

public getScore():number
{
    return this._score;
}

public addPoints(value:number):void
{
    this._score += value;
}

public removePoints(value:number):void
{
    this._score -= value;
}   }

Then anywhere in your other classes you would get access to the Singleton by:

var scoreManager = SingletonClass.getInstance();
scoreManager.setScore(10); scoreManager.addPoints(1);
scoreManager.removePoints(2); console.log( scoreManager.getScore() );

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

The "ojdbc.jar" is not in the CLASSPATH of your application server.

Just tell us which application server it is and we will tell you where the driver should be placed.

Edit: I saw the tag so it has to be placed in folder "$JBOSS_HOME/server/default/lib/"

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.

Important note

Your code has a typo in your if statement in not exists(select...) part. Inner select statement has only one where condition while UserName condition is excluded from the not exists due to invalid brace completion. In any case you cave too many closing braces.

I assume this based on the fact that you're using two where conditions in update statement later on in your code.

Let's continue to my answer...

SQL Server 2008+ support MERGE statement

MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).

declare @clockDate date = '08/10/2012';
declare @userName = 'test';

merge Clock as target
using (select @clockDate, @userName) as source (ClockDate, UserName)
on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
when matched then
    update
    set BreakOut = getdate()
when not matched then
    insert (ClockDate, UserName, BreakOut)
    values (getdate(), source.UserName, getdate());

How do you handle a "cannot instantiate abstract class" error in C++?

Visual Studio's Error List pane only shows you the first line of the error. Invoke View>Output and I bet you'll see something like:

c:\path\to\your\code.cpp(42): error C2259: 'AmbientOccluder' : cannot instantiate abstract class
          due to following members:
          'ULONG MysteryUnimplementedMethod(void)' : is abstract
          c:\path\to\some\include.h(8) : see declaration of 'MysteryUnimplementedMethod'

How to properly stop the Thread in Java?

For synchronizing threads I prefer using CountDownLatch which helps threads to wait until the process being performed complete. In this case, the worker class is set up with a CountDownLatch instance with a given count. A call to await method will block until the current count reaches zero due to invocations of the countDown method or the timeout set is reached. This approach allows interrupting a thread instantly without having to wait for the specified waiting time to elapse:

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);

    private final CountDownLatch countdownlatch;
    public IndexProcessor(CountDownLatch countdownlatch) {
        this.countdownlatch = countdownlatch;
    }


    public void run() {
        try {
            while (!countdownlatch.await(15000, TimeUnit.MILLISECONDS)) {
                LOGGER.debug("Processing...");
            }
        } catch (InterruptedException e) {
            LOGGER.error("Exception", e);
            run = false;
        }

    }
}

When you want to finish execution of the other thread, execute countDown on the CountDownLatch and join the thread to the main thread:

public class SearchEngineContextListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);

    private Thread thread = null;
    private IndexProcessor runnable = null;
    private CountDownLatch countdownLatch = null;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        countdownLatch = new CountDownLatch(1);
        Thread thread = new Thread(new IndexProcessor(countdownLatch));
        LOGGER.debug("Starting thread: " + thread);
        thread.start();
        LOGGER.debug("Background process successfully started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        LOGGER.debug("Stopping thread: " + thread);
        if (countdownLatch != null) 
        {
            countdownLatch.countDown();
        } 
        if (thread != null) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
            }
            LOGGER.debug("Thread successfully stopped.");
        } 
    }
}

Encrypting & Decrypting a String in C#

using System.IO;
using System.Text;
using System.Security.Cryptography;

public static class EncryptionHelper
{
    public static string Encrypt(string clearText)
    {
        string EncryptionKey = "abc123";
        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());
            }
        }
        return clearText;
    }
    public static string Decrypt(string cipherText)
    {
        string EncryptionKey = "abc123";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        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.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
}

No connection could be made because the target machine actively refused it 127.0.0.1:3446

If you use WCF storm, can you even log-in to the WCF service endpoint? If not, and you are hosting it in a Windows service, you probably forgot to register that namespace. It's not very well advertised that this step is required, and it is actually annoying to do.

I use this tool to do this; it automates all those cumbersome steps.

How to update UI from another thread running in another class

Felt the need to add this better answer, as nothing except BackgroundWorker seemed to help me, and the answer dealing with that thus far was woefully incomplete. This is how you would update a XAML page called MainWindow that has an Image tag like this:

<Image Name="imgNtwkInd" Source="Images/network_on.jpg" Width="50" />

with a BackgroundWorker process to show if you are connected to the network or not:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

public partial class MainWindow : Window
{
    private BackgroundWorker bw = new BackgroundWorker();

    public MainWindow()
    {
        InitializeComponent();

        // Set up background worker to allow progress reporting and cancellation
        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;

        // This is your main work process that records progress
        bw.DoWork += new DoWorkEventHandler(SomeClass.DoWork);

        // This will update your page based on that progress
        bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

        // This starts your background worker and "DoWork()"
        bw.RunWorkerAsync();

        // When this page closes, this will run and cancel your background worker
        this.Closing += new CancelEventHandler(Page_Unload);
    }

    private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        BitmapImage bImg = new BitmapImage();
        bool connected = false;
        string response = e.ProgressPercentage.ToString(); // will either be 1 or 0 for true/false -- this is the result recorded in DoWork()

        if (response == "1")
            connected = true;

        // Do something with the result we got
        if (!connected)
        {
            bImg.BeginInit();
            bImg.UriSource = new Uri("Images/network_off.jpg", UriKind.Relative);
            bImg.EndInit();
            imgNtwkInd.Source = bImg;
        }
        else
        {
            bImg.BeginInit();
            bImg.UriSource = new Uri("Images/network_on.jpg", UriKind.Relative);
            bImg.EndInit();
            imgNtwkInd.Source = bImg;
        }
    }

    private void Page_Unload(object sender, CancelEventArgs e)
    {
        bw.CancelAsync();  // stops the background worker when unloading the page
    }
}


public class SomeClass
{
    public static bool connected = false;

    public void DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker bw = sender as BackgroundWorker;

        int i = 0;
        do 
        {
            connected = CheckConn();  // do some task and get the result

            if (bw.CancellationPending == true)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                Thread.Sleep(1000);
                // Record your result here
                if (connected)
                    bw.ReportProgress(1);
                else
                    bw.ReportProgress(0);
            }
        }
        while (i == 0);
    }

    private static bool CheckConn()
    {
        bool conn = false;
        Ping png = new Ping();
        string host = "SomeComputerNameHere";

        try
        {
            PingReply pngReply = png.Send(host);
            if (pngReply.Status == IPStatus.Success)
                conn = true;
        }
        catch (PingException ex)
        {
            // write exception to log
        }
        return conn;
    }
}

For more information: https://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx

Copy struct to struct in C

For simple structures you can either use memcpy like you do, or just assign from one to the other:

RTCclk = RTCclkBuffert;

The compiler will create code to copy the structure for you.


An important note about the copying: It's a shallow copy, just like with memcpy. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I am using spring 3.0 and Hibernate 3.6 in my project. I ran into the same error just now. Googling this error message brought me to this page.

Funtik's comment on Jan 17 '12 at 8:49 helped me resolve the issue-

"This tells me that javassist cannot be accessed. How do you include this library into the project?"

So, I included java assist in my maven pom file as below:

<dependency>
    <groupId>javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.12.1.GA</version>
</dependency>

This resolved the issue for me. Thanks Funtik.

Classes cannot be accessed from outside package

Check the default superclass's constructor. It need be public or protected.

WAMP Server doesn't load localhost

Solution(s) for this, found in the official wampserver.com forums:

SOLUTION #1:

This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )

To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80". Note thatPID on the right side. This is the process id of the software which currently usesport 80. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).

SOLUTION #2:

left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80" to 8080. Restart. Done !

SOLUTION #3:

Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here

By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.

IMPORTANT: you have to use localhost or 127.0.0.1 now with port 8080, this means 127.0.0.1:8080 or localhost:8080.

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

As original question was - how to ignore the cert error, here is solution for those using SpringBoot and RestTemplate

@Service
public class SomeService {

    private final RestTemplate restTemplate;

    private final ObjectMapper objectMapper;    

    private static HttpComponentsClientHttpRequestFactory createRequestFactory() {
        try {
            SSLContextBuilder sslContext = new SSLContextBuilder();
            sslContext.loadTrustMaterial(null, new TrustAllStrategy());
            CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext.build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setHttpClient(client);
            return requestFactory;
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException var3) {
            throw new IllegalStateException("Couldn't create HTTP Request factory ignore SSL cert validity: ", var3);
        }
    }

    @Autowired
    public SomeService(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        this.dimetorURL = dimetorURL;
        restTemplate.setRequestFactory(createRequestFactory());
    }


    public ResponseEntity<ResponseObject> sendRequest(RequestObject requestObject) {
        //...
        return restTemplate.exchange(url, HttpMethod.GET, ResponseObject.class);
        //...
    }
}

How do I force make/GCC to show me the commands?

Use make V=1

Other suggestions here:

  • make VERBOSE=1 - did not work at least from my trials.
  • make -n - displays only logical operation, not command line being executed. E.g. CC source.cpp

  • make --debug=j - works as well, but might also enable multi threaded building, causing extra output.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

I did it by passing the cookie through the HttpContext:

HttpContext localContext = new BasicHttpContext();

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

response = client.execute(httppost, localContext);

How to dynamically create a class?

I know i reopen this old task but with c# 4.0 this task is absolutely painless.

dynamic expando = new ExpandoObject();
expando.EmployeeID=42;
expando.Designation="unknown";
expando.EmployeeName="curt"

//or more dynamic
AddProperty(expando, "Language", "English");

for more see https://www.oreilly.com/learning/building-c-objects-dynamically

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

Get generic type of class at runtime

Sure, you can.

Java does not use the information at run time, for backwards compatibility reasons. But the information is actually present as metadata and can be accessed via reflection (but it is still not used for type-checking).

From the official API:

http://download.oracle.com/javase/6/docs/api/java/lang/reflect/ParameterizedType.html#getActualTypeArguments%28%29

However, for your scenario I would not use reflection. I'm personally more inclined to use that for framework code. In your case I would just add the type as a constructor param.

Java: Multiple class declarations in one file

My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.

As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)

MySQL Install: ERROR: Failed to build gem native extension

A number of people found this post helpful.

Also, I needed to do first type this:

yum install mysql-devel

and then:

gem install mysql 

For some people you may need to type:

gem install mysql -- --with-mysql-config=/usr/local/mysql/mysql_config

Check if a class is derived from a generic class

(Reposted due to a massive rewrite)

JaredPar's code answer is fantastic, but I have a tip that would make it unnecessary if your generic types are not based on value type parameters. I was hung up on why the "is" operator would not work, so I have also documented the results of my experimentation for future reference. Please enhance this answer to further enhance its clarity.

TIP:

If you make certain that your GenericClass implementation inherits from an abstract non-generic base class such as GenericClassBase, you could ask the same question without any trouble at all like this:

typeof(Test).IsSubclassOf(typeof(GenericClassBase))

IsSubclassOf()

My testing indicates that IsSubclassOf() does not work on parameterless generic types such as

typeof(GenericClass<>)

whereas it will work with

typeof(GenericClass<SomeType>)

Therefore the following code will work for any derivation of GenericClass<>, assuming you are willing to test based on SomeType:

typeof(Test).IsSubclassOf(typeof(GenericClass<SomeType>))

The only time I can imagine that you would want to test by GenericClass<> is in a plug-in framework scenario.


Thoughts on the "is" operator

At design-time C# does not allow the use of parameterless generics because they are essentially not a complete CLR type at that point. Therefore, you must declare generic variables with parameters, and that is why the "is" operator is so powerful for working with objects. Incidentally, the "is" operator also can not evaluate parameterless generic types.

The "is" operator will test the entire inheritance chain, including interfaces.

So, given an instance of any object, the following method will do the trick:

bool IsTypeof<T>(object t)
{
    return (t is T);
}

This is sort of redundant, but I figured I would go ahead and visualize it for everybody.

Given

var t = new Test();

The following lines of code would return true:

bool test1 = IsTypeof<GenericInterface<SomeType>>(t);

bool test2 = IsTypeof<GenericClass<SomeType>>(t);

bool test3 = IsTypeof<Test>(t);

On the other hand, if you want something specific to GenericClass, you could make it more specific, I suppose, like this:

bool IsTypeofGenericClass<SomeType>(object t)
{
    return (t is GenericClass<SomeType>);
}

Then you would test like this:

bool test1 = IsTypeofGenericClass<SomeType>(t);

How to properly and completely close/reset a TcpClient connection?

Have you tried calling TcpClient.Dispose() explicitly?

And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?

Equivalent of typedef in C#

Both C++ and C# are missing easy ways to create a new type which is semantically identical to an exisiting type. I find such 'typedefs' totally essential for type-safe programming and its a real shame c# doesn't have them built-in. The difference between void f(string connectionID, string username) to void f(ConID connectionID, UserName username) is obvious ...

(You can achieve something similar in C++ with boost in BOOST_STRONG_TYPEDEF)

It may be tempting to use inheritance but that has some major limitations:

  • it will not work for primitive types
  • the derived type can still be casted to the original type, ie we can send it to a function receiving our original type, this defeats the whole purpose
  • we cannot derive from sealed classes (and ie many .NET classes are sealed)

The only way to achieve a similar thing in C# is by composing our type in a new class:

Class SomeType { 
  public void Method() { .. }
}

sealed Class SomeTypeTypeDef {
  public SomeTypeTypeDef(SomeType composed) { this.Composed = composed; }

  private SomeType Composed { get; }

  public override string ToString() => Composed.ToString();
  public override int GetHashCode() => HashCode.Combine(Composed);
  public override bool Equals(object obj) => obj is TDerived o && Composed.Equals(o.Composed); 
  public bool Equals(SomeTypeTypeDefo) => object.Equals(this, o);

  // proxy the methods we want
  public void Method() => Composed.Method();
}

While this will work it is very verbose for just a typedef. In addition we have a problem with serializing (ie to Json) as we want to serialize the class through its Composed property.

Below is a helper class that uses the "Curiously Recurring Template Pattern" to make this much simpler:

namespace Typedef {

  [JsonConverter(typeof(JsonCompositionConverter))]
  public abstract class Composer<TDerived, T> : IEquatable<TDerived> where TDerived : Composer<TDerived, T> {
    protected Composer(T composed) { this.Composed = composed; }
    protected Composer(TDerived d) { this.Composed = d.Composed; }

    protected T Composed { get; }

    public override string ToString() => Composed.ToString();
    public override int GetHashCode() => HashCode.Combine(Composed);
    public override bool Equals(object obj) => obj is Composer<TDerived, T> o && Composed.Equals(o.Composed); 
    public bool Equals(TDerived o) => object.Equals(this, o);
  }

  class JsonCompositionConverter : JsonConverter {
    static FieldInfo GetCompositorField(Type t) {
      var fields = t.BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      if (fields.Length!=1) throw new JsonSerializationException();
      return fields[0];
    }

    public override bool CanConvert(Type t) {
      var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      return fields.Length == 1;
    }

    // assumes Compositor<T> has either a constructor accepting T or an empty constructor
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      while (reader.TokenType == JsonToken.Comment && reader.Read()) { };
      if (reader.TokenType == JsonToken.Null) return null; 
      var compositorField = GetCompositorField(objectType);
      var compositorType = compositorField.FieldType;
      var compositorValue = serializer.Deserialize(reader, compositorType);
      var ctorT = objectType.GetConstructor(new Type[] { compositorType });
      if (!(ctorT is null)) return Activator.CreateInstance(objectType, compositorValue);
      var ctorEmpty = objectType.GetConstructor(new Type[] { });
      if (ctorEmpty is null) throw new JsonSerializationException();
      var res = Activator.CreateInstance(objectType);
      compositorField.SetValue(res, compositorValue);
      return res;
    }

    public override void WriteJson(JsonWriter writer, object o, JsonSerializer serializer) {
      var compositorField = GetCompositorField(o.GetType());
      var value = compositorField.GetValue(o);
      serializer.Serialize(writer, value);
    }
  }

}

With Composer the above class becomes simply:

sealed Class SomeTypeTypeDef : Composer<SomeTypeTypeDef, SomeType> {
   public SomeTypeTypeDef(SomeType composed) : base(composed) {}

   // proxy the methods we want
   public void Method() => Composed.Method();
}

And in addition the SomeTypeTypeDef will serialize to Json in the same way that SomeType does.

Hope this helps !

What are some resources for getting started in operating system development?

You might want to look at linuxfromscratch.

Linux From Scratch (LFS) is a project that provides you with step-by-step instructions for building your own custom Linux system, entirely from source code.

Calculating days between two dates with Java

The best way, and it converts to a String as bonus ;)

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        //Dates to compare
        String CurrentDate=  "09/24/2015";
        String FinalDate=  "09/26/2015";

        Date date1;
        Date date2;

        SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

        //Setting dates
        date1 = dates.parse(CurrentDate);
        date2 = dates.parse(FinalDate);

        //Comparing dates
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long differenceDates = difference / (24 * 60 * 60 * 1000);

        //Convert long to String
        String dayDifference = Long.toString(differenceDates);

        Log.e("HERE","HERE: " + dayDifference);
    }
    catch (Exception exception) {
        Log.e("DIDN'T WORK", "exception " + exception);
    }
}

Scale iFrame css width 100% like an image

@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.

The most reliable, simplest answer is:

_x000D_
_x000D_
body {_x000D_
  /* for demo */_x000D_
  background: lightgray;_x000D_
}_x000D_
.fixed-aspect-wrapper {_x000D_
  /* anything or nothing, it doesn't matter */_x000D_
  width: 60%;_x000D_
  /* only need if other rulesets give this padding */_x000D_
  padding: 0;_x000D_
}_x000D_
.fixed-aspect-padder {_x000D_
  height: 0;_x000D_
  /* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
  padding: 0 0 56.25%;_x000D_
  position: relative;_x000D_
  /* only need next 2 rules if other rulesets change these */_x000D_
  margin: 0;_x000D_
  width: auto;_x000D_
}_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  /* for demo */_x000D_
  border: 0;_x000D_
  background: white;_x000D_
}
_x000D_
<div class="fixed-aspect-wrapper">_x000D_
  <div class="fixed-aspect-padder">_x000D_
    <iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I add PHP code/file to HTML(.html) files?

If you only have php code in one html file but have multiple other files that only contain html code, you can add the following to your .htaccess file so it will only serve that particular file as php.

<Files yourpage.html>
AddType application/x-httpd-php .html 
//you may need to use x-httpd-php5 if you are using php 5 or higher
</Files>

This will make the PHP executable ONLY on the "yourpage.html" file and not on all of your html pages which will prevent slowdown on your entire server.

As to why someone might want to serve php via an html file, I use the IMPORTHTML function in google spreadsheets to import JSON data from an external url that must be parsed with php to clean it up and build an html table. So far I haven't found any way to import a .php file into google spreadsheets so it must be saved as an .html file for the function to work. Being able to serve php via an .html file is necessary for that particular use.

Retrieving the first digit of a number

Almost certainly more efficient than using Strings:

int firstDigit(int x) {
    while (x > 9) {
        x /= 10;
    }
    return x;
}

(Works only for nonnegative integers.)

Write string to output stream

You may use Apache Commons IO:

try (OutputStream outputStream = ...) {
    IOUtils.write("data", outputStream, "UTF-8");
}

Is a LINQ statement faster than a 'foreach' loop?

LINQ is slower now, but it might get faster at some point. The good thing about LINQ is that you don't have to care about how it works. If a new method is thought up that's incredibly fast, the people at Microsoft can implement it without even telling you and your code would be a lot faster.

More importantly though, LINQ is just much easier to read. That should be enough reason.

How to change the bootstrap primary color?

Using SaSS
change the brand color

$brand-primary:#some-color;

this will change the primary color accross all UI.

Using css-
suppose you want to change button primary color.So

btn.primary{
  background:#some-color;
}

search the element and add a new css/sass rule in a new file and attach it after u load the bootstrap css.

How to call a shell script from python code?

I know this is an old question but I stumbled upon this recently and it ended up misguiding me since the Subprocess API as changed since python 3.5.

The new way to execute external scripts is with the run function, which runs the command described by args. Waits for command to complete, then returns a CompletedProcess instance.

import subprocess

subprocess.run(['./test.sh'])

see if two files have the same content in python

I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.

There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can

  • Compare file sizes first, discarding all which doesn't match
  • If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file

Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Date validation with ASP.NET validator

A CustomValidator would also work here:

<asp:CustomValidator runat="server"
    ID="valDateRange" 
    ControlToValidate="txtDatecompleted"
    onservervalidate="valDateRange_ServerValidate" 
    ErrorMessage="enter valid date" />

Code-behind:

protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
    DateTime minDate = DateTime.Parse("1000/12/28");
    DateTime maxDate = DateTime.Parse("9999/12/28");
    DateTime dt;

    args.IsValid = (DateTime.TryParse(args.Value, out dt) 
                    && dt <= maxDate 
                    && dt >= minDate);
}

jQuery UI dialog positioning

Check out some of the jQuery plugins for other implementations of a dialog. Cluetip appears to be a feature-rich tooltip/dialog style plug-in. The 4th demo sounds similar to what you are trying to do (although I see that it doesn't have the precise positioning option that you're looking for.)

Cross-Origin Read Blocking (CORB)

It seems that this warning occured when sending an empty response with a 200.

This configuration in my .htaccess display the warning on Chrome:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST,GET,HEAD,OPTIONS,PUT,DELETE"
Header always set Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization"

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

But changing the last line to

RewriteRule .* / [R=204,L]

resolve the issue!

repaint() in Java

If you added JComponent to already visible Container, then you have call

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

for example

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(460, 500);
        frame.setTitle("Circles generator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              frame.setVisible(true);
           }
        });

        String input = JOptionPane.showInputDialog("Enter n:");
        CustomComponents0 component = new CustomComponents0();
        frame.add(component);
        frame.getContentPane().validate();
        frame.getContentPane().repaint();
    }

    static class CustomComponents0 extends JLabel {

        private static final long serialVersionUID = 1L;

        @Override
        public Dimension getMinimumSize() {
            return new Dimension(200, 100);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
        }

        @Override
        public void paintComponent(Graphics g) {
            int margin = 10;
            Dimension dim = getSize();
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
        }
    }
}

Python function attributes - uses and abuses

I've created this helper decorator to easily set function attributes:

def with_attrs(**func_attrs):
    """Set attributes in the decorated function, at definition time.
    Only accepts keyword arguments.
    E.g.:
        @with_attrs(counter=0, something='boing')
        def count_it():
            count_it.counter += 1
        print count_it.counter
        print count_it.something
        # Out:
        # >>> 0
        # >>> 'boing'
    """
    def attr_decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            return fn(*args, **kwargs)

        for attr, value in func_attrs.iteritems():
            setattr(wrapper, attr, value)

        return wrapper

    return attr_decorator

A use case is to create a collection of factories and query the data type they can create at a function meta level.
For example (very dumb one):

@with_attrs(datatype=list)
def factory1():
    return [1, 2, 3]

@with_attrs(datatype=SomeClass)
def factory2():
    return SomeClass()

factories = [factory1, factory2]

def create(datatype):
    for f in factories:
        if f.datatype == datatype:
            return f()
    return None

how to split the ng-repeat data with three columns using bootstrap

m59's answer is pretty good. The one thing I don't like about it is that it uses divs for what could potentially be data for a table.

So in conjunction with m59's filter (answer somewhere above), here is how to display it in a table.

<table>
    <tr class="" ng-repeat="rows in foos | chunk:2">
        <td ng-repeat="item in rows">{{item}}</td>
    </tr>
</table>

How to get records randomly from the oracle database?

SELECT *
FROM   (
    SELECT *
    FROM   table
    ORDER BY DBMS_RANDOM.RANDOM)
WHERE  rownum < 21;

PHP json_encode json_decode UTF-8

Try sending the UTF-8 Charset header:

<?php header ('Content-type: text/html; charset=utf-8'); ?>

And the HTML meta:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

Vbscript list all PDF files in folder and subfolders

(For those who stumble upon this from your search engine of choice)

This just recursively traces down the folder, so you don't need to duplicate your code twice. Also the OPs logic is needlessly complex.

Wscript.Echo "begin."
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
Call ShowSubfolders (objSuperFolder)

Wscript.Echo "end."

WScript.Quit 0

Sub ShowSubFolders(fFolder)
    Set objFolder = objFSO.GetFolder(fFolder.Path)
    Set colFiles = objFolder.Files
    For Each objFile in colFiles
        If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
            Wscript.Echo objFile.Name
        End If
    Next

    For Each Subfolder in fFolder.SubFolders
        ShowSubFolders(Subfolder)
    Next
End Sub

How to use an image for the background in tkinter?

You can use the root.configure(background='your colour') example:- import tkinter root=tkiner.Tk() root.configure(background='pink')

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

This can happen when trigger(s) execute additional DML (data modification) queries which affect the row counts. My solution was to add the following at the top of my trigger:

SET NOCOUNT ON;

Use dynamic variable names in JavaScript

This will do exactly what you done in php:

var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1

The way to check a HDFS directory's size?

% of used space on Hadoop cluster
sudo -u hdfs hadoop fs –df

Capacity under specific folder:
sudo -u hdfs hadoop fs -du -h /user

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I am using xUnit 2.2.0.

My issue was my solution was not able to find certain dlls and app.config was trying to resolve them. The error was not showing up in the test output window in Visual Studio.

I was able to identify the error when I installed xunit.runner.console and tried to run the tests through command line.

How to run xunit tests in CLI.

Error: Cannot find module 'webpack'

Seems to be a common Windows problem. This fixed it for me:

Nodejs cannot find installed module on Windows?

"Add an environment variable called NODE_PATH and set it to %USERPROFILE%\Application Data\npm\node_modules (Windows XP), %AppData%\npm\node_modules (Windows 7), or wherever npm ends up installing the modules on your Windows flavor. To be done with it once and for all, add this as a System variable in the Advanced tab of the System Properties dialog (run control.exe sysdm.cpl,System,3)."

Note that you can't actually use another environment variable within the value of NODE_PATH. That is, don't just copy and paste that string above, but set it to an actual resolved path like C:\Users\MYNAME\AppData\Roaming\npm\node_modules

How to change the date format of a DateTimePicker in vb.net

Try this code it works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
    MsgBox(CustomeDate.ToString)

    con.Open()

    dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)

    ds = New System.Data.DataSet
    dadap.Fill(ds)
    Dgview.DataSource = ds.Tables(0)
    con.Close()

Note : if u use dd for date representation it will return nothing while selecting 1 to 9 so use d for selection

'Date time format
'MMM     Three-letter month.
'ddd     Three-letter day of the week.
'd       Day of the month.
'HH      Two-digit hours on 24-hour scale.
'mm      Two-digit minutes.
'yyyy    Four-digit year.

The documentation contains a full list of the date formats.

What does -> mean in C++?

The -> operator, which is applied exclusively to pointers, is needed to obtain the specified field or method of the object referenced by the pointer. (this applies also to structs just for their fields)

If you have a variable ptr declared as a pointer you can think of it as (*ptr).field.

A side node that I add just to make pedantic people happy: AS ALMOST EVERY OPERATOR you can define a different semantic of the operator by overloading it for your classes.

Pass multiple parameters to rest API - Spring

Multiple parameters can be given like below,

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

How to convert a 3D point into 2D perspective projection?

I know it's an old topic but your illustration is not correct, the source code sets up the clip matrix correct.

[fov * aspectRatio][        0        ][        0              ][        0       ]
[        0        ][       fov       ][        0              ][        0       ]
[        0        ][        0        ][(far+near)/(far-near)  ][(2*near*far)/(near-far)]
[        0        ][        0        ][        1              ][        0       ]

some addition to your things:

This clip matrix works only if you are projecting on static 2D plane if you want to add camera movement and rotation:

viewMatrix = clipMatrix * cameraTranslationMatrix4x4 * cameraRotationMatrix4x4;

this lets you rotate the 2D plane and move it around..-

How to draw a graph in LaTeX?

I have used graphviz ( https://www.graphviz.org/gallery ) together with LaTeX using dot command to generate graphs in PDF and includegraphics to include those.

If graphviz produces what you are aiming at, this might be the best way to integrate: dot2tex: https://ctan.org/pkg/dot2tex?lang=en

Remove blank lines with grep

Use:

$ dos2unix file
$ grep -v "^$" file

Or just simply awk:

awk 'NF' file

If you don't have dos2unix, then you can use tools like tr:

tr -d '\r' < "$file" > t ; mv t "$file"

How to redirect from one URL to another URL?

Since you tagged the question with javascript and html...

For a purely HTML solution, you can use a meta tag in the header to "refresh" the page, specifying a different URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

If you can/want to use JavaScript, you can set the location.href of the window:

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>

What is a reasonable length limit on person "Name" fields?

In the UK, there are a few government standards which deal successfully with the bulk of the UK population -- the Passport Office, the Driver & Vehicle Licensing Agency, the Deed Poll office, and the NHS. They use different standards, obviously.

Changing your name by Deed Poll allows 300 characters;

There is no legal limit on the length of your name, but we impose a limit of 300 characters (including spaces) for your full name.

The NHS uses 70 characters for patient names

PATIENT NAME
Format/length: max an70

The Passport Office allows 30+30 first/last and Driving Licenses (DVLA) is 30 total.

Note that other organisations will have their own restrictions about what they will show on the documents they produce — for HM Passport Office the limit is 30 characters each for your forename and your surname, and for the DVLA the limit is 30 characters in total for your full name.

How to programmatically move, copy and delete files and directories on SD?

/**
     * Copy the local DB file of an application to the root of external storage directory
     * @param context the Context of application
     * @param dbName The name of the DB
     */
    private void copyDbToExternalStorage(Context context , String dbName){

        try {
            File name = context.getDatabasePath(dbName);
            File sdcardFile = new File(Environment.getExternalStorageDirectory() , "test.db");//The name of output file
            sdcardFile.createNewFile();
            InputStream inputStream = null;
            OutputStream outputStream = null;
            inputStream = new FileInputStream(name);
            outputStream = new FileOutputStream(sdcardFile);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        }
        catch (Exception e) {
            Log.e("Exception" , e.toString());
        }
    }

How to sum digits of an integer in java?

public static void main(String[] args) {
        int num = 321;
        int sum = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println(sum); 
}

Output

6

The remote host closed the connection. The error code is 0x800704CD

As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).

There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx

Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:

http://blog.whitesites.com/fixing-The-remote-host-closed-the-connection-The-error-code-is-0x80070057__633882307305519259_blog.htm

The following stack-overflow post might also be of interest:

"The remote host closed the connection" in Response.OutputStream.Write

static function in C

pmg's answer is very convincing. If you would like to know how static declarations work at object level then this below info could be interesting to you. I reused the same program written by pmg and compiler it into a .so(shared object) file

Following contents are after dumping the .so file into something human readable

0000000000000675 f1: address of f1 function

000000000000068c f2: address of f2(staticc) function

note the difference in the function address , it means something . For a function that's declared with different address , it can very well signify that f2 lives very far away or in a different segment of the object file.

Linkers use something called PLT(Procedure linkage table) and GOT(Global offsets table) to understand symbols that they have access to link to .

For now think that GOT and PLT magically bind all the addresses and a dynamic section holds information of all these functions that are visible by linker.

After dumping the dynamic section of the .so file we get a bunch of entries but only interested in f1 and f2 function.

The dynamic section holds entry only for f1 function at address 0000000000000675 and not for f2 !

Num: Value Size Type Bind Vis Ndx Name

 9: 0000000000000675    23 FUNC    GLOBAL DEFAULT   11 f1

And thats it !. From this its clear that the linker will be unsuccessful in finding the f2 function since its not in the dynamic section of the .so file.

Algorithm: efficient way to remove duplicate integers from an array

First, you should create an array check[n] where n is the number of elements of the array you want to make duplicate-free and set the value of every element(of the check array) equal to 1. Using a for loop traverse the array with the duplicates, say its name is arr, and in the for-loop write this :

{
    if (check[arr[i]] != 1) {
        arr[i] = 0;
    }
    else {
        check[arr[i]] = 0;
    }
}

With that, you set every duplicate equal to zero. So the only thing is left to do is to traverse the arr array and print everything it's not equal to zero. The order stays and it takes linear time (3*n).

jquery dialog save cancel button styling

In jQueryUI 1.8.9 using className rather than classes works.

$('#element').dialog({
  buttons:{
    "send":{
      text:'Send',
      className:'save'
    },
    "cancel":{
      text:'Cancel',
      className:'cancel'
    }
  });

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

Wow, this one took me a while to solve, as I was using SVN through Eclipse. In the end, the only thing that worked for me was to commit all non-affected files, then (with Eclipse closed) rename the project directory, and re-check the project out from SVN. Glad it works properly now!

Why doesn't java.util.Set have get(int index)?

If you don't mind the set to be sorted then you may be interested to take a look at the indexed-tree-map project.

The enhanced TreeSet/TreeMap provides access to elements by index or getting the index of an element. And the implementation is based on updating node weights in the RB tree. So no iteration or backing up by a list here.

How to horizontally center an unordered list of unknown width?

The answer of philfreo is great, it works perfectly (cross-browser, with IE 7+). Just add my exp for the anchor tag inside li.

#footer ul li { display: inline; }
#footer ul li a { padding: 2px 4px; } /* no display: block here */

#footer ul li { position: relative; float: left; display: block; right: 50%; }
#footer ul li a {display: block; left: 0; } 

How to convert image to byte array

try this:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

How to get JS variable to retain value after page refresh?

You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one

If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage

Ex: using localStorage and cookies library

var mode = getStoredValue('myPageMode');

function buttonClick(mode) {
    mode = mode;
    storeValue('myPageMode', mode);
}

function storeValue(key, value) {
    if (localStorage) {
        localStorage.setItem(key, value);
    } else {
        $.cookies.set(key, value);
    }
}

function getStoredValue(key) {
    if (localStorage) {
        return localStorage.getItem(key);
    } else {
        return $.cookies.get(key);
    }
}

How can I pass selected row to commandLink inside dataTable or ui:repeat?

Thanks to this site by Mkyong, the only solution that actually worked for us to pass a parameter was this

<h:commandLink action="#{user.editAction}">
    <f:param name="myId" value="#{param.id}" />
</h:commandLink>

with

public String editAction() {

  Map<String,String> params = 
            FacesContext.getExternalContext().getRequestParameterMap();
  String idString = params.get("myId");
  long id = Long.parseLong(idString);
  ...
}

Technically, that you cannot pass to the method itself directly, but to the JSF request parameter map.

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

I didn't think it would be that simple! go to this link: https://www.codeproject.com/Articles/18399/Localizing-System-MessageBox

Download the source. Take the MessageBoxManager.cs file, add it to your project. Now just register it once in your code (for example in the Main() method inside your Program.cs file) and it will work every time you call MessageBox.Show():

    MessageBoxManager.OK = "Alright";
    MessageBoxManager.Yes = "Yep!";
    MessageBoxManager.No = "Nope";
    MessageBoxManager.Register();

See this answer for the source code here for MessageBoxManager.cs.

What is the best way to call a script from another script?

Add this to your python script.

import os
os.system("exec /path/to/another/script")

This executes that command as if it were typed into the shell.

Java: How to convert String[] to List or Set

String[] w = {"a", "b", "c", "d", "e"};  

List<String> wL = Arrays.asList(w);  

C++ equivalent of java's instanceof

Instanceof implementation without dynamic_cast

I think this question is still relevant today. Using the C++11 standard you are now able to implement a instanceof function without using dynamic_cast like this:

if (dynamic_cast<B*>(aPtr) != nullptr) {
  // aPtr is instance of B
} else {
  // aPtr is NOT instance of B
}

But you're still reliant on RTTI support. So here is my solution for this problem depending on some Macros and Metaprogramming Magic. The only drawback imho is that this approach does not work for multiple inheritance.

InstanceOfMacros.h

#include <set>
#include <tuple>
#include <typeindex>

#define _EMPTY_BASE_TYPE_DECL() using BaseTypes = std::tuple<>;
#define _BASE_TYPE_DECL(Class, BaseClass) \
  using BaseTypes = decltype(std::tuple_cat(std::tuple<BaseClass>(), Class::BaseTypes()));
#define _INSTANCE_OF_DECL_BODY(Class)                                 \
  static const std::set<std::type_index> baseTypeContainer;           \
  virtual bool instanceOfHelper(const std::type_index &_tidx) {       \
    if (std::type_index(typeid(ThisType)) == _tidx) return true;      \
    if (std::tuple_size<BaseTypes>::value == 0) return false;         \
    return baseTypeContainer.find(_tidx) != baseTypeContainer.end();  \
  }                                                                   \
  template <typename... T>                                            \
  static std::set<std::type_index> getTypeIndexes(std::tuple<T...>) { \
    return std::set<std::type_index>{std::type_index(typeid(T))...};  \
  }

#define INSTANCE_OF_SUB_DECL(Class, BaseClass) \
 protected:                                    \
  using ThisType = Class;                      \
  _BASE_TYPE_DECL(Class, BaseClass)            \
  _INSTANCE_OF_DECL_BODY(Class)

#define INSTANCE_OF_BASE_DECL(Class)                                                    \
 protected:                                                                             \
  using ThisType = Class;                                                               \
  _EMPTY_BASE_TYPE_DECL()                                                               \
  _INSTANCE_OF_DECL_BODY(Class)                                                         \
 public:                                                                                \
  template <typename Of>                                                                \
  typename std::enable_if<std::is_base_of<Class, Of>::value, bool>::type instanceOf() { \
    return instanceOfHelper(std::type_index(typeid(Of)));                               \
  }

#define INSTANCE_OF_IMPL(Class) \
  const std::set<std::type_index> Class::baseTypeContainer = Class::getTypeIndexes(Class::BaseTypes());

Demo

You can then use this stuff (with caution) as follows:

DemoClassHierarchy.hpp*

#include "InstanceOfMacros.h"

struct A {
  virtual ~A() {}
  INSTANCE_OF_BASE_DECL(A)
};
INSTANCE_OF_IMPL(A)

struct B : public A {
  virtual ~B() {}
  INSTANCE_OF_SUB_DECL(B, A)
};
INSTANCE_OF_IMPL(B)

struct C : public A {
  virtual ~C() {}
  INSTANCE_OF_SUB_DECL(C, A)
};
INSTANCE_OF_IMPL(C)

struct D : public C {
  virtual ~D() {}
  INSTANCE_OF_SUB_DECL(D, C)
};
INSTANCE_OF_IMPL(D)

The following code presents a small demo to verify rudimentary the correct behavior.

InstanceOfDemo.cpp

#include <iostream>
#include <memory>
#include "DemoClassHierarchy.hpp"

int main() {
  A *a2aPtr = new A;
  A *a2bPtr = new B;
  std::shared_ptr<A> a2cPtr(new C);
  C *c2dPtr = new D;
  std::unique_ptr<A> a2dPtr(new D);

  std::cout << "a2aPtr->instanceOf<A>(): expected=1, value=" << a2aPtr->instanceOf<A>() << std::endl;
  std::cout << "a2aPtr->instanceOf<B>(): expected=0, value=" << a2aPtr->instanceOf<B>() << std::endl;
  std::cout << "a2aPtr->instanceOf<C>(): expected=0, value=" << a2aPtr->instanceOf<C>() << std::endl;
  std::cout << "a2aPtr->instanceOf<D>(): expected=0, value=" << a2aPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2bPtr->instanceOf<A>(): expected=1, value=" << a2bPtr->instanceOf<A>() << std::endl;
  std::cout << "a2bPtr->instanceOf<B>(): expected=1, value=" << a2bPtr->instanceOf<B>() << std::endl;
  std::cout << "a2bPtr->instanceOf<C>(): expected=0, value=" << a2bPtr->instanceOf<C>() << std::endl;
  std::cout << "a2bPtr->instanceOf<D>(): expected=0, value=" << a2bPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2cPtr->instanceOf<A>(): expected=1, value=" << a2cPtr->instanceOf<A>() << std::endl;
  std::cout << "a2cPtr->instanceOf<B>(): expected=0, value=" << a2cPtr->instanceOf<B>() << std::endl;
  std::cout << "a2cPtr->instanceOf<C>(): expected=1, value=" << a2cPtr->instanceOf<C>() << std::endl;
  std::cout << "a2cPtr->instanceOf<D>(): expected=0, value=" << a2cPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "c2dPtr->instanceOf<A>(): expected=1, value=" << c2dPtr->instanceOf<A>() << std::endl;
  std::cout << "c2dPtr->instanceOf<B>(): expected=0, value=" << c2dPtr->instanceOf<B>() << std::endl;
  std::cout << "c2dPtr->instanceOf<C>(): expected=1, value=" << c2dPtr->instanceOf<C>() << std::endl;
  std::cout << "c2dPtr->instanceOf<D>(): expected=1, value=" << c2dPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2dPtr->instanceOf<A>(): expected=1, value=" << a2dPtr->instanceOf<A>() << std::endl;
  std::cout << "a2dPtr->instanceOf<B>(): expected=0, value=" << a2dPtr->instanceOf<B>() << std::endl;
  std::cout << "a2dPtr->instanceOf<C>(): expected=1, value=" << a2dPtr->instanceOf<C>() << std::endl;
  std::cout << "a2dPtr->instanceOf<D>(): expected=1, value=" << a2dPtr->instanceOf<D>() << std::endl;

  delete a2aPtr;
  delete a2bPtr;
  delete c2dPtr;

  return 0;
}

Output:

a2aPtr->instanceOf<A>(): expected=1, value=1
a2aPtr->instanceOf<B>(): expected=0, value=0
a2aPtr->instanceOf<C>(): expected=0, value=0
a2aPtr->instanceOf<D>(): expected=0, value=0

a2bPtr->instanceOf<A>(): expected=1, value=1
a2bPtr->instanceOf<B>(): expected=1, value=1
a2bPtr->instanceOf<C>(): expected=0, value=0
a2bPtr->instanceOf<D>(): expected=0, value=0

a2cPtr->instanceOf<A>(): expected=1, value=1
a2cPtr->instanceOf<B>(): expected=0, value=0
a2cPtr->instanceOf<C>(): expected=1, value=1
a2cPtr->instanceOf<D>(): expected=0, value=0

c2dPtr->instanceOf<A>(): expected=1, value=1
c2dPtr->instanceOf<B>(): expected=0, value=0
c2dPtr->instanceOf<C>(): expected=1, value=1
c2dPtr->instanceOf<D>(): expected=1, value=1

a2dPtr->instanceOf<A>(): expected=1, value=1
a2dPtr->instanceOf<B>(): expected=0, value=0
a2dPtr->instanceOf<C>(): expected=1, value=1
a2dPtr->instanceOf<D>(): expected=1, value=1

Performance

The most interesting question which now arises is, if this evil stuff is more efficient than the usage of dynamic_cast. Therefore I've written a very basic performance measurement app.

InstanceOfPerformance.cpp

#include <chrono>
#include <iostream>
#include <string>
#include "DemoClassHierarchy.hpp"

template <typename Base, typename Derived, typename Duration>
Duration instanceOfMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = ptr->template instanceOf<Derived>();
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

template <typename Base, typename Derived, typename Duration>
Duration dynamicCastMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = dynamic_cast<Derived *>(ptr) != nullptr;
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

int main() {
  unsigned testCycles = 10000000;
  std::string unit = " us";
  using DType = std::chrono::microseconds;

  std::cout << "InstanceOf performance(A->D)  : " << instanceOfMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->C)  : " << instanceOfMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->B)  : " << instanceOfMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->A)  : " << instanceOfMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  std::cout << "DynamicCast performance(A->D) : " << dynamicCastMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->C) : " << dynamicCastMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->B) : " << dynamicCastMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->A) : " << dynamicCastMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  return 0;
}

The results vary and are essentially based on the degree of compiler optimization. Compiling the performance measurement program using g++ -std=c++11 -O0 -o instanceof-performance InstanceOfPerformance.cpp the output on my local machine was:

InstanceOf performance(A->D)  : 699638 us
InstanceOf performance(A->C)  : 642157 us
InstanceOf performance(A->B)  : 671399 us
InstanceOf performance(A->A)  : 626193 us

DynamicCast performance(A->D) : 754937 us
DynamicCast performance(A->C) : 706766 us
DynamicCast performance(A->B) : 751353 us
DynamicCast performance(A->A) : 676853 us

Mhm, this result was very sobering, because the timings demonstrates that the new approach is not much faster compared to the dynamic_cast approach. It is even less efficient for the special test case which tests if a pointer of A is an instance ofA. BUT the tide turns by tuning our binary using compiler otpimization. The respective compiler command is g++ -std=c++11 -O3 -o instanceof-performance InstanceOfPerformance.cpp. The result on my local machine was amazing:

InstanceOf performance(A->D)  : 3035 us
InstanceOf performance(A->C)  : 5030 us
InstanceOf performance(A->B)  : 5250 us
InstanceOf performance(A->A)  : 3021 us

DynamicCast performance(A->D) : 666903 us
DynamicCast performance(A->C) : 698567 us
DynamicCast performance(A->B) : 727368 us
DynamicCast performance(A->A) : 3098 us

If you are not reliant on multiple inheritance, are no opponent of good old C macros, RTTI and template metaprogramming and are not too lazy to add some small instructions to the classes of your class hierarchy, then this approach can boost your application a little bit with respect to its performance, if you often end up with checking the instance of a pointer. But use it with caution. There is no warranty for the correctness of this approach.

Note: All demos were compiled using clang (Apple LLVM version 9.0.0 (clang-900.0.39.2)) under macOS Sierra on a MacBook Pro Mid 2012.

Edit: I've also tested the performance on a Linux machine using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609. On this platform the perfomance benefit was not so significant as on macOs with clang.

Output (without compiler optimization):

InstanceOf performance(A->D)  : 390768 us
InstanceOf performance(A->C)  : 333994 us
InstanceOf performance(A->B)  : 334596 us
InstanceOf performance(A->A)  : 300959 us

DynamicCast performance(A->D) : 331942 us
DynamicCast performance(A->C) : 303715 us
DynamicCast performance(A->B) : 400262 us
DynamicCast performance(A->A) : 324942 us

Output (with compiler optimization):

InstanceOf performance(A->D)  : 209501 us
InstanceOf performance(A->C)  : 208727 us
InstanceOf performance(A->B)  : 207815 us
InstanceOf performance(A->A)  : 197953 us

DynamicCast performance(A->D) : 259417 us
DynamicCast performance(A->C) : 256203 us
DynamicCast performance(A->B) : 261202 us
DynamicCast performance(A->A) : 193535 us

Django: TemplateSyntaxError: Could not parse the remainder

In templates/admin/includes_grappelli/header.html, line 12, you forgot to put admin:password_change between '.

The url Django tag syntax should always be like:

{% url 'your_url_name' %}

JavaScript checking for null vs. undefined and difference between == and ===

Ad 1. null is not an identifier for a property of the global object, like undefined can be

_x000D_
_x000D_
let x;      // undefined_x000D_
let y=null; // null_x000D_
let z=3;    // has value_x000D_
// 'w'      // is undeclared_x000D_
_x000D_
if(!x) console.log('x is null or undefined');_x000D_
if(!y) console.log('y is null or undefined');_x000D_
if(!z) console.log('z is null or undefined');_x000D_
_x000D_
try { if(w) 0 } catch(e) { console.log('w is undeclared') }_x000D_
// typeof not throw exception for undelared variabels_x000D_
if(typeof w === 'undefined') console.log('w is undefined');
_x000D_
_x000D_
_x000D_

Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.

Following your example code, try making a subclass of AbstractThing without implementing the m2 method and see what errors the compiler gives you. It will force you to implement this method.

How to pass a PHP variable using the URL

All the above answers are correct, but I noticed something very important. Leaving a space between the variable and the equal sign might result in a problem. For example, (?variablename =value)

View not attached to window manager crash

Override onConfigurationChanged and dismiss progress dialog. If progress dialog is created in portrait and dismisses in landscape then it will throw View not attached to window manager error.

Also stop the progress bar and stop the async task in onPause(), onBackPressed and onDestroy method.

if(asyncTaskObj !=null && asyncTaskObj.getStatus().equals(AsyncTask.Status.RUNNING)){

    asyncTaskObj.cancel(true);

}

Java switch statement multiple cases

The second option is completely fine. I'm not sure why a responder said it was not possible. This is fine, and I do this all the time:

switch (variable)
{
    case 5:
    case 6:
    etc.
    case 100:
        doSomething();
    break;
}

How do I fix a Git detached head?

Normally HEAD points to a branch. When it is not pointing to a branch instead when it points to a commit hash like 69e51 it means you have a detached HEAD. You need to point it two a branch to fix the issue. You can do two things to fix it.

  1. git checkout other_branch // Not possible when you need the code in that commit hash
  2. create a new branch and point the commit hash to the newly created branch.

HEAD must point to a branch, not a commit hash is the golden rule.

How to disable a input in angular2

A note in response to Belter's comment on fedtuck's accepted answer above, since I lack the reputation to add comments.

This is not true for any of which I am aware, in line with the Mozilla docs

disabled equals to true or false

When the disabled attribute is present the element is disabled regardless of value. See this example

<input placeholder="i can be changed"/>
<input disabled placeholder="i can NOT be changed"/>
<input disabled="true" placeholder="i can NOT be changed"/>
<input disabled="false" placeholder="i can NOT be changed"/>

NoSql vs Relational database

If you need to process huge amount of data with high performance

OR

If data model is not predetermined

then

NoSQL database is a better choice.

How to implode array with key and value without foreach in PHP

Here is a simple example, using class:

$input = array(
    'element1'  => 'value1',
    'element2'  => 'value2',
    'element3' =>  'value3'
);

echo FlatData::flatArray($input,', ', '=');

class FlatData
{

    public static function flatArray(array $input = array(), $separator_elements = ', ', $separator = ': ')
    {
        $output = implode($separator_elements, array_map(
            function ($v, $k, $s) {
                return sprintf("%s{$s}%s", $k, $v);
            },
            $input,
            array_keys($input),
            array_fill(0, count($input), $separator)
        ));
      return $output;
    }

}

How to read string from keyboard using C?

The following code can be used to read the input string from a user. But it's space is limited to 64.

char word[64] = { '\0' };  //initialize all elements with '\0'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
    scanf_s("%c", &word[i++], 1);
}

Multidimensional Array [][] vs [,]

One is an array of arrays, and one is a 2d array. The former can be jagged, the latter is uniform.

That is, a double[][] can validly be:

double[][] x = new double[5][];

x[0] = new double[10];
x[1] = new double[5];
x[2] = new double[3];
x[3] = new double[100];
x[4] = new double[1];

Because each entry in the array is a reference to an array of double. With a jagged array, you can do an assignment to an array like you want in your second example:

x[0] = new double[13];

On the second item, because it is a uniform 2d array, you can't assign a 1d array to a row or column, because you must index both the row and column, which gets you down to a single double:

double[,] ServicePoint = new double[10,9];

ServicePoint[0]... // <-- meaningless, a 2d array can't use just one index.

UPDATE:

To clarify based on your question, the reason your #1 had a syntax error is because you had this:

double[][] ServicePoint = new double[10][9];

And you can't specify the second index at the time of construction. The key is that ServicePoint is not a 2d array, but an 1d array (of arrays) and thus since you are creating a 1d array (of arrays), you specify only one index:

double[][] ServicePoint = new double[10][];

Then, when you create each item in the array, each of those are also arrays, so then you can specify their dimensions (which can be different, hence the term jagged array):

ServicePoint[0] = new double[13];
ServicePoint[1] = new double[20];

Hope that helps!

How do I print an IFrame from javascript in Safari/Chrome

One thing to note is if you are testing this locally using file:///, it will not work on chrome as the function in the iframe will appear as undefined. However once on a web server it will work.

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

How to mock private method for testing using PowerMock?

With no argument:

ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");

With String argument:

ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
                .withArguments(anyString()).thenReturn("mocked result");

Android Studio SDK location

If you are working on React native,please make sure you have installed these tools because I was missing and it resolved my issue Necessory tolls for installations React Native doc for installation

How to show validation message below each textbox using jquery?

is only the matter of finding the dom where you want to insert the the text.

DEMO jsfiddle

$().text(); 

What is PEP8's E128: continuation line under-indented for visual indent?

PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:

urlpatterns = patterns('',
                       url(r'^$', listing, name='investment-listing'))

or not putting any arguments on the starting line, then indenting to a uniform level:

urlpatterns = patterns(
    '',
    url(r'^$', listing, name='investment-listing'),
)

urlpatterns = patterns(
    '', url(r'^$', listing, name='investment-listing'))

I suggest taking a read through PEP-8 - you can skim through a lot of it, and it's pretty easy to understand, unlike some of the more technical PEPs.

What's the pythonic way to use getters and setters?

You can use the magic methods __getattribute__ and __setattr__.

class MyClass:
    def __init__(self, attrvalue):
        self.myattr = attrvalue
    def __getattribute__(self, attr):
        if attr == "myattr":
            #Getter for myattr
    def __setattr__(self, attr):
        if attr == "myattr":
            #Setter for myattr

Be aware that __getattr__ and __getattribute__ are not the same. __getattr__ is only invoked when the attribute is not found.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Replacing a character from a certain index

Strings in Python are immutable meaning you cannot replace parts of them.

You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.

You could for instance write a function:

def replace_str_index(text,index=0,replacement=''):
    return '%s%s%s'%(text[:index],replacement,text[index+1:])

And then for instance call it with:

new_string = replace_str_index(old_string,middle)

If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.

For instance:

replace_str_index('hello?bye',5)

will return 'hellobye'; and:

replace_str_index('hello?bye',5,'good')

will return 'hellogoodbye'.

React - clearing an input value after form submit

Since you input field is a controlled element, you cannot directly change the input field value without modifying the state.

Also in

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

this.mainInput doesn't refer the input since mainInput is an id, you need to specify a ref to the input

<input
      ref={(ref) => this.mainInput= ref}
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      value={this.state.city}
      type="text"
    />

In you current state the best way is to clear the state to clear the input value

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({city: ""});
  }

However if you still for some reason want to keep the value in state even if the form is submitted, you would rather make the input uncontrolled

<input
      id="mainInput"
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      type="text"
    />

and update the value in state onChange and onSubmit clear the input using ref

 onHandleChange(e) {
    this.setState({
      city: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

Having Said that, I don't see any point in keeping the state unchanged, so the first option should be the way to go.

How to stretch a table over multiple pages

You should \usepackage{longtable}.

Mysql - How to quit/exit from stored procedure

This works for me :

 CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
IN bus_fun_temp_id int  , OUT o_message VARCHAR (50) ,
            OUT o_number INT )
 BEGIN

DECLARE  v_pkg_name  varchar(50) ;

DECLARE  v_pkg_temp_id  int(10)  ; 

DECLARE  v_workflow_count INT(10);

-- checking if workflow created for package
select count(*)  INTO v_workflow_count from workflow w where w.package_id = 
package_id ;

this_proc:BEGIN   -- this_proc block start here 

 IF  v_workflow_count = 0 THEN
   select 'no work flow ' as 'workflow_status' ;
    SET o_message ='Work flow is not created for this package.';
    SET  o_number = -2 ;
      LEAVE this_proc;
 END IF;

select 'work flow  created ' as 'workflow_status' ;
-- To  send some message
SET o_message ='SUCCESSFUL';
SET  o_number = 1 ;

  END ;-- this_proc block end here 

END

Check to see if python script is running

I'm a big fan of Supervisor for managing daemons. It's written in Python, so there are plenty of examples of how to interact with or extend it from Python. For your purposes the XML-RPC process control API should work nicely.

How do I test if a variable does not equal either of two values?

var test = $("#test").val();
if (test != 'A' && test != 'B'){
    do stuff;
}
else {
    do other stuff;
}

How do I initialize the base (super) class?

Both

SuperClass.__init__(self, x)

or

super(SubClass,self).__init__( x )

will work (I prefer the 2nd one, as it adheres more to the DRY principle).

See here: http://docs.python.org/reference/datamodel.html#basic-customization

The VMware Authorization Service is not running

You can fix this by starting the service manually.

  1. Type services in the Windows search bar.
  2. Open Services; scroll to the VMware Authorization Service (should be close to the bottom of the page)
  3. Double-click to open the Properties page of the service.
  4. Change the startup type to Automatic and then start the service. That way, the service will be started automatically every time you log in.

More detailed info can be found at Powering on a virtual machine fails with the error: The VMware Authorization Service is not running (1007131)

How do I find which rpm package supplies a file I'm looking for?

You can do this alike here but with your package. In my case, it was lsb_release

Run: yum whatprovides lsb_release

Response:

redhat-lsb-core-4.1-24.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-24.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release`

Run to install: yum install redhat-lsb-core

The package name SHOULD be without number and system type so yum packager can choose what is best for him.

How to set default vim colorscheme

Once you’ve decided to change vim color scheme that you like, you’ll need to configure vim configuration file ~/.vimrc.

For e.g. to use the elflord color scheme just add these lines to your ~/.vimrc file:

colo elflord

For other names of color schemes you can look in /usr/share/vim/vimNN/colors where NN - version of VIM.

Running Composer returns: "Could not open input file: composer.phar"

I found this worked as I did not have curl installed. On Windows 8 with XAMPP installed. It will add it to your local build I use .gitignore to avoid the repo

php -r "readfile('https://getcomposer.org/installer');" | php

I got it from here: https://getcomposer.org/download/

How do I keep CSS floats in one line?

Wrap your floaters in a div with a min-width greater than the combined width+margin of the floaters.

No hacks or HTML tables needed.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The following is needed:

  • MS Online Services Assistant needs to be downloaded and installed.
  • MS Online Module for PowerShell needs to be downloaded and installed
  • Connect to Microsoft Online in PowerShell

Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/

Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)

Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html

Hope this is better and can save some people's time

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

Fastest way to flatten / un-flatten nested JSON objects

Here's a recursive solution for flatten I put together in PowerShell:

#---helper function for ConvertTo-JhcUtilJsonTable
#
function getNodes {
    param (
        [Parameter(Mandatory)]
        [System.Object]
        $job,
        [Parameter(Mandatory)]
        [System.String]
        $path
    )

    $t = $job.GetType()
    $ct = 0
    $h = @{}

    if ($t.Name -eq 'PSCustomObject') {
        foreach ($m in Get-Member -InputObject $job -MemberType NoteProperty) {
            getNodes -job $job.($m.Name) -path ($path + '.' + $m.Name)
        }
        
    }
    elseif ($t.Name -eq 'Object[]') {
        foreach ($o in $job) {
            getNodes -job $o -path ($path + "[$ct]")
            $ct++
        }
    }
    else {
        $h[$path] = $job
        $h
    }
}


#---flattens a JSON document object into a key value table where keys are proper JSON paths corresponding to their value
#
function ConvertTo-JhcUtilJsonTable {
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [System.Object[]]
        $jsonObj
    )

    begin {
        $rootNode = 'root'    
    }
    
    process {
        foreach ($o in $jsonObj) {
            $table = getNodes -job $o -path $rootNode

            # $h = @{}
            $a = @()
            $pat = '^' + $rootNode
            
            foreach ($i in $table) {
                foreach ($k in $i.keys) {
                    # $h[$k -replace $pat, ''] = $i[$k]
                    $a += New-Object -TypeName psobject -Property @{'Key' = $($k -replace $pat, ''); 'Value' = $i[$k]}
                    # $h[$k -replace $pat, ''] = $i[$k]
                }
            }
            # $h
            $a
        }
    }

    end{}
}

Example:

'{"name": "John","Address": {"house": "1234", "Street": "Boogie Ave"}, "pets": [{"Type": "Dog", "Age": 4, "Toys": ["rubberBall", "rope"]},{"Type": "Cat", "Age": 7, "Toys": ["catNip"]}]}' | ConvertFrom-Json | ConvertTo-JhcUtilJsonTable
Key              Value
---              -----
.Address.house   1234
.Address.Street  Boogie Ave
.name            John
.pets[0].Age     4
.pets[0].Toys[0] rubberBall
.pets[0].Toys[1] rope
.pets[0].Type    Dog
.pets[1].Age     7
.pets[1].Toys[0] catNip
.pets[1].Type    Cat

How do I get sed to read from standard input?

use "-e" to specify the sed-expression

cat input.txt | sed -e 's/foo/bar/g'

SQL to Query text in access with an apostrophe in it

How about more simply: Select * from tblStudents where [name] = replace(YourName,"'","''")

What does SQL clause "GROUP BY 1" mean?

In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.

This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.

If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).

Show Image View from file path?

You can also use:



    File imgFile = new  File(“filepath”);
    if(imgFile.exists())
    {
        ImageView myImage = new ImageView(this);
        myImage.setImageURI(Uri.fromFile(imgFile));

    }

This does the bitmap decoding implicit for you.

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

How to check if any flags of a flag combination are set?

There is HasFlag method in .NET 4 or higher.

if(letter.HasFlag(Letters.AB))
{
}

Disable developer mode extensions pop up in Chrome

Using selenium with Python, you start the driver with extensions disabled like this:

from selenium import webdriver
options = webdriver.chrome.options.Options()
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options)

The popup 'Disable developer mode extensions' will not pop up.

How to set the authorization header using curl

If you don't have the token at the time of the call is made, You will have to make two calls, one to get the token and the other to extract the token form the response, pay attention to

grep token | cut -d, -f1 | cut -d\" -f4

as it is the part which is dealing with extracting the token from the response.

echo "Getting token response and extracting token"    
def token = sh (returnStdout: true, script: """
    curl -S -i -k -X POST https://www.example.com/getToken -H \"Content-Type: application/json\" -H \"Accept: application/json\" -d @requestFile.json | grep token | cut -d, -f1 | cut -d\\" -f4
""").split()

After extracting the token you can use the token to make subsequent calls as follows.

echo "Token : ${token[-1]}"       
echo "Making calls using token..."       
curl -S -i -k  -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ${token[-1]}" https://www.example.com/api/resources 

C# code to validate email address

This may be the best way for the email validation for your textbox.

string pattern = null;
pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";

if (Regex.IsMatch("txtemail.Text", pattern))
{
MessageBox.Show ("Valid Email address ");
}
else
{
MessageBox.Show("Invalid Email Email");
}

Just include in any function where you want.

When to throw an exception?

I'd say that generally every fundamentalism leads to hell.

You certainly wouldn't want to end up with exception driven flow, but avoiding exceptions altogether is also a bad idea. You have to find a balance between both approaches. What I would not do is to create an exception type for every exceptional situation. That is not productive.

What I generally prefer is to create two basic types of exceptions which are used throughout the system: LogicalException and TechnicalException. These can be further distinguished by subtypes if needed, but it is not generally not necessary.

The technical exception denotes the really unexpected exception like database server being down, the connection to the web service threw the IOException and so on.

On the other hand the logical exceptions are used to propagate the less severe erroneous situation to the upper layers (generally some validation result).

Please note that even the logical exception is not intended to be used on regular basis to control the program flow, but rather to highlight the situation when the flow should really end. When used in Java, both exception types are RuntimeException subclasses and error handling is highly aspect oriented.

So in the login example it might be wise to create something like AuthenticationException and distinguish the concrete situations by enum values like UsernameNotExisting, PasswordMismatch etc. Then you won't end up in having a huge exception hierarchy and can keep the catch blocks on maintainable level. You can also easily employ some generic exception handling mechanism since you have the exceptions categorized and know pretty well what to propagate up to the user and how.

Our typical usage is to throw the LogicalException during the Web Service call when the user's input was invalid. The Exception gets marshalled to the SOAPFault detail and then gets unmarshalled to the exception again on the client which is resulting in showing the validation error on one certain web page input field since the exception has proper mapping to that field.

This is certainly not the only situation: you don't need to hit web service to throw up the exception. You are free to do so in any exceptional situation (like in the case you need to fail-fast) - it is all at your discretion.

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

I keep getting "Uncaught SyntaxError: Unexpected token o"

SyntaxError: Unexpected token o in JSON

This also happens when you forget to use the await keyword for a method that returns JSON data.

For example:

async function returnJSONData()
{
   return "{\"prop\": 2}";
}

var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);

will throw an error because of the missing await. What is actually returned is a Promise [object], not a string.

To fix just add await as you're supposed to:

var json_str = await returnJSONData();

This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distance between your await method call and the JSON.parse call.

Using a Python subprocess call to invoke a Python script

subprocess.call expects the same arguments as subprocess.Popen - that is a list of strings (the argv in C) rather than a single string.

It's quite possible that your child process attempted to run "s" with the parameters "o", "m", "e", ...

WCF named pipe minimal example

Try this.

Here is the service part.

[ServiceContract]
public interface IService
{
    [OperationContract]
    void  HelloWorld();
}

public class Service : IService
{
    public void HelloWorld()
    {
        //Hello World
    }
}

Here is the Proxy

public class ServiceProxy : ClientBase<IService>
{
    public ServiceProxy()
        : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
            new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
    {

    }
    public void InvokeHelloWorld()
    {
        Channel.HelloWorld();
    }
}

And here is the service hosting part.

var serviceHost = new ServiceHost
        (typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
    serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
    serviceHost.Open();

    Console.WriteLine("Service started. Available in following endpoints");
    foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
    {
        Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
    }

onclick="location.href='link.html'" does not load page in Safari

You can try this:

 <a href="link.html">
       <input type="button" value="Visit Page" />
    </a>

This will create button inside a link and it works on any browser

Conda command not found

To initialize your shell run the below code

source ~/anaconda3/etc/profile.d/conda.sh
conda activate Your_env

It's Worked for me, I got the solution from the below link
https://www.codegrepper.com/code-[“CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.][1]examples/shell/CommandNotFoundError%3A+Your+shell+has+not+been+properly+configured+to+use+%27conda+activate%27.+To+initialize+your+shell%2C+run

SQL alias for SELECT statement

You can do this using the WITH clause of the SELECT statement:

;
WITH my_select As (SELECT ... FROM ...) 
SELECT * FROM foo
WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name)

That's the ANSI/ISO SQL Syntax. I know that SQL Server, Oracle and DB2 support it. Not sure about the others...

Adding a new entry to the PATH variable in ZSH

OPTION 1: Add this line to ~/.zshrc:

export "PATH=$HOME/pear/bin:$PATH"

After that you need to run source ~/.zshrc in order your changes to take affect OR close this window and open a new one

OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.

Convert an image to grayscale in HTML/CSS

As a complement to other's answers, it's possible to desaturate an image half the way on FF without SVG's matrix's headaches:

<feColorMatrix type="saturate" values="$v" />

Where $v is between 0 and 1. It's equivalent to filter:grayscale(50%);.

Live example:

_x000D_
_x000D_
.desaturate {_x000D_
    filter: url("#desaturate");_x000D_
    -webkit-filter: grayscale(50%);_x000D_
}_x000D_
figcaption{_x000D_
    background: rgba(55, 55, 136, 1);_x000D_
    padding: 4px 98px 0 18px;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    border-top-left-radius: 8px;_x000D_
    border-top-right-radius: 100%;_x000D_
    font-family: "Helvetica";_x000D_
}
_x000D_
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
  <filter id="desaturate">_x000D_
   <feColorMatrix type="saturate" values="0.4"/>_x000D_
  </filter>_x000D_
</svg>_x000D_
_x000D_
<figure>_x000D_
  <figcaption>Original</figcaption>_x000D_
  <img src="http://www.placecage.com/c/500/200"/>_x000D_
  </figure>_x000D_
<figure>_x000D_
  <figcaption>Half grayed</figcaption>_x000D_
  <img class="desaturate" src="http://www.placecage.com/c/500/200"/>_x000D_
</figure>
_x000D_
_x000D_
_x000D_

Reference on MDN

Cannot ping AWS EC2 instance

If you want to enable ping (from anywhere) programmatically, via the SDK, the magic formula is:

cidrIp:     "0.0.0.0/0"
ipProtocol: "icmp"
toPort:     -1
fromPort:   8

For example, in Scala (using the AWS Java SDK v2), the following works to define an IpPermission for the authorizeSecurityGroupIngress endpoint.

  val PingPermission = {
    val range = IpRange.builder().cidrIp( "0.0.0.0/0" ).build()
    IpPermission.builder().ipProtocol( "icmp" ).ipRanges( range ).toPort( -1 ).fromPort( 8 ).build()
  }

(I've tried this is only on EC2-Classic. I don't know what egress rules might be necessary under a VPC)

What is hashCode used for? Is it unique?

After learning what it is all about, I thought to write a hopefully simpler explanation via analogy:

Summary: What is a hashcode?

  • It's a fingerprint. We can use this finger print to identify people of interest.

Read below for more details:

Think of a Hashcode as us trying to To Uniquely Identify Someone

I am a detective, on the look out for a criminal. Let us call him Mr Cruel. (He was a notorious murderer when I was a kid -- he broke into a house kidnapped and murdered a poor girl, dumped her body and he's still out on the loose - but that's a separate matter). Mr Cruel has certain peculiar characteristics that I can use to uniquely identify him amongst a sea of people. We have 25 million people in Australia. One of them is Mr Cruel. How can we find him?

Bad ways of Identifying Mr Cruel

Apparently Mr Cruel has blue eyes. That's not much help because almost half the population in Australia also has blue eyes.

Good ways of Identifying Mr Cruel

What else can i use? I know: I will use a fingerprint!

Advantages:

  • It is really really hard for two people to have the same finger print (not impossible, but extremely unlikely).
  • Mr Cruel's fingerprint will never change.
  • Every single part of Mr Cruel's entire being: his looks, hair colour, personality, eating habits etc must (ideally) be reflected in his fingerprint, such that if he has a brother (who is very similar but not the same) - then both should have different finger prints. I say "should" because we cannot guarantee 100% that two people in this world will have different fingerprints.
  • But we can always guarantee that Mr Cruel will always have the same finger print - and that his fingerprint will NEVER change.

The above characteristics generally make for good hash functions.

So what's the deal with 'Collisions'?

So imagine if I get a lead and I find someone matching Mr Cruel's fingerprints. Does this mean I have found Mr Cruel?

........perhaps! I must take a closer look. If i am using SHA256 (a hashing function) and I am looking in a small town with only 5 people - then there is a very good chance I found him! But if I am using MD5 (another famous hashing function) and checking for fingerprints in a town with +2^1000 people, then it is a fairly good possibility that two entirely different people might have the same fingerprint.

So what is the benefit of all this anyways?

The only real benefit of hashcodes is if you want to put something in a hash table - and with hash tables you'd want to find objects quickly - and that's where the hash code comes in. They allow you to find things in hash tables really quickly. It's a hack that massively improves performance, but at a small expense of accuracy.

So let's imagine we have a hash table filled with people - 25 million suspects in Australia. Mr Cruel is somewhere in there..... How can we find him really quickly? We need to sort through them all: to find a potential match, or to otherwise acquit potential suspects. You don't want to consider each person's unique characteristics because that would take too much time. What would you use instead? You'd use a hashcode! A hashcode can tell you if two people are different. Whether Joe Bloggs is NOT Mr Cruel. If the prints don't match then you know it's definitely NOT Mr Cruel. But, if the finger prints do match then depending on the hash function you used, chances are already fairly good you found your man. But it's not 100%. The only way you can be certain is to investigate further: (i) did he/she have an opportunity/motive, (ii) witnesses etc etc.

When you are using computers if two objects have the same hash code value, then you again need to investigate further whether they are truly equal. e.g. You'd have to check whether the objects have e.g. the same height, same weight etc, if the integers are the same, or if the customer_id is a match, and then come to the conclusion whether they are the same. this is typically done perhaps by implementing an IComparer or IEquality interfaces.

Key Summary

So basically a hashcode is a finger print.

Digital Fingerprint - Picture attribute to Pixabay - Freely available for use at: https://pixabay.com/en/finger-fingerprint-security-digital-2081169/

  1. Two different people/objects can theoretically still have the same fingerprint. Or in other words. If you have two fingerprints that are the same.........then they need not both come from the same person/object.
  2. Buuuuuut, the same person/object will always return the same fingerprint.
  3. Which means that if two objects return different hash codes then you know for 100% certainty that those objects are different.

It takes a good 3 minutes to get your head around the above. Perhaps read it a few times till it makes sense. I hope this helps someone because it took a lot of grief for me to learn it all!

Python: Finding differences between elements of a list

In the upcoming Python 3.10 release schedule, with the new pairwise function it's possible to slide through pairs of elements and thus map on rolling pairs:

from itertools import pairwise

[y-x for (x, y) in pairwise([1, 3, 6, 7])]
# [2, 3, 1]

The intermediate result being:

pairwise([1, 3, 6, 7])
# [(1, 3), (3, 6), (6, 7)]

Generate signed apk android studio

you can add this to your build gradel

android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("my.keystore")
            storePassword "password"
            keyAlias "MyReleaseKey"
            keyPassword "password"
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }
}

if you then need a keyHash do like this via android stdio terminal on project root folder

keytool -exportcert -alias my.keystore -keystore app/my.keystore.jks | openssl sha1 -binary | openssl base64

How to convert password into md5 in jquery?

Download and include this plugin

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>

and use like

if(CryptoJS.MD5($("#txtOldPassword").val())) != oldPassword) {

}

//Following lines shows md5 value
//var hash = CryptoJS.MD5("Message");
//alert(hash);

Print page numbers on pages when printing html

This is what you want:

@page {
   @bottom-right {
    content: counter(page) " of " counter(pages);
   }
}

Redirect all output to file in Bash

All POSIX operating systems have 3 streams: stdin, stdout, and stderr. stdin is the input, which can accept the stdout or stderr. stdout is the primary output, which is redirected with >, >>, or |. stderr is the error output, which is handled separately so that any exceptions do not get passed to a command or written to a file that it might break; normally, this is sent to a log of some kind, or dumped directly, even when the stdout is redirected. To redirect both to the same place, use:

command &> /some/file

EDIT: thanks to Zack for pointing out that the above solution is not portable--use instead:

*command* > file 2>&1 

If you want to silence the error, do:

*command* 2> /dev/null

Event system in Python

Some time ago I've wrote library that might be useful for you. It allows you to have local and global listeners, multiple different ways of registering them, execution priority and so on.

from pyeventdispatcher import register

register("foo.bar", lambda event: print("second"))
register("foo.bar", lambda event: print("first "), -100)

dispatch(Event("foo.bar", {"id": 1}))
# first second

Have a look pyeventdispatcher

Difference between jQuery’s .hide() and setting CSS to display: none

.hide() stores the previous display property just before setting it to none, so if it wasn't the standard display property for the element you're a bit safer, .show() will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

How to change color and font on ListView

in android 6.0 you can change the colour of text like below

holder._linear_text_active_release_pass.setBackgroundColor(ContextCompat.getColor(context, R.color.green));

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I've been trying to deploy a simple Angular 7 application, to an Azure Web App. Everything worked fine, until the point where you refreshed the page. Doing so, was presenting me with an 500 error - moved content. I've read both on the Angular docs and in around a good few forums, that I need to add a web.config file to my deployed solution and make sure the rewrite rule fallback to the index.html file. After hours of frustration and trial and error tests, I've found the error was quite simple: adding a tag around my file markup.

Where is the correct location to put Log4j.properties in an Eclipse project?

The best way is to create special source folder named resources and use it for all resource including log4j.properties. So, just put it there.

On the Java Resources folder that was automatically created by the Dynamic Web Project, right click and add a new Source Folder and name it 'resources'. Files here will then be exported to the war file to the classes directory

Is there a way to style a TextView to uppercase all of its letters?

I've come up with a solution which is similar with RacZo's in the fact that I've also created a subclass of TextView which handles making the text upper-case.

The difference is that instead of overriding one of the setText() methods, I've used a similar approach to what the TextView actually does on API 14+ (which is in my point of view a cleaner solution).

If you look into the source, you'll see the implementation of setAllCaps():

public void setAllCaps(boolean allCaps) {
    if (allCaps) {
        setTransformationMethod(new AllCapsTransformationMethod(getContext()));
    } else {
        setTransformationMethod(null);
    }
}

The AllCapsTransformationMethod class is not (currently) public, but still, the source is also available. I've simplified that class a bit (removed the setLengthChangesAllowed() method), so the complete solution is this:

public class UpperCaseTextView extends TextView {

    public UpperCaseTextView(Context context) {
        super(context);
        setTransformationMethod(upperCaseTransformation);
    }

    public UpperCaseTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTransformationMethod(upperCaseTransformation);
    }

    public UpperCaseTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setTransformationMethod(upperCaseTransformation);
    }

    private final TransformationMethod upperCaseTransformation =
            new TransformationMethod() {

        private final Locale locale = getResources().getConfiguration().locale;

        @Override
        public CharSequence getTransformation(CharSequence source, View view) {
            return source != null ? source.toString().toUpperCase(locale) : null;
        }

        @Override
        public void onFocusChanged(View view, CharSequence sourceText,
                boolean focused, int direction, Rect previouslyFocusedRect) {}
    };
}

replacing text in a file with Python

The essential way is

  • read(),
  • data = data.replace() as often as you need and then
  • write().

If you read and write the whole data at once or in smaller parts is up to you. You should make it depend on the expected file size.

read() can be replaced with the iteration over the file object.

Where do you include the jQuery library from? Google JSAPI? CDN?

In head:

  (function() {
    var jsapi = document.createElement('script'); jsapi.type = 'text/javascript'; jsapi.async = true;
    jsapi.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.google.com/jsapi?key=YOUR KEY';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('head')[0]).appendChild(jsapi);
  })();

End of Body:

<script type="text/javascript">
google.load("jquery", "version");
</script>

Most efficient way to create a zero filled JavaScript array?

Shortest for loop code

a=i=[];for(;i<100;)a[i++]=0;

edit:
for(a=i=[];i<100;)a[i++]=0;
or
for(a=[],i=100;i--;)a[i]=0;

Safe var version

var a=[],i=0;for(;i<100;)a[i++]=0;

edit:
for(var i=100,a=[];i--;)a[i]=0;

Update records using LINQ

Strangely, for me it's SubmitChanges as opposed to SaveChanges:

    foreach (var item in w)
    {
        if (Convert.ToInt32(e.CommandArgument) == item.ID)
        {
            item.Sort = 1;
        }
        else
        {
            item.Sort = null;
        }
        db.SubmitChanges();            
    }                   

Make Bootstrap 3 Tabs Responsive

I prefer a css only scheme based on horizontal scroll, like tabs on android. This's my solution, just wrap with a class nav-tabs-responsive:

<div class="nav-tabs-responsive">
  <ul class="nav nav-tabs" role="tablist">
    <li>...</li>
  </ul>
</div>

And two css lines:

.nav-tabs { min-width: 600px; }
.nav-tabs-responsive { overflow: auto; }

600px is the point over you will be responsive (you can set it using bootstrap variables)

Select something that has more/less than x character

If you are using SQL Server, Use the LEN (Length) function:

SELECT EmployeeName FROM EmployeeTable WHERE LEN(EmployeeName) > 4

MSDN for it states:

Returns the number of characters of the specified string expression,
excluding trailing blanks.

Here's the link to the MSDN

For oracle/plsql you can use Length(), mysql also uses Length.

Here is the Oracle documentation:

http://www.techonthenet.com/oracle/functions/length.php

And here is the mySQL Documentation of Length(string):

http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length

For PostgreSQL, you can use length(string) or char_length(string). Here is the PostgreSQL documentation:

http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

mysqldump with create database line

The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:

mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql

Here is a dumpfile's header:

-- MySQL dump 10.13  Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost    Database: database_example
-- ------------------------------------------------------
-- Server version       5.5.36-34.2-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `database_example`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

Change the location of the ~ directory in a Windows install of Git Bash

1.Right click to Gitbash shortcut choose Properties
2.Choose "Shortcut" tab
3.Type your starting directory to "Start in" field
4.Remove "--cd-to-home" part from "Target" field

Regex for string not ending with given suffix

Try this

/.*[^a]$/

The [] denotes a character class, and the ^ inverts the character class to match everything but an a.

Scanner is never closed

Try this

Scanner scanner = new Scanner(System.in);
int amountOfPlayers;
do {
    System.out.print("Select the amount of players (1/2): ");
    while (!scanner.hasNextInt()) {
        System.out.println("That's not a number!");
        scanner.next(); // this is important!
    }

    amountOfPlayers = scanner.nextInt();
} while ((amountOfPlayers <= 0) || (amountOfPlayers > 2));
if(scanner != null) {
    scanner.close();
}
System.out.println("You've selected " + amountOfPlayers+" player(s).");

Upgrade python without breaking yum

I have written a quick guide on how to install the latest versions of Python 2 and Python 3 on CentOS 6 and CentOS 7. It currently covers Python 2.7.13 and Python 3.6.0:

# Start by making sure your system is up-to-date:
yum update
# Compilers and related tools:
yum groupinstall -y "development tools"
# Libraries needed during compilation to enable all features of Python:
yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel expat-devel
# If you are on a clean "minimal" install of CentOS you also need the wget tool:
yum install -y wget

The next steps depend on the version of Python you're installing.

For Python 2.7.14:

wget http://python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
tar xf Python-2.7.14.tar.xz
cd Python-2.7.14
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall

# Strip the Python 2.7 binary:
strip /usr/local/lib/libpython2.7.so.1.0

For Python 3.6.3:

wget http://python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
tar xf Python-3.6.3.tar.xz
cd Python-3.6.3
./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall

# Strip the Python 3.6 binary:
strip /usr/local/lib/libpython3.6m.so.1.0

To install Pip:

# First get the script:
wget https://bootstrap.pypa.io/get-pip.py

# Then execute it using Python 2.7 and/or Python 3.6:
python2.7 get-pip.py
python3.6 get-pip.py

# With pip installed you can now do things like this:
pip2.7 install [packagename]
pip2.7 install --upgrade [packagename]
pip2.7 uninstall [packagename]

You are not supposed to change the system version of Python because it will break the system (as you found out). Installing other versions works fine as long as you leave the original system version alone. This can be accomplished by using a custom prefix (for example /usr/local) when running configure, and using make altinstall (instead of the normal make install) when installing your build of Python.

Having multiple versions of Python available is usually not a big problem as long as you remember to type the full name including the version number (for example "python2.7" or "pip2.7"). If you do all your Python work from a virtualenv the versioning is handled for you, so make sure you install and use virtualenv!

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

Confirmation before closing of tab/browser

If you want to ask based on condition:

var ask = true
window.onbeforeunload = function (e) {
    if(!ask) return null
    e = e || window.event;
    //old browsers
    if (e) {e.returnValue = 'Sure?';}
    //safari, chrome(chrome ignores text)
    return 'Sure?';
};

How to check if a variable is not null?

Sometimes if it was not even defined is better to be prepared. For this I used typeof

if(typeof(variable) !== "undefined") {
    //it exist
    if(variable !== null) {
        //and is not null
    }
    else {
        //but is null
    }
}
else {
    //it doesn't
}

jQuery: serialize() form and other parameters

You can also use serializeArray function to do the same.

How to get user agent in PHP

Use the native PHP $_SERVER['HTTP_USER_AGENT'] variable instead.

How to get javax.comm API?

On ubuntu

 sudo apt-get install librxtx-java then 

add RXTX jars to the project which are in

 usr/share/java

Is null check needed before calling instanceof?

The instanceof operator does not need explicit null checks, as it does not throw a NullPointerException if the operand is null.

At run time, the result of the instanceof operator is true if the value of the relational expression is not null and the reference could be cast to the reference type without raising a class cast exception.

If the operand is null, the instanceof operator returns false and hence, explicit null checks are not required.

Consider the below example,

public static void main(String[] args) {
         if(lista != null && lista instanceof ArrayList) {                     //Violation
                System.out.println("In if block");
         }
         else {
                System.out.println("In else block");
         }
}

The correct usage of instanceof is as shown below,

public static void main(String[] args) {
      
         if(lista instanceof ArrayList){                     //Correct way
                  System.out.println("In if block");
         }
            else {
                 System.out.println("In else block");
         }  
}

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

Maybe you can simply

$ sudo bash -c "echo vm.overcommit_memory=1 >> /etc/sysctl.conf"
$ sudo sysctl -p

It works for my case.

Reference: https://github.com/openai/gym/issues/110#issuecomment-220672405

Is there a Visual Basic 6 decompiler?

For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.

How to get the selected radio button value using js

you can use this

$('input[name="field_value"]:checked').val(); 

or, for older version of jquery

$('input[@name="field_value"]:checked').val();

html table cell width for different rows

One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:

_x000D_
_x000D_
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
    <colgroup>_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
    </colgroup>_x000D_
    <tr>_x000D_
        <td colspan=5>25</td>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=5>25</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=6>30</td>_x000D_
        <td colspan=4>20</td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JSFIDDLE

Swift convert unix time to date and time

For managing dates in Swift 3 I ended up with this helper function:

extension Double {
    func getDateStringFromUTC() -> String {
        let date = Date(timeIntervalSince1970: self)

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US")
        dateFormatter.dateStyle = .medium

        return dateFormatter.string(from: date)
    }
}

This way it easy to use whenever you need it - in my case it was converting a string:

("1481721300" as! Double).getDateStringFromUTC() // "Dec 14, 2016"

Reference the DateFormatter docs for more details on formatting (Note that some of the examples are out of date)

I found this article to be very helpful as well

Failed to allocate memory: 8

I realized the solution to this problem stems from Eclipse memory allocation when you run the application in normal mode. I just checked the "Run as Administrator" box under the shortcut properties for Eclipse and now it allows me to allocate more memory for the AVD.

Hope that helps.

How do I create a Java string from the contents of a file?

Based on @erickson`s answer, you can use:

public String readAll(String fileName) throws IOException {
    List<String> lines = Files.readAllLines(new File(fileName).toPath());
    return String.join("\n", lines.toArray(new String[lines.size()]));
}

How do I check to see if a value is an integer in MySQL?

Here is the simple solution for it assuming the data type is varchar

select * from calender where year > 0

It will return true if the year is numeric else false

How do you open an SDF file (SQL Server Compact Edition)?

Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.

You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.

If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.

Update: comment from Nick Westgate in nice formatting

The steps are not all that intuitive:

  1. Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
  2. In the Connect to Server dialog change Server type to SQL Server Compact Edition
  3. From the Database file dropdown select < Browse for more...>
  4. Open your SDF file.

Bootstrap 3 Glyphicons are not working

If you're using a CDN for the bootstrap CSS files it may be the culprit, as the glyph files (e.g. glyphicons-halflings-regular.woff) are taken from the CDN as well.

In my case, I faced this issue using Microsoft's CDN, but switching to MaxCDN resolved it.

How to fetch the dropdown values from database and display in jsp

You can learn some tutorials for JSP page direct access database (mysql) here

Notes:

  • import sql tag library in jsp page

    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

  • then set datasource on page

    <sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
    
  • Now query what you want on page

    <sql:query dataSource="${ds}" var="result"> //ref  defined 'ds'
        SELECT * from <your-table>;
    </sql:query>
    
  • Finally you can populate dropdowns on page using c:forEach tag to iterate result rows in select element

    <c:forEach var="row" items="${result.rows}"> //ref set var 'result' <option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option> </c:forEach>

Are email addresses case sensitive?

I know this is an old question but I just want to comment here: To any extent email addresses ARE case sensitive, most users would be "very unwise" to actively use an email address that requires capitals. They would soon stop using the address because they'd be missing a lot of their mail. (Unless they have a specific reason to make things difficult, and they expect mail only from specific senders they know.)

That's because imperfect humans as well as imperfect software exist, (Surprise!) which will assume all email is lowercase, and for this reason these humans and software will send messages using a "lower cased version" of the address regardless of how it was provided to them. If the recipient is unable to receive such messages, it won't be long before they notice they're missing a lot, and switch to a lowercase-only email address, or get their server set up to be case-insensitive.

CSV file written with Python has blank lines between each row

In Python 2, open outfile with mode 'wb' instead of 'w'. The csv.writer writes \r\n into the file directly. If you don't open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.

In Python 3 the required syntax changed (see documentation links below), so open outfile with the additional parameter newline='' (empty string) instead.

Examples:

# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

Documentation Links

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

What you are talking about is called dot sourcing. And it's evil. But no worries, there is a better and easier way to do what you are wanting with modules (it sounds way scarier than it is). The major benefit of using modules is that you can unload them from the shell if you need to, and it keeps the variables in the functions from creeping into the shell (once you dot source a function file, try calling one of the variables from a function in the shell, and you'll see what I mean).

So first, rename the .ps1 file that has all your functions in it to MyFunctions.psm1 (you've just created a module!). Now for a module to load properly, you have to do some specific things with the file. First for Import-Module to see the module (you use this cmdlet to load the module into the shell), it has to be in a specific location. The default path to the modules folder is $home\Documents\WindowsPowerShell\Modules.

In that folder, create a folder named MyFunctions, and place the MyFunctions.psm1 file into it (the module file must reside in a folder with exactly the same name as the PSM1 file).

Once that is done, open PowerShell, and run this command:

Get-Module -listavailable

If you see one called MyFunctions, you did it right, and your module is ready to be loaded (this is just to ensure that this is set up right, you only have to do this once).

To use the module, type the following in the shell (or put this line in your $profile, or put this as the first line in a script):

Import-Module MyFunctions

You can now run your functions. The cool thing about this is that once you have 10-15 functions in there, you're going to forget the name of a couple. If you have them in a module, you can run the following command to get a list of all the functions in your module:

Get-Command -module MyFunctions

It's pretty sweet, and the tiny bit of effort that it takes to set up on the front side is WAY worth it.

How do I write out a text file in C# with a code page other than UTF-8?

using System.IO;
using System.Text;

using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{    
    sw.WriteLine("my text...");     
}

An alternate way of getting your encoding:

using System.IO;
using System.Text;

using (var sw  = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
    sw.WriteLine("my text...");             
}

Check out the docs for the StreamWriter constructor.

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

Global events are also deprecated.

Here's a patch, which fixes the browser and event issues:

--- jquery.fancybox-1.3.4.js.orig   2010-11-11 23:31:54.000000000 +0100
+++ jquery.fancybox-1.3.4.js    2013-03-22 23:25:29.996796800 +0100
@@ -26,7 +26,9 @@

        titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),

-       isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
+       isIE = !+"\v1",
+       
+       isIE6 = isIE && window.XMLHttpRequest === undefined,

        /*
         * Private methods 
@@ -322,7 +324,7 @@
            loading.hide();

            if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
-               $.event.trigger('fancybox-cancel');
+               $('.fancybox-inline-tmp').trigger('fancybox-cancel');

                busy = false;
                return;
@@ -389,7 +391,7 @@
                        content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
                    };

-                   $.event.trigger('fancybox-change');
+                   $('.fancybox-inline-tmp').trigger('fancybox-change');

                    content
                        .empty()
@@ -612,7 +614,7 @@
            }

            if (currentOpts.type == 'iframe') {
-               $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
+               $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + (isIE ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
            }

            wrap.show();
@@ -912,7 +914,7 @@

        busy = true;

-       $.event.trigger('fancybox-cancel');
+       $('.fancybox-inline-tmp').trigger('fancybox-cancel');

        _abort();

@@ -957,7 +959,7 @@
            title.empty().hide();
            wrap.hide();

-           $.event.trigger('fancybox-cleanup');
+           $('.fancybox-inline-tmp, select:not(#fancybox-tmp select)').trigger('fancybox-cleanup');

            content.empty();

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

try this method

$("your id or class name").css({ 'margin-top': '18px' });  

What does elementFormDefault do in XSD?

ElementFormDefault has nothing to do with namespace of the types in the schema, it's about the namespaces of the elements in XML documents which comply with the schema.

Here's the relevent section of the spec:

Element Declaration Schema

Component Property  {target namespace}
Representation      If form is present and its ·actual value· is qualified, 
                    or if form is absent and the ·actual value· of 
                    elementFormDefault on the <schema> ancestor is qualified, 
                    then the ·actual value· of the targetNamespace [attribute]
                    of the parent <schema> element information item, or 
                    ·absent· if there is none, otherwise ·absent·.

What that means is that the targetNamespace you've declared at the top of the schema only applies to elements in the schema compliant XML document if either elementFormDefault is "qualified" or the element is declared explicitly in the schema as having form="qualified".

For example: If elementFormDefault is unqualified -

<element name="name" type="string" form="qualified"></element>
<element name="page" type="target:TypePage"></element>

will expect "name" elements to be in the targetNamespace and "page" elements to be in the null namespace.

To save you having to put form="qualified" on every element declaration, stating elementFormDefault="qualified" means that the targetNamespace applies to each element unless overridden by putting form="unqualified" on the element declaration.

Change value in a cell based on value in another cell

=IF(A2="Y","Male",IF(A2="N","Female",""))

Python: Find a substring in a string and returning the index of the substring

late to the party, was searching for same, as "in" is not valid, I had just created following.

def find_str(full, sub):
    index = 0
    sub_index = 0
    position = -1
    for ch_i,ch_f in enumerate(full) :
        if ch_f.lower() != sub[sub_index].lower():
            position = -1
            sub_index = 0
        if ch_f.lower() == sub[sub_index].lower():
            if sub_index == 0 :
                position = ch_i

            if (len(sub) - 1) <= sub_index :
                break
            else:
                sub_index += 1

    return position

print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))

which produces

3
8
-1

remove lower() in case case insensitive find not needed.

Stripping non printable characters from a string in python

To remove 'whitespace',

import re
t = """
\n\t<p>&nbsp;</p>\n\t<p>&nbsp;</p>\n\t<p>&nbsp;</p>\n\t<p>&nbsp;</p>\n\t<p>
"""
pat = re.compile(r'[\t\n]')
print(pat.sub("", t))

How to build minified and uncompressed bundle with webpack?

You should export an array like this:

const path = require('path');
const webpack = require('webpack');

const libName = 'YourLibraryName';

function getConfig(env) {
  const config = {
    mode: env,
    output: {
      path: path.resolve('dist'),
      library: libName,
      libraryTarget: 'umd',
      filename: env === 'production' ? `${libName}.min.js` : `${libName}.js`
    },
    target: 'web',
    .... your shared options ...
  };

  return config;
}

module.exports = [
  getConfig('development'),
  getConfig('production'),
];

Set width of dropdown element in HTML select dropdown options

u can simply use "width" attribute of "style" to change the length of the dropdown box

<select class="my_dropdown" id="my_dropdown" style="width:APPROPRIATE WIDTH IN PIXLES">
<option value="1">LONG OPTION</option>
<option value="2">short</option>
</select>

e.g.

style="width:200px"

What's the best way to get the current URL in Spring MVC?

Java's URI Class can help you out of this:

public static String getCurrentUrl(HttpServletRequest request){
    URL url = new URL(request.getRequestURL().toString());
    String host  = url.getHost();
    String userInfo = url.getUserInfo();
    String scheme = url.getProtocol();
    String port = url.getPort();
    String path = request.getAttribute("javax.servlet.forward.request_uri");
    String query = request.getAttribute("javax.servlet.forward.query_string");

    URI uri = new URI(scheme,userInfo,host,port,path,query,null)
    return uri.toString();
}

Delete a database in phpMyAdmin

database_name -> Operations -> Remove database -> click on drop the database (DROP)

Writing a string to a cell in excel

replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"

When tracing out variables in the console, How to create a new line?

console.log('Hello, \n' + 
            'Text under your Header\n' + 
            '-------------------------\n' + 
            'More Text\n' +
            'Moree Text\n' +
            'Moooooer Text\n' );

This works great for me for text only, and easy on the eye.

When should I use cross apply over inner join?

The essence of the APPLY operator is to allow correlation between left and right side of the operator in the FROM clause.

In contrast to JOIN, the correlation between inputs is not allowed.

Speaking about correlation in APPLY operator, I mean on the right hand side we can put:

  • a derived table - as a correlated subquery with an alias
  • a table valued function - a conceptual view with parameters, where the parameter can refer to the left side

Both can return multiple columns and rows.

How do I implement JQuery.noConflict() ?

By default, jquery uses the variable jQuery and the $ is used for your convenience. If you want to avoid conflicts, a good way is to encapsulate jQuery like so:

(function($){

    $(function(){

        alert('$ is safe!');

    });

})(jQuery)

What are the different NameID format used for?

Refer to Section 8.3 of this SAML core pdf of oasis SAML specification.

SP and IdP usually communicate each other about a subject. That subject should be identified through a NAME-IDentifier , which should be in some format so that It is easy for the other party to identify it based on the Format.

All these

1.urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified [default]

2.urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress

3.urn:oasis:names:tc:SAML:2.0:nameid-format:persistent

4.urn:oasis:names:tc:SAML:2.0:nameid-format:transient

are format for the Name Identifiers.

The name format for a transient ID in SAML 1 is urn:mace:shibboleth:1.0:nameIdentifier and in SAML 2 is urn:oasis:names:tc:SAML:2.0:nameid-format:transient

Transient is for [section 8.3.8 of SAML Core]

Indicates that the content of the element is an identifier with transient semantics and SHOULD be treated as an opaque and temporary value by the relying party.

Unspecified can be used and it purely depends on the entities implementation on their own wish.

Best Practices for mapping one object to another

/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
    Type T1 = sourceObj.GetType();
    Type T2 = targetObj.GetType();

    PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
    PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);

   foreach (var sourceProp in sourceProprties)
   {
       object osourceVal = sourceProp.GetValue(sourceObj, null);
       int entIndex = Array.IndexOf(targetProprties, sourceProp);
       if (entIndex >= 0)
       {
           var targetProp = targetProprties[entIndex];
           targetProp.SetValue(targetObj, osourceVal);
       }
   }
}

Getting the IP address of the current machine using Java

private static InetAddress getLocalAddress(){
        try {
            Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
            while( b.hasMoreElements()){
                for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses())
                    if ( f.getAddress().isSiteLocalAddress())
                        return f.getAddress();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

Multiple returns from a function

Some might prefer returning multiple values as object:

function test() {
    $object = new stdClass();

    $object->x = 'value 1';
    $object->y = 'value 2';

    return $object;
}

And call it like this:

echo test()->x;

Or:

$test = test();
echo $test->y;

How to remove index.php from URLs?

Follow the below steps it will helps you.

step 1: Go to to your site root folder and you can find the .htaccess file there. Open it with a text editor and find the line #RewriteBase /magento/. Just replace it with #RewriteBase / take out just the 'magento/'

step 2: Then go to your admin panel and enable the Rewrites(set yes for Use Web Server Rewrites). You can find it at System->Configuration->Web->Search Engine Optimization.

step 3: Then go to Cache management page (system cache management ) and refresh your cache and refresh to check the site.

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

The best way to do that programmatically is using the next method:

public static DigitsKeyListener getInstance (boolean sign, boolean decimal) 

Returns a DigitsKeyListener that accepts the digits 0 through 9, plus the minus sign (only at the beginning) and/or decimal point (only one per field) if specified.

This solve the problem about the many '.' in EditText

editText.setKeyListener(DigitsKeyListener.getInstance(true,true)); // decimals and positive/negative numbers. 

editText.setKeyListener(DigitsKeyListener.getInstance(false,true)); // positive decimals numbers. 

editText.setKeyListener(DigitsKeyListener.getInstance(false,false)); // positive integer numbers.

editText.setKeyListener(DigitsKeyListener.getInstance(true,false)); // positive/negative integer numbers.

Java compiler level does not match the version of the installed Java project facet

If using eclipse,

Under.settings click on org.eclipse.wst.common.project.facet.core.xml

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <installed facet="java" version="1.7"/>
</faceted-project>

Change the version to the correct version.

How can I import a database with MySQL from terminal?

Preferable way for windows:

  1. Open the console and start the interactive MySQL mode

  2. use <name_of_your_database>;

  3. source <path_of_your_.sql>

SQLite: How do I save the result of a query as a CSV file?

All the existing answers only work from the sqlite command line, which isn't ideal if you'd like to build a reusable script. Python makes it easy to build a script that can be executed programatically.

import pandas as pd
import sqlite3

conn = sqlite3.connect('your_cool_database.sqlite')

df = pd.read_sql('SELECT * from orders', conn)
df.to_csv('orders.csv', index = False)

You can customize the query to only export part of the sqlite table to the CSV file.

You can also run a single command to export all sqlite tables to CSV files:

for table in c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
    t = table[0]
    df = pd.read_sql('SELECT * from ' + t, conn)
    df.to_csv(t + '_one_command.csv', index = False)

See here for more info.

.htaccess - how to force "www." in a generic way?

This won't work with subdomains.

domain.com correctly gets redirected to www.domain.com

but

images.domain.com gets redirected to www.images.domain.com

Instead of checking if the subdomain is "not www", check if there are two dots:

RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ HTTP%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Count characters in textarea

I created my own jQuery plugin for this task, you can try it out here:

http://jsfiddle.net/Sk8erPeter/8NF4r/

You can create character counters on-the-fly (and also remaining character counters), you can define whether you want to chop text, you can define the suffix texts and you can also define a short format and its separator.

Here's an example usage:

$(document).ready(function () {

    $('#first_textfield').characterCounter();

    $('#second_textfield').characterCounter({
        maximumCharacters: 20,
        chopText: true
    });

    $('#third_textfield').characterCounter({
        maximumCharacters: 20,
        shortFormat: true,
        shortFormatSeparator: " / ",
        positionBefore: true,
        chopText: true
    });

    $('#fourth_textfield').characterCounter({
        maximumCharacters: 20,
        characterCounterNeeded: true,
        charactersRemainingNeeded: true,
        chopText: false
    });

    $('#first_textarea').characterCounter({
        maximumCharacters: 50,
        characterCounterNeeded: true,
        charactersRemainingNeeded: false,
        chopText: true
    });

    $('#second_textarea').characterCounter({
        maximumCharacters: 25
    });

});

Here's the code of the plugin:

/**
 * Character counter and limiter plugin for textfield and textarea form elements
 * @author Sk8erPeter
 */ 
(function ($) {
  $.fn.characterCounter = function (params) {
    // merge default and user parameters
    params = $.extend({
      // define maximum characters
      maximumCharacters: 1000,
      // create typed character counter DOM element on the fly
      characterCounterNeeded: true,
      // create remaining character counter DOM element on the fly
      charactersRemainingNeeded: true,
      // chop text to the maximum characters
      chopText: false,
      // place character counter before input or textarea element
      positionBefore: false,
      // class for limit excess
      limitExceededClass: "character-counter-limit-exceeded",
      // suffix text for typed characters
      charactersTypedSuffix: " characters typed",
      // suffix text for remaining characters
      charactersRemainingSuffixText: " characters left",
      // whether to use the short format (e.g. 123/1000)
      shortFormat: false,
      // separator for the short format
      shortFormatSeparator: "/"
    }, params);

    // traverse all nodes
    this.each(function () {
      var $this = $(this),
        $pluginElementsWrapper,
        $characterCounterSpan,
        $charactersRemainingSpan;

      // return if the given element is not a textfield or textarea
      if (!$this.is("input[type=text]") && !$this.is("textarea")) {
        return this;
      }

      // create main parent div
      if (params.characterCounterNeeded || params.charactersRemainingNeeded) {
        // create the character counter element wrapper
        $pluginElementsWrapper = $('<div>', {
          'class': 'character-counter-main-wrapper'
        });

        if (params.positionBefore) {
          $pluginElementsWrapper.insertBefore($this);
        } else {
          $pluginElementsWrapper.insertAfter($this);
        }
      }

      if (params.characterCounterNeeded) {
        $characterCounterSpan = $('<span>', {
          'class': 'counter character-counter',
          'text': 0
        });

        if (params.shortFormat) {
          $characterCounterSpan.appendTo($pluginElementsWrapper);

          var $shortFormatSeparatorSpan = $('<span>', {
            'html': params.shortFormatSeparator
          }).appendTo($pluginElementsWrapper);

        } else {
          // create the character counter element wrapper
          var $characterCounterWrapper = $('<div>', {
            'class': 'character-counter-wrapper',
            'html': params.charactersTypedSuffix
          });

          $characterCounterWrapper.prepend($characterCounterSpan);
          $characterCounterWrapper.appendTo($pluginElementsWrapper);
        }
      }

      if (params.charactersRemainingNeeded) {

        $charactersRemainingSpan = $('<span>', {
          'class': 'counter characters-remaining',
          'text': params.maximumCharacters
        });

        if (params.shortFormat) {
          $charactersRemainingSpan.appendTo($pluginElementsWrapper);
        } else {
          // create the character counter element wrapper
          var $charactersRemainingWrapper = $('<div>', {
            'class': 'characters-remaining-wrapper',
            'html': params.charactersRemainingSuffixText
          });
          $charactersRemainingWrapper.prepend($charactersRemainingSpan);
          $charactersRemainingWrapper.appendTo($pluginElementsWrapper);
        }
      }

      $this.keyup(function () {

        var typedText = $this.val();
        var textLength = typedText.length;
        var charactersRemaining = params.maximumCharacters - textLength;

        // chop the text to the desired length
        if (charactersRemaining < 0 && params.chopText) {
          $this.val(typedText.substr(0, params.maximumCharacters));
          charactersRemaining = 0;
          textLength = params.maximumCharacters;
        }

        if (params.characterCounterNeeded) {
          $characterCounterSpan.text(textLength);
        }

        if (params.charactersRemainingNeeded) {
          $charactersRemainingSpan.text(charactersRemaining);

          if (charactersRemaining <= 0) {
            if (!$charactersRemainingSpan.hasClass(params.limitExceededClass)) {
              $charactersRemainingSpan.addClass(params.limitExceededClass);
            }
          } else {
            $charactersRemainingSpan.removeClass(params.limitExceededClass);
          }
        }
      });

    });

    // allow jQuery chaining
    return this;

  };
})(jQuery);

Floating Div Over An Image

Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:

_x000D_
_x000D_
    .container {_x000D_
       border: 1px solid #DDDDDD;_x000D_
       width: 200px;_x000D_
       height: 200px;_x000D_
       position: relative;_x000D_
    }_x000D_
    .tag {_x000D_
       float: left;_x000D_
       position: absolute;_x000D_
       left: 0px;_x000D_
       top: 0px;_x000D_
       z-index: 1000;_x000D_
       background-color: #92AD40;_x000D_
       padding: 5px;_x000D_
       color: #FFFFFF;_x000D_
       font-weight: bold;_x000D_
    }
_x000D_
<div class="container">_x000D_
       <div class="tag">Featured</div>_x000D_
       <img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The key is the container has to be positioned relative and the tag positioned absolute.

Find the nth occurrence of substring in a string

Avoid a failure or incorrect output when the input value for occurrence provided is higher than the actual count of occurrence. For example, in a string 'overflow' if you would check the 3rd occurrence of 'o' ( it has only 2 occurrences ) then below code will return a warning or message indicating that the occurrence value has exceeded.

Input Occurrence entered has exceeded the actual count of Occurrence.

def check_nth_occurrence (string, substr, n):

## Count the Occurrence of a substr
    cnt = 0
    for i in string:
        if i ==substr:
            cnt = cnt + 1
        else:
            pass

## Check if the Occurrence input has exceeded the actual count of Occurrence

    if n > cnt:
        print (f' Input Occurrence entered has exceeded the actual count of Occurrence')
        return

## Get the Index value for first Occurrence of the substr

   index = string.find(substr)

## Get the Index value for nth Occurrence of Index
    while index >= 0 and n > 1:
        index = string.find(substr, index+ 1)
        n -= 1
  return index

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

How can I force division to be floating point? Division keeps rounding down to 0?

How can I force division to be floating point in Python?

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.

How can I force c to be a floating point number in Python in the following?

c = a / b

What is really being asked here is:

"How do I force true division such that a / b will return a fraction?"

Upgrade to Python 3

In Python 3, to get true division, you simply do a / b.

>>> 1/2
0.5

Floor division, the classic division behavior for integers, is now a // b:

>>> 1//2
0
>>> 1//2.0
0.0

However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.

If Using Python 2

In Python 2, it's not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.

Recommendation for Python 2

You can get Python 3 division behavior in any given module with the following import at the top:

from __future__ import division

which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:

>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0

This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.

Other Options for Python 2

If you don't want to apply this to the entire module, you're limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:

>>> 1/(2 * 1.0)
0.5

Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it's a function call:

>>> from operator import truediv
>>> truediv(1, 2)
0.5

Not Recommended for Python 2

Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.

>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

It doesn't make much sense to me to purposefully make your code more brittle.

You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don't recommend this except for testing. But to demonstrate:

$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j

Java, List only subdirectories from a directory, not files

@Mohamed Mansour you were almost there... the "dir" argument from that you were using is actually the curent path, so it will always return true. In order to see if the child is a subdirectory or not you need to test that child.

File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));

Issue with virtualenv - cannot activate

  1. Open your project using VS code editor .
  2. Change the default shell in vs code terminal to git bash.

  3. now your project is open with bash console and right path, put "source venv\Scripts\activate" in Windows

Maven: add a dependency to a jar by relative path

This is another method in addition to my previous answer at Can I add jars to maven 2 build classpath without installing them?

This will get around the limit when using multi-module builds especially if the downloaded JAR is referenced in child projects outside of the parent. This also reduces the setup work by creating the POM and the SHA1 files as part of the build. It also allows the file to reside anywhere in the project without fixing the names or following the maven repository structure.

This uses the maven-install-plugin. For this to work, you need to set up a multi-module project and have a new project representing the build to install files into the local repository and ensure that one is first.

You multi-module project pom.xml would look like this:

<packaging>pom</packaging>
<modules>
<!-- The repository module must be first in order to ensure
     that the local repository is populated -->
    <module>repository</module>
    <module>... other modules ...</module>
</modules>

The repository/pom.xml file will then contain the definitions to load up the JARs that are part of your project. The following are some snippets of the pom.xml file.

<artifactId>repository</artifactId>
<packaging>pom</packaging>

The pom packaging prevents this from doing any tests or compile or generating any jar file. The meat of the pom.xml is in the build section where the maven-install-plugin is used.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <executions>
                <execution>
                        <id>com.ibm.db2:db2jcc</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>install-file</goal>
                        </goals>
                        <configuration>
                            <groupId>com.ibm.db2</groupId>
                            <artifactId>db2jcc</artifactId>
                            <version>9.0.0</version>
                            <packaging>jar</packaging>
                            <file>${basedir}/src/jars/db2jcc.jar</file>
                            <createChecksum>true</createChecksum>
                            <generatePom>true</generatePom>
                        </configuration>
                </execution>
                <execution>...</execution>
            </executions>
        </plugin>
    </plugins>
</build>

To install more than one file, just add more executions.

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

Change visibility of ASP.NET label with JavaScript

If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.

How can I reduce the waiting (ttfb) time

If you are using PHP, try using <?php flush(); ?> after </head> and before </body> or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.

More info

HTML5 placeholder css padding

I had a problem, which appears just in internet explorer. Input field was styled

height:38px;
line-height:38px;

Unfortunately in IE the initial placeholder appears not at the correct position. But when I have clicked into the field and then left this field, the placeholder appeared on the right position.

My solution was to set:

line-height:normal;

how can I enable PHP Extension intl?

If the below line is not available or commented in C:\xampp\php\php.ini, then add it or uncomment and restart the apache server then it works.

extension=php_intl.dll

How to write a PHP ternary operator

Since this would be a common task I would suggest wrapping a switch/case inside of a function call.

function getVocationName($vocation){
    switch($vocation){
        case 1: return "Sorcerer";
        case 2: return 'Druid';
        case 3: return 'Paladin';
        case 4: return 'Knight';
        case 5: return 'Master Sorcerer';
        case 6: return 'Elder Druid';
        case 7: return 'Royal Paladin';
        default: return 'Elite Knight';
    }
}

echo getVocationName($result->vocation);

What is the difference between utf8mb4 and utf8 charsets in MySQL?

Taken from the MySQL 8.0 Reference Manual:

  • utf8mb4: A UTF-8 encoding of the Unicode character set using one to four bytes per character.

  • utf8mb3: A UTF-8 encoding of the Unicode character set using one to three bytes per character.

In MySQL utf8 is currently an alias for utf8mb3 which is deprecated and will be removed in a future MySQL release. At that point utf8 will become a reference to utf8mb4.

So regardless of this alias, you can consciously set yourself an utf8mb4 encoding.

To complete the answer, I'd like to add the @WilliamEntriken's comment below (also taken from the manual):

To avoid ambiguity about the meaning of utf8, consider specifying utf8mb4 explicitly for character set references instead of utf8.

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

Launch Pycharm from command line (terminal)

Steps for someone using zsh on Mac:

  1. emacs ~/.zshrc&
  2. Put this in zshrc---> alias pycharm="/Applications/PyCharm\CE.app/Contents/MacOS/pycharm"
  3. source ~/.zshrc
  4. Launch by typing pycharm in command window

Check if one list contains element from the other

org.springframework.util.CollectionUtils

boolean containsAny(java.util.Collection<?> source, java.util.Collection<?> candidates)

Return true if any element in 'candidates' is contained in 'source'; otherwise returns false

jQuery $(document).ready and UpdatePanels?

When $(document).ready(function (){...}) not work after page post back then use JavaScript function pageLoad in Asp.page as follow:

<script type="text/javascript" language="javascript">
function pageLoad() {
// Initialization code here, meant to run once. 
}
</script>

Is it possible to make desktop GUI application in .NET Core?

I'm working on a project that might help: https://github.com/gkmo/CarloSharp

The following application is written in .NET with the UI in HTML, JavaScript, and CSS (Angular).

Enter image description here