Programs & Examples On #Exploratory

Exploratory Testing - Comes under Session Based testing where every member of QA team needs to explore/test different scenarios through which the system can be broken.

Autoreload of modules in IPython

For IPython version 3.1, 4.x, and 5.x

%load_ext autoreload
%autoreload 2

Then your module will be auto-reloaded by default. This is the doc:

File:       ...my/python/path/lib/python2.7/site-packages/IPython/extensions/autoreload.py

Docstring:
``autoreload`` is an IPython extension that reloads modules
automatically before executing the line of code typed.

This makes for example the following workflow possible:

.. sourcecode:: ipython

   In [1]: %load_ext autoreload

   In [2]: %autoreload 2

   In [3]: from foo import some_function

   In [4]: some_function()
   Out[4]: 42

   In [5]: # open foo.py in an editor and change some_function to return 43

   In [6]: some_function()
   Out[6]: 43

The module was reloaded without reloading it explicitly, and the
object imported with ``from foo import ...`` was also updated.

There is a trick: when you forget all of the above when using ipython, just try:

import autoreload
?autoreload
# Then you get all the above

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

Listing available com ports with Python

Several options are available:

Call QueryDosDevice with a NULL lpDeviceName to list all DOS devices. Then use CreateFile and GetCommConfig with each device name in turn to figure out whether it's a serial port.

Call SetupDiGetClassDevs with a ClassGuid of GUID_DEVINTERFACE_COMPORT.

WMI is also available to C/C++ programs.

There's some conversation on the win32 newsgroup and a CodeProject, er, project.

Removing whitespace between HTML elements when using line breaks

You could use comments.

 <img src="..." alt="..."><!--
 --><img src="..." alt="..."><!--
 --><img src="..." alt="..."><!--
 --><img src="..." alt="...">

I'd worry about the semantics of having a series of images side by side though.

How to convert buffered image to image and vice-versa?

Just an information: let us all remember that the Image class is actually an abstract class and referencing a variable of this with a BufferedImage only stores or returns any Object's memory adress.

Also, wherefore, static java.awt.image.imageIO's read() method returns a BufferedImage object, therefore no doubt that using operator/expression instanceof BufferedImage on that object will return true.

In fact, being abstract, Image class has such method signatures as:

  1. public abstract Graphics getGraphics()
  2. public abstract ImageProducer getSource()

among others.

I emphasize, an actual Image variable only holds memory adress of a concrete Image-subclass object, almost like pointers in C, C++, Ada, etc.

If you're introduced or advanced in those languages, and also of Java interface instances like Runnable, javax.sound.Clip, AWT's Shape, etc.. . Take note that Image has: public abstract Image getScaledInstance(...) - you get the point. (Of course, scaling in 2D Graphics programming is interchangeable to resizing, for which precision is desirable).

But in an impossible case when herein ImageIO method return ! (instanceof BufferedImage) just create a new BufferedImage object with this ImgObjNotInstncfBufImg apassed to one of its constructor argument. Then, at (rational) will manipulate this in the logic of your code.

Anyways, the Affine Transform class is appropriate for transforming Shapes and Images to thier scaled, rotated, relocated, etc forms, so I recommend you to study about using an "affine transform".

Take note that you can manipulate the actual pixels in such Image's Raster - well another technical 2D Graphics jargon which must be referenced from a technical glossary - which perhaps a excercised skill in Java ways of binary blitwise operations will be needed, in types of Image buffers that store individual color attributes in a compact in of 32-bytes - 7-bits each for the alpha and RGB values.

I suspect your gonna use it in layering images. So, FINALLY, the rational is that you only reference BufferedImage with the abstract Image, and if ever your Image object isn't a BufferedImage one yet, then you can just make an image out of this related-but-non-BufferedImage-instance without having to worry about any conversion, casting, autoboxing or whatever; manipulating a BufferedImage really means manipulating also the underlying root Image data-bearing object that it points to.

Okay, finished; I think I certainly extracted and splintered out what deadlock you may have thought you are facing to. As I have said abstract classes in java, and also interfaces, are very much the equivaleng of the low-level, more-close-to-hardware operators called pointers in other languages.

How do I check for equality using Spark Dataframe without SQL Query?

We can write multiple Filter/where conditions in Dataframe.

For example:

table1_df
.filter($"Col_1_name" === "buddy")  // check for equal to string
.filter($"Col_2_name" === "A")
.filter(not($"Col_2_name".contains(" .sql")))  // filter a string which is    not relevent
.filter("Col_2_name is not null")   // no null filter
.take(5).foreach(println)

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

Read XML file using javascript

You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.

<script type="text/javascript">

function readXml(xmlFile){

var xmlDoc;

if(typeof window.DOMParser != "undefined") {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",xmlFile,false);
    if (xmlhttp.overrideMimeType){
        xmlhttp.overrideMimeType('text/xml');
    }
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
}
else{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.load(xmlFile);
}
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>

How to customize the configuration file of the official PostgreSQL Docker image?

My solution is for colleagues who needs to make changes in config before launching docker-entrypoint-initdb.d

I was needed to change 'shared_preload_libraries' setting so during it's work postgres already has new library preloaded and code in docker-entrypoint-initdb.d can use it.

So I just patched postgresql.conf.sample file in Dockerfile:

RUN echo "shared_preload_libraries='citus,pg_cron'" >> /usr/share/postgresql/postgresql.conf.sample
RUN echo "cron.database_name='newbie'" >> /usr/share/postgresql/postgresql.conf.sample

And with this patch it become possible to add extension in .sql file in docker-entrypoint-initdb.d/:

CREATE EXTENSION pg_cron;

What is Dependency Injection?

This is the most simple explanation about Dependency Injection and Dependency Injection Container I have ever seen:

Without Dependency Injection

  • Application needs Foo (e.g. a controller), so:
  • Application creates Foo
  • Application calls Foo
    • Foo needs Bar (e.g. a service), so:
    • Foo creates Bar
    • Foo calls Bar
      • Bar needs Bim (a service, a repository, …), so:
      • Bar creates Bim
      • Bar does something

With Dependency Injection

  • Application needs Foo, which needs Bar, which needs Bim, so:
  • Application creates Bim
  • Application creates Bar and gives it Bim
  • Application creates Foo and gives it Bar
  • Application calls Foo
    • Foo calls Bar
      • Bar does something

Using a Dependency Injection Container

  • Application needs Foo so:
  • Application gets Foo from the Container, so:
    • Container creates Bim
    • Container creates Bar and gives it Bim
    • Container creates Foo and gives it Bar
  • Application calls Foo
    • Foo calls Bar
      • Bar does something

Dependency Injection and dependency Injection Containers are different things:

  • Dependency Injection is a method for writing better code
  • a DI Container is a tool to help injecting dependencies

You don't need a container to do dependency injection. However a container can help you.

How do I debug Windows services in Visual Studio?

Debug a Windows Service over http (tested with VS 2015 Update 3 and .Net FW 4.6)

Firstly, you have to create a Console Project within your VS Solution(Add -> New Project -> Console Application).

Within the new project, create a class "ConsoleHost" with that code:

class ConsoleHost : IDisposable
{
    public static Uri BaseAddress = new Uri(http://localhost:8161/MyService/mex);
    private ServiceHost host;

    public void Start(Uri baseAddress)
    {
        if (host != null) return;

        host = new ServiceHost(typeof(MyService), baseAddress ?? BaseAddress);

        //binding
        var binding = new BasicHttpBinding()
        {
            Name = "MyService",
            MessageEncoding = WSMessageEncoding.Text,
            TextEncoding = Encoding.UTF8,
            MaxBufferPoolSize = 2147483647,
            MaxBufferSize = 2147483647,
            MaxReceivedMessageSize = 2147483647
        };

        host.Description.Endpoints.Clear();
        host.AddServiceEndpoint(typeof(IMyService), binding, baseAddress ?? BaseAddress);

        // Enable metadata publishing.
        var smb = new ServiceMetadataBehavior
        {
            HttpGetEnabled = true,
            MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 },
        };

        host.Description.Behaviors.Add(smb);

        var defaultBehaviour = host.Description.Behaviors.OfType<ServiceDebugBehavior>().FirstOrDefault();
        if (defaultBehaviour != null)
        {
            defaultBehaviour.IncludeExceptionDetailInFaults = true;
        }

        host.Open();
    }

    public void Stop()
    {
        if (host == null)
            return;

        host.Close();
        host = null;
    }

    public void Dispose()
    {
        this.Stop();
    }
}

And this is the code for the Program.cs class:

public static class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        var baseAddress = new Uri(http://localhost:8161/MyService);
        var host = new ConsoleHost();
        host.Start(null);
        Console.WriteLine("The service is ready at {0}", baseAddress);
        Console.WriteLine("Press <Enter> to stop the service.");
        Console.ReadLine();
        host.Stop();
    }
}

Configurations such as connectionstrings should be copied in the App.config file of the Console project.

To sturt up the console, righ-click on Console project and click Debug -> Start new instance.

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

I have a struct KeyValuePairSerializable:

[Serializable]
public struct KeyValuePairSerializable<K, V>
{
    public KeyValuePairSerializable(KeyValuePair<K, V> pair)
    {
        Key = pair.Key;
        Value = pair.Value;
    }

    [XmlAttribute]
    public K Key { get; set; }

    [XmlText]
    public V Value { get; set; }

    public override string ToString()
    {
        return "[" + StringHelper.ToString(Key, "") + ", " + StringHelper.ToString(Value, "") + "]";
    }
}

Then, the XML serialization of a Dictionary property is by:

[XmlIgnore]
public Dictionary<string, string> Parameters { get; set; }

[XmlArray("Parameters")]
[XmlArrayItem("Pair")]
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // not necessary
public KeyValuePairSerializable<string, string>[] ParametersXml
{
    get 
    { 
        return Parameters?.Select(p => new KeyValuePairSerializable<string, string>(p)).ToArray(); 
    }
    set
    {
        Parameters = value?.ToDictionary(i => i.Key, i => i.Value);
    }
}

Just the property must be the array, not the List.

else & elif statements not working in Python

indentation is important in Python. Your if else statement should be within triple arrow (>>>), In Mac python IDLE version 3.7.4 elif statement doesn't comes with correct indentation when you go on next line you have to shift left to avoid syntax error.

enter image description here

Constructor in an Interface?

Dependencies that are not referenced in an interfaces methods should be regarded as implementation details, not something that the interface enforces. Of course there can be exceptions, but as a rule, you should define your interface as what the behavior is expected to be. Internal state of a given implementation shouldn't be a design concern of the interface.

Error importing Seaborn module in Python

I had faced the same problem. Restarting the notebook solved my problem.

If that doesn't solve the problem, you can try this

pip install seaborn

Edit

As few people have posted in the comments, you can also use

python -m pip install seaborn

Plus, as per https://bugs.python.org/issue22295 it is a better way because in this case, you can specify which version of python (python3 or python2) to use for running pip

Chrome: Uncaught SyntaxError: Unexpected end of input

This particular error is one annoying fact about . In most cases your JavaScript is broken in some way. For example missing a } or something like that.

Example given, this will yield "Unexpected end of input" too:

eval('[{"test": 4}') // notice the missing ]

But the root cause of the problems seems to be that the requested JSON url has a Content-Type of text/html which Chrome apparently tries to parse as HTML, which then results in the unexpected end of input due to the fact that the included image tags are being parsed.

Try setting the Content-Type to text/plain I think it should fix the issues.

Nonetheless, V8 could do a better Job about telling one exactly where the input ended unexpectedly.

Getting the thread ID from a thread

You can use the deprecated AppDomain.GetCurrentThreadId to get the ID of the currently running thread. This method uses a PInvoke to the Win32 API method GetCurrentThreadID, and will return the Windows thread ID.

This method is marked as deprecated because the .NET Thread object does not correspond to a single Windows thread, and as such there is no stable ID which can be returned by Windows for a given .NET thread.

See configurator's answer for more reasons why this is the case.

Convert a date format in epoch

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds.

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

What is the difference between sed and awk?

Both tools are meant to work with text and there are tasks both tools can be used for.

For me the rule to separate them is: Use sed to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.

Also you should not forget about grep. Use grep if you only want to search/extract something in a text (file)

Resize jqGrid when browser is resized?

Hello Stack overflow enthusiasts. I enjoyed most of answers, and I even up-voted a couple, but none of them worked for me on IE 8 for some strange reason... I did however run into these links... This guy wrote a library that seems to work. Include it in your projects in adittion to jquery UI, throw in the name of your table and the div.

http://stevenharman.net/blog/archive/2009/08/21/creating-a-fluid-jquery-jqgrid.aspx

http://code.google.com/p/codeincubator/source/browse/#svn%2FSamples%2Fsteveharman%2FjQuery%2Fjquery.jqgrid.fluid%253Fstate%253Dclosed

Java: Convert a String (representing an IP) to InetAddress

Simply call InetAddress.getByName(String host) passing in your textual IP address.

From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

InetAddress javadoc

Android Studio Image Asset Launcher Icon Background Color

I'm using Android Studio 3.0.1 and if the above answer doesn't work for you, try to change the icon type into Legacy and select Shape to None, the default one is Adaptive and Legacy.

enter image description here

Note: Some device has installed a launcher with automatically adding white background in icon, that's normal.

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

Use int() on a boolean test:

x = int(x == 'true')

int() turns the boolean into 1 or 0. Note that any value not equal to 'true' will result in 0 being returned.

Counting unique values in a column in pandas dataframe like in Qlik?

you can use unique property by using len function

len(df['hID'].unique()) 5

Can’t delete docker image with dependent child images

What worked to me was to use the REPOSITORY:TAG combination rather than IMAGE ID.

When I tried to delete a docker image with the command docker rmi <IMAGE ID> with no containers associated with this image I had the message:

$ docker rmi 3f66bec2c6bf
Error response from daemon: conflict: unable to delete 3f66bec2c6bf (cannot be forced) - image has dependent child images

I could delete with success when I used the command docker rmi RPOSITORY:TAG

$ docker rmi ubuntu:18.04v1
Untagged: ubuntu:18.04v1

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Paste in insert mode?

You can also use the mouse middle button to paste in insert mode (Linux only).

JWT refresh token flow

Based in this implementation with Node.js of JWT with refresh token:

1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

Python: Find index of minimum item in list of floats

Use of the argmin method for numpy arrays.

import numpy as np
np.argmin(myList)

However, it is not the fastest method: it is 3 times slower than OP's answer on my computer. It may be the most concise one though.

Accessing a resource via codebehind in WPF

You may also use this.Resources["mykey"]. I guess that is not much better than your own suggestion.

Bootstrap 3 Horizontal and Vertical Divider

I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)

Fiddle: https://jsfiddle.net/tqmfpwhv/1/


css based on OP information, media query at end is for med & lg view.

.vr-all {
    padding:0px;
    border-right:1px solid #CC0000;
}
.vr-xs {
    padding:0px;
}
.vr-md {
    padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
    border-color: #CC0000;
    border-style: solid;
    border-bottom: 1px;
    margin:0px;
    padding:0px;
}
/* for medium and up */
@media(min-width:992px){
    .vr-xs {
        border-right:1px solid #CC0000;
    }
    }

html adjustments to OP provided code. Red border and Img links for example.

<div class="container">
  <div class="row">
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
            <h5>Rich Media Ad Production</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
            <h5>Web Design & Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for only x-small/small viewports -->
        <div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
            <h5>Mobile Apps Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
            <h5>Creative Design</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for for all viewports -->
        <div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
            <h5>Web Analytics</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
            <h5>Search Engine Marketing</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for only x-small/small viewports -->
        <div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
            <h5>Mobile Apps Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
            <h5>Quality Assurance</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>


    </div>
</div>

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

VBA Date as integer

You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)

How do you test a public/private DSA keypair?

I found a way that seems to work better for me:

ssh-keygen -y -f <private key file>

That command will output the public key for the given private key, so then just compare the output to each *.pub file.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Where should I put the CSS and Javascript code in an HTML webpage?

You should put it in the <head>. I typically put style references above JS and I order my JS from top to bottom if some of them are dependent on others, but I beleive all of the references are loaded before the page is rendered.

C# Telnet Library

I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.

You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh

You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

I just did it like this:

<a href="@Url.Action("Index","Home")#features">Features</a>

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

How to set and reference a variable in a Jenkinsfile

We got around this by adding functions to the environment step, i.e.:

environment {
    ENVIRONMENT_NAME = defineEnvironment() 
}
...
def defineEnvironment() {
    def branchName = "${env.BRANCH_NAME}"
    if (branchName == "master") {
        return 'staging'
    }
    else {
        return 'test'
    }
}

Pass Javascript Array -> PHP

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

C# Return Different Types?

Marc's answer should be the correct one, but in .NET 4 you couldn't also go with dynamic type.

This should be used only if you have no control over the classes you return and there are no common ancestors ( usually with interop ) and only if not using dynamic is a lot more painful then using(casting every object in every step :) ).

Few blog post trying to explain when to use dynamic: http://blogs.msdn.com/b/csharpfaq/archive/tags/dynamic/

public dynamic GetSomething()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio(); 
     return // anyobject

}

git revert back to certain commit

http://www.kernel.org/pub/software/scm/git/docs/git-revert.html

using git revert <commit> will create a new commit that reverts the one you dont want to have.

You can specify a list of commits to revert.

An alternative: http://git-scm.com/docs/git-reset

git reset will reset your copy to the commit you want.

Converting bool to text in C++

Use boolalpha to print bool to string.

std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;

C++ Reference

How to find controls in a repeater header or footer

This is in VB.NET, just translate to C# if you need it:

<Extension()>
Public Function FindControlInRepeaterHeader(Of T As Control)(obj As Repeater, ControlName As String) As T
    Dim ctrl As T = TryCast((From item As RepeaterItem In obj.Controls
                   Where item.ItemType = ListItemType.Header).SingleOrDefault.FindControl(ControlName),T)
    Return ctrl
End Function

And use it easy:

Dim txt as string = rptrComentarios.FindControlInRepeaterHeader(Of Label)("lblVerTodosComentarios").Text

Try to make it work with footer, and items controls too =)

What is the easiest way to push an element to the beginning of the array?

What about using the unshift method?

ary.unshift(obj, ...) ? ary
Prepends objects to the front of self, moving other elements upwards.

And in use:

irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"

How to create two columns on a web page?

The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.

  • They perform better than CSS
  • They work on all browsers without any fuss
  • You can debug them easily with the border=1 attribute

How do I pass JavaScript values to Scriptlet in JSP?

If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.

Other wise you can't do it.

Convert string to ASCII value python

If you are using python 3 or above,

>>> list(bytes(b'test'))
[116, 101, 115, 116]

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

Find by key deep in a nested array

I found this page through googling for the similar functionalities. Based on the work provided by Zach and regularmike, I created another version which suits my needs.
BTW, teriffic work Zah and regularmike! I'll post the code here:

function findObjects(obj, targetProp, targetValue, finalResults) {

  function getObject(theObject) {
    let result = null;
    if (theObject instanceof Array) {
      for (let i = 0; i < theObject.length; i++) {
        getObject(theObject[i]);
      }
    }
    else {
      for (let prop in theObject) {
        if(theObject.hasOwnProperty(prop)){
          console.log(prop + ': ' + theObject[prop]);
          if (prop === targetProp) {
            console.log('--found id');
            if (theObject[prop] === targetValue) {
              console.log('----found porop', prop, ', ', theObject[prop]);
              finalResults.push(theObject);
            }
          }
          if (theObject[prop] instanceof Object || theObject[prop] instanceof Array){
            getObject(theObject[prop]);
          }
        }
      }
    }
  }

  getObject(obj);

}

What it does is it find any object inside of obj with property name and value matching to targetProp and targetValue and will push it to the finalResults array. And Here's the jsfiddle to play around: https://jsfiddle.net/alexQch/5u6q2ybc/

'Static readonly' vs. 'const'

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants

Short and clear MSDN reference here

jQuery append text inside of an existing paragraph tag

If you want to append text or html to span then you can do it as below.

$('p span#add_here').append('text goes here');

append will add text to span tag at the end.

to replace entire text or html inside of span you can use .text() or .html()

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

How do I delete from multiple tables using INNER JOIN in SQL server

You can take advantage of the "deleted" pseudo table in this example. Something like:

begin transaction;

   declare @deletedIds table ( id int );

   delete from t1
   output deleted.id into @deletedIds
   from table1 as t1
    inner join table2 as t2
      on t2.id = t1.id
    inner join table3 as t3
      on t3.id = t2.id;

   delete from t2
   from table2 as t2
    inner join @deletedIds as d
      on d.id = t2.id;

   delete from t3
   from table3 as t3 ...

commit transaction;

Obviously you can do an 'output deleted.' on the second delete as well, if you needed something to join on for the third table.

As a side note, you can also do inserted.* on an insert statement, and both inserted.* and deleted.* on an update statement.

EDIT: Also, have you considered adding a trigger on table1 to delete from table2 + 3? You'll be inside of an implicit transaction, and will also have the "inserted." and "deleted." pseudo-tables available.

Remove leading and trailing spaces?

You can use the strip() to remove trailing and leading spaces.

>>> s = '   abd cde   '
>>> s.strip()
'abd cde'

Note: the internal spaces are preserved

How do I set up curl to permanently use a proxy?

Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:

proxy = yourproxy.com:8080

Setting environment variable in react-native?

The simplest (not the best or ideal) solution I found was to use react-native-dotenv. You simply add the "react-native-dotenv" preset to your .babelrc file at the project root like so:

{
  "presets": ["react-native", "react-native-dotenv"]
}

Create a .env file and add properties:

echo "SOMETHING=anything" > .env

Then in your project (JS):

import { SOMETHING } from 'react-native-dotenv'
console.log(SOMETHING) // "anything"

How do you dismiss the keyboard when editing a UITextField

Programmatically set the delegate of the UITextField in swift 3

Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )

 lazy var firstNameTF: UITextField = {

    let firstname = UITextField()
    firstname.placeholder = "FirstName"
    firstname.frame = CGRect(x:38, y: 100, width: 244, height: 30)
    firstname.textAlignment = .center
    firstname.borderStyle = UITextBorderStyle.roundedRect
    firstname.keyboardType = UIKeyboardType.default
    firstname.delegate = self
    return firstname
}()

lazy var lastNameTF: UITextField = {

    let lastname = UITextField()
    lastname.placeholder = "LastName"
    lastname.frame = CGRect(x:38, y: 150, width: 244, height: 30)
    lastname.textAlignment = .center
    lastname.borderStyle = UITextBorderStyle.roundedRect
    lastname.keyboardType = UIKeyboardType.default
    lastname.delegate = self
    return lastname
}()

lazy var emailIdTF: UITextField = {

    let emailid = UITextField()
    emailid.placeholder = "EmailId"
    emailid.frame = CGRect(x:38, y: 200, width: 244, height: 30)
    emailid.textAlignment = .center
    emailid.borderStyle = UITextBorderStyle.roundedRect
    emailid.keyboardType = UIKeyboardType.default
    emailid.delegate = self
    return emailid
}()

// Mark:- handling delegate textField..

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if textField == firstNameTF {

        lastNameTF.becomeFirstResponder()
    }

    else if textField == lastNameTF {

        emailIdTF.becomeFirstResponder()
    }
    else {
        view.emailIdTF(true)
    }
    return true
}

What does "if (rs.next())" mean?

The next() method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:

Moves the cursor down one row from its current position.

This method return true if there's another row or false otherwise.

Matplotlib/pyplot: How to enforce axis range?

I tried all of those above answers, and I then summarized a pipeline of how to draw the fixed-axes image. It applied both to show function and savefig function.

  1. before you plot:

    fig = pylab.figure()
    ax = fig.gca()
    ax.set_autoscale_on(False)
    

This is to request an ax which is subplot(1,1,1).

  1. During the plot:

    ax.plot('You plot argument') # Put inside your argument, like ax.plot(x,y,label='test')
    ax.axis('The list of range') # Put in side your range [xmin,xmax,ymin,ymax], like ax.axis([-5,5,-5,200])
    
  2. After the plot:

    1. To show the image :

      fig.show()
      
    2. To save the figure :

      fig.savefig('the name of your figure')
      

I find out that put axis at the front of the code won't work even though I have set autoscale_on to False.

I used this code to create a series of animation. And below is the example of combing multiple fixed axes images into an animation. img

How to rollback just one step using rake db:migrate

If the version is 20150616132425, then use:

rails db:migrate:down VERSION=20150616132425

Get the IP Address of local computer

You cannot do that in Standard C++.

I'm posting this because it is the only correct answer. Your question asks how to do it in C++. Well, you can't do it in C++. You can do it in Windows, POSIX, Linux, Android, but all those are OS-specific solutions and not part of the language standard.

Standard C++ does not have a networking layer at all.

I assume you have this wrong assumption that C++ Standard defines the same scope of features as other language standards, Java. While Java might have built-in networking (and even a GUI framework) in the language's own standard library, C++ does not.

While there are third-party APIs and libraries which can be used by a C++ program, this is in no way the same as saying that you can do it in C++.

Here is an example to clarify what I mean. You can open a file in C++ because it has an fstream class as part of its standard library. This is not the same thing as using CreateFile(), which is a Windows-specific function and available only for WINAPI.

How to set CATALINA_HOME variable in windows 7?

Setting the JAVA_HOME, CATALINA_HOME Environment Variable on Windows

One can do using command prompt:

  1. set JAVA_HOME=C:\ "top level directory of your java install"
  2. set CATALINA_HOME=C:\ "top level directory of your Tomcat install"
  3. set PATH=%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

OR you can do the same:

  1. Go to system properties
  2. Go to environment variables and add a new variable with the name JAVA_HOME and provide variable value as C:\ "top level directory of your java install"
  3. Go to environment variables and add a new variable with the name CATALINA_HOME and provide variable value as C:\ "top level directory of your Tomcat install"
  4. In path variable add a new variable value as ;%CATALINA_HOME%\bin;

Dump a mysql database to a plaintext (CSV) backup from the command line

Check out mk-parallel-dump which is part of the ever-useful maatkit suite of tools. This can dump comma-separated files with the --csv option.

This can do your whole db without specifying individual tables, and you can specify groups of tables in a backupset table.

Note that it also dumps table definitions, views and triggers into separate files. In addition providing a complete backup in a more universally accessible form, it also immediately restorable with mk-parallel-restore

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

You can't create a new branch with this command

git checkout --track origin/branch

if you have changes that are not staged.

Here is example:

$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   src/App.js

no changes added to commit (use "git add" and/or "git commit -a")

// TRY TO CREATE:

$ git checkout --track origin/new-branch
fatal: 'origin/new-branch' is not a commit and a branch 'new-branch' cannot be created from it

However you can easily create a new branch with un-staged changes with git checkout -b command:

$ git checkout -b new-branch
Switched to a new branch 'new-branch'
M       src/App.js

How to prune local tracking branches that do not exist on remote anymore

If using Windows and Powershell, you can use the following to delete all local branches that have been merged into the branch currently checked out:

git branch --merged | ? {$_[0] -ne '*'} | % {$_.trim()} | % {git branch -d $_}

Explanation

  • Lists the current branch and the branches that have been merged into it
  • Filters out the current branch
  • Cleans up any leading or trailing spaces from the git output for each remaining branch name
  • Deletes the merged local branches

It's worth running git branch --merged by itself first just to make sure it's only going to remove what you expect it to.

(Ported/automated from http://railsware.com/blog/2014/08/11/git-housekeeping-tutorial-clean-up-outdated-branches-in-local-and-remote-repositories/.)

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

You can get just the edition name by using the following steps.

  • Open "SQL Server Configuration Manager"
  • From the List of SQL Server Services, Right Click on "SQL Server (Instance_name)" and Select Properties.
  • Select "Advanced" Tab from the Properties window.
  • Verify Edition Name from the "Stock Keeping Unit Name"
  • Verify Edition Id from the "Stock Keeping Unit Id"
  • Verify Service Pack from the "Service Pack Level"
  • Verify Version from the "Version"

screen shot

Password encryption/decryption code in .NET

Do not encrypt/decrypt passwords, that is a significant security vulnerability. HASH passwords, using a strong hash algorithm such as PBKDF2, bcrypt, scrypts, or Argon.

When the user sets their password, hash it, and store the hash (and salt).

When the user logs in, re-hash their provided password, and compare it to the hash in the database.

How to create image slideshow in html?

Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.

Here is the one I most liked.

http://www.zurb.com/playground/orbit-jquery-image-slider

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

After wasting so much time i got to know that there was mistake in my syntax to connect with DB. I was using colon ":" instead of slash "/".

(1) if you use sid below is the syntax to get connection:

**"jdbc:oracle:thin:@{hostname}:{port}:{SID}"**

(2) if you use service name, below is the syntax to get connection:

"**jdbc:oracle:thin:@//{hostname}:{port}/{servicename}**"

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

PHP Checking if the current date is before or after a set date

If you are looking for a generic way of doing this via MySQL, you could simply use a SELECT statement, and add the WHERE clause to it.

This will grab all fields for all rows, where the date stored in field "date" is before "now".

SELECT * FROM table WHERE UNIX_TIMESTAMP(`date`) < UNIX_TIMESTAMP()

Personally, I found this method to be more gentle on newbies in MySQL, since it uses the standard SELECT statement with WHERE to fetch the results. Obviously, you could grab only the fields relevant if you wanted to, by listing them instead of using a wildcard (*).

jQuery: Performing synchronous AJAX requests

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false,
        success: function (result) {
            /* if result is a JSon object */
            if (result.valid)
                return true;
            else
                return false;
        }
    });
}

Remove the last character from a string

An alternative to substr is the following, as a function:

substr_replace($string, "", -1)

Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.

C# : Converting Base Class to Child Class

I would recommend identifying the functionality you need from any subclasses, and make a generic method to cast into the right subclass.

I had this same problem, but really didn't feel like creating some mapping class or importing a library.

Let's say you need the 'Authenticate' method to take behavior from the right subclass. In your NetworkClient:

protected bool Authenticate(string username, string password) {
  //...
}
protected bool DoAuthenticate<T>(NetworkClient nc, string username, string password) where T : NetworkClient {
//Do a cast into the sub class.
  T subInst = (T) nc;
  return nc.Authenticate(username, password);
}

Marquee text in Android

Lots of answers correctly state that calling textView.setSelected(true) is required. However, if preferred to do so just via XML, one option could be to make use of the Binding Adapters when working with Data Binding.

So, just create a new adapter similar to:

@BindingAdapter("app:autoStartMarquee")
fun setAutoStartMarquee(textView: TextView, autoStartMarquee: Boolean) {
    textView.isSelected = autoStartMarquee
}

Then, you can simply use it in the XML as follows:

...
<TextView
    ...
    android:ellipsize="marquee"
    android:singleLine="true"
    app:autoStartMarquee="@{true}"/>
...

No need to call it from code anymore.

Wrapping text inside input type="text" element HTML/CSS

You can not use input for it, you need to use textarea instead. Use textarea with the wrap="soft"code and optional the rest of the attributes like this:

<textarea name="text" rows="14" cols="10" wrap="soft"> </textarea>

Atributes: To limit the amount of text in it for example to "40" characters you can add the attribute maxlength="40" like this: <textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40"></textarea> To hide the scroll the style for it. if you only use overflow:scroll; or overflow:hidden; or overflow:auto; it will only take affect for one scroll bar. If you want different attributes for each scroll bar then use the attributes like this overflow:scroll; overflow-x:auto; overflow-y:hidden; in the style area: To make the textarea not resizable you can use the style with resize:none; like this:

<textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40" style="overflow:hidden; resize:none;></textarea>

That way you can have or example a textarea with 14 rows and 10 cols with word wrap and max character length of "40" characters that works exactly like a input text box does but with rows instead and without using input text.

NOTE: textarea works with rows unlike like input <input type="text" name="tbox" size="10"></input> that is made to not work with rows at all.

How do I pull from a Git repository through an HTTP proxy?

You could too edit .gitconfig file located in %userprofile% directory on Windows system (notepad %userprofile%.gitconfig) or in ~ directory on Linux system (vi ~/.gitconfig) and add a http section as below.

Content of .gitconfig file :

[http]
        proxy = http://proxy.mycompany:80

How to debug (only) JavaScript in Visual Studio?

The debugger should automatically attach to the browser with Visual Studio 2012. You can use the debugger keyword to halt at a certain point in the application or use the breakpoints directly inside VS.

You can also detatch the default debugger in Visual Studio and use the Developer Tools which come pre loaded with Internet Explorer or FireBug etc.

To do this goto Visual Studio -> Debug -> Detatch All and then click Start debugging in Internet Explorer. You can then set breakpoints at this level. enter image description here

Get a file name from a path

m_szFilePath.MakeLower();
CFileFind finder;
DWORD buffSize = MAX_PATH;
char longPath[MAX_PATH];
DWORD result = GetLongPathName(m_szFilePath, longPath, MAX_PATH );

if( result == 0)
{
    m_bExists = FALSE;
    return;
}
m_szFilePath = CString(longPath);
m_szFilePath.Replace("/","\\");
m_szFilePath.Trim();
//check if it does not ends in \ => remove it
int length = m_szFilePath.GetLength();
if( length > 0 && m_szFilePath[length - 1] == '\\' )
{
    m_szFilePath.Truncate( length - 1 );
}
BOOL bWorking = finder.FindFile(this->m_szFilePath);
if(bWorking){
    bWorking = finder.FindNextFile();
    finder.GetCreationTime(this->m_CreationTime);
    m_szFilePath = finder.GetFilePath();
    m_szFileName = finder.GetFileName();

    this->m_szFileExtension = this->GetExtension( m_szFileName );

    m_szFileTitle = finder.GetFileTitle();
    m_szFileURL = finder.GetFileURL();
    finder.GetLastAccessTime(this->m_LastAccesTime);
    finder.GetLastWriteTime(this->m_LastWriteTime);
    m_ulFileSize = static_cast<unsigned long>(finder.GetLength());
    m_szRootDirectory = finder.GetRoot();
    m_bIsArchive = finder.IsArchived();
    m_bIsCompressed = finder.IsCompressed();
    m_bIsDirectory = finder.IsDirectory();
    m_bIsHidden = finder.IsHidden();
    m_bIsNormal = finder.IsNormal();
    m_bIsReadOnly = finder.IsReadOnly();
    m_bIsSystem = finder.IsSystem();
    m_bIsTemporary = finder.IsTemporary();
    m_bExists = TRUE;
    finder.Close();
}else{
    m_bExists = FALSE;
}

The variable m_szFileName contains the fileName.

What characters are forbidden in Windows and Linux directory names?

In Windows 10 (2019), the following characters are forbidden by an error when you try to type them:

A file name can't contain any of the following characters:

\ / : * ? " < > |

How to make "if not true condition"?

try

if ! grep -q sysa /etc/passwd ; then

grep returns true if it finds the search target, and false if it doesn't.

So NOT false == true.

if evaluation in shells are designed to be very flexible, and many times doesn't require chains of commands (as you have written).

Also, looking at your code as is, your use of the $( ... ) form of cmd-substitution is to be commended, but think about what is coming out of the process. Try echo $(cat /etc/passwd | grep "sysa") to see what I mean. You can take that further by using the -c (count) option to grep and then do if ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; then which works but is rather old school.

BUT, you could use the newest shell features (arithmetic evaluation) like

if ! (( $(grep -c "sysa" /etc/passwd) == 0 )) ; then ...`

which also gives you the benefit of using the c-lang based comparison operators, ==,<,>,>=,<=,% and maybe a few others.

In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like

if ! (( $(grep -c "sysa" /etc/passwd) )) ; then ....

OR

if (( ! $(grep -c "sysa" /etc/passwd) )) ; then ....

Finally, there is an award called the Useless Use of Cat (UUOC). :-) Some people will jump up and down and cry gothca! I'll just say that grep can take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don't have to? ;-)

I hope this helps.

C# Generics and Type Checking

Your construction completely defeats the purpose of a generic method. It's ugly on purpose because there must be a better way to achieve what you're trying to accomplish, although you haven't given us quite enough information to figure out what that is.

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

I disagree with the most voted answer. Use screen and not window

    if(screen.innerHeight > screen.innerWidth){
    alert("Please use Landscape!");
}

Is the proper way to do it. If you calculate with window.height, you ll have trouble on Android. When keyboard is open, window shrinks. So use screen instead of window.

The screen.orientation.type is a good answer but with IE. https://caniuse.com/#search=screen.orientation

How could I put a border on my grid control in WPF?

If nesting your grid in a border control

<Border>
    <Grid>
    </Grid>
</Border>

does not do what you want, then you are going to have to make your own control template for the grid (or border) that DOES do what you want.

document.all vs. document.getElementById

Specifically, document.all was introduced for IE4 BEFORE document.getElementById had been introduced.

So, the presence of document.all means that the code is intended to support IE4, or is trying to identify the browser as IE4 (though it could have been Opera), or the person who wrote (or copied and pasted) the code wasn't up on the latest.

In the highly unlikely event that you need to support IE4, then, you do need document.all (or a library that handles these ancient IE specs).

How to Alter a table for Identity Specification is identity SQL Server

You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

ALTER TABLE ProductInProduct 
ADD NewId INT IDENTITY (1, 1);

Update:

OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

how to create inline style with :before and :after

If you really need it inline, for example because you are loading some user-defined colors dynamically, you can always add a <style> element right before your content.

<style>#project-slide-1:before { color: #ff0000; }</style>
<div id="project-slide-1" class="project-slide"> ... </div>

Example use case with PHP and some (wordpress inspired) dummy functions:

<style>#project-slide-<?php the_ID() ?>:before { color: <?php the_field('color') ?>; }</style>
<div id="project-slide-<?php the_ID() ?>" class="project-slide"> ... </div>

Since HTML 5.2 it is valid to place style elements inside the body, although it is still recommend to place style elements in the head.

Reference: https://www.w3.org/TR/html52/document-metadata.html#the-style-element

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

Make an update object with the property names including the necessary dot path. ("somekey."+ from OP's example), and then use that do the update.

//the modification that's requested
updateReq = { 
   param2 : "val2_new",
   param3 : "val3_new"   
}

//build a renamed version of the update request
var update = {};
for(var field in updateReq){
    update["somekey."+field] = updateReq[field];
}

//apply the update without modifying fields not originally in the update
db.collection.update({._id:...},{$set:update},{upsert:true},function(err,result){...});

What is an unsigned char?

signed char and unsigned char both represent 1byte, but they have different ranges.

   Type        |      range
-------------------------------
signed char    |  -128 to +127
unsigned char  |     0 to 255

In signed char if we consider char letter = 'A', 'A' is represent binary of 65 in ASCII/Unicode, If 65 can be stored, -65 also can be stored. There are no negative binary values in ASCII/Unicode there for no need to worry about negative values.

Example

#include <stdio.h>

int main()
{
    signed char char1 = 255;
    signed char char2 = -128;
    unsigned char char3 = 255;
    unsigned char char4 = -128;

    printf("Signed char(255) : %d\n",char1);
    printf("Unsigned char(255) : %d\n",char3);

    printf("\nSigned char(-128) : %d\n",char2);
    printf("Unsigned char(-128) : %d\n",char4);

    return 0;
}

Output -:

Signed char(255) : -1
Unsigned char(255) : 255

Signed char(-128) : -128
Unsigned char(-128) : 128

change html input type by JS?

_x000D_
_x000D_
$(".show-pass").click(function (e) {_x000D_
    e.preventDefault();_x000D_
    var type = $("#signupform-password").attr('type');_x000D_
    switch (type) {_x000D_
        case 'password':_x000D_
        {_x000D_
            $("#signupform-password").attr('type', 'text');_x000D_
            return;_x000D_
        }_x000D_
        case 'text':_x000D_
        {_x000D_
            $("#signupform-password").attr('type', 'password');_x000D_
            return;_x000D_
        }_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" name="password" class="show-pass">
_x000D_
_x000D_
_x000D_

Types in Objective-C on iOS

Note that you can also use the C99 fixed-width types perfectly well in Objective-C:

#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform

The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h and inttypes.h to be useful.

How to accept Date params in a GET request to Spring MVC Controller?

Below solution perfectly works for spring boot application.

Controller:

@GetMapping("user/getAllInactiveUsers")
List<User> getAllInactiveUsers(@RequestParam("date") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date dateTime) {
    return userRepository.getAllInactiveUsers(dateTime);
}

So in the caller (in my case its a web flux), we need to pass date time in this("yyyy-MM-dd HH:mm:ss") format.

Caller Side:

public Flux<UserDto> getAllInactiveUsers(String dateTime) {
    Flux<UserDto> userDto = RegistryDBService.getDbWebClient(dbServiceUrl).get()
            .uri("/user/getAllInactiveUsers?date={dateTime}", dateTime).retrieve()
            .bodyToFlux(User.class).map(UserDto::of);
    return userDto;
}

Repository:

@Query("SELECT u from User u  where u.validLoginDate < ?1 AND u.invalidLoginDate < ?1 and u.status!='LOCKED'")
List<User> getAllInactiveUsers(Date dateTime);

Cheers!!

jQuery, get html of a whole element

You can easily get child itself and all of its decedents (children) with Jquery's Clone() method, just

var child = $('#div div:nth-child(1)').clone();  

var child2 = $('#div div:nth-child(2)').clone();

You will get this for first query as asked in question

<div id="div1">
     <p>Some Content</p>
</div>

How to add a new project to Github using VS Code

Well, It's quite easy.

Open your local project.


enter image description here


Add a README.md file (If you don't have anything to add yet)


enter image description here


Click on Publish on Github


enter image description here


Choose as you wish


enter image description here


Choose the files you want to include in firt commit.
Note: If you don't select a file or folder it will added to .gitignore file


enter image description here


You are good to go. it is published.

P.S. If this was you first time. A prompt will ask for for your Github Credentials fill those and you are good to go. It is published.

How to position the form in the center screen?

If you use NetBeans IDE right click form then

Properties ->Code -> check out Generate Center

How to get disk capacity and free space of remote computer

I created a PowerShell advanced function (script cmdlet) a while back that allows you to query multiple computers.

The code for the function is a little over 100 lines long, so you can find it here: PowerShell version of the df command

Check out the Usage section for examples. The following usage example queries a set of remote computers (input from the PowerShell pipeline) and displays the output in a table format with numeric values in human-readable form:

PS> $cred = Get-Credential -Credential 'example\administrator'
PS> 'db01','dc01','sp01' | Get-DiskFree -Credential $cred -Format | Format-Table -GroupBy Name -AutoSize

   Name: DB01

Name Vol Size  Used  Avail Use% FS   Type
---- --- ----  ----  ----- ---- --   ----
DB01 C:  39.9G 15.6G 24.3G   39 NTFS Local Fixed Disk
DB01 D:  4.1G  4.1G  0B     100 CDFS CD-ROM Disc


   Name: DC01

Name Vol Size  Used  Avail Use% FS   Type
---- --- ----  ----  ----- ---- --   ----
DC01 C:  39.9G 16.9G 23G     42 NTFS Local Fixed Disk
DC01 D:  3.3G  3.3G  0B     100 CDFS CD-ROM Disc
DC01 Z:  59.7G 16.3G 43.4G   27 NTFS Network Connection


   Name: SP01

Name Vol Size   Used   Avail Use% FS   Type
---- --- ----   ----   ----- ---- --   ----
SP01 C:  39.9G  20G    19.9G   50 NTFS Local Fixed Disk
SP01 D:  722.8M 722.8M 0B     100 UDF  CD-ROM Disc

Java String - See if a string contains only numbers and not letters

There are lots of facilities to obtain numbers from Strings in Java (and vice versa). You may want to skip the regex part to spare yourself the complication of that.

For example, you could try and see what Double.parseDouble(String s) returns for you. It should throw a NumberFormatException if it does not find an appropriate value in the string. I would suggest this technique because you could actually make use of the value represented by the String as a numeric type.

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

Can I serve multiple clients using just Flask app.run() as standalone?

Using the simple app.run() from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason.

Spawning threads and managing them yourself is probably not going to get you very far either, because of the Python GIL.

That said, you do still have some good options. Gunicorn is a solid, easy-to-use WSGI server that will let you spawn multiple workers (separate processes, so no GIL worries), and even comes with asynchronous workers that will speed up your app (and make it more secure) with little to no work on your part (especially with Flask).

Still, even Gunicorn should probably not be directly publicly exposed. In production, it should be used behind a more robust HTTP server; nginx tends to go well with Gunicorn and Flask.

What does file:///android_asset/www/index.html mean?

If someone uses AndroidStudio make sure that the assets folder is placed in

  1. app/src/main/assets

    directory.

map function for objects (instead of arrays)

JavaScript just got the new Object.fromEntries method.

Example

_x000D_
_x000D_
function mapObject (obj, fn) {_x000D_
  return Object.fromEntries(_x000D_
    Object_x000D_
      .entries(obj)_x000D_
      .map(fn)_x000D_
  )_x000D_
}_x000D_
_x000D_
const myObject = { a: 1, b: 2, c: 3 }_x000D_
const myNewObject = mapObject(myObject, ([key, value]) => ([key, value * value]))_x000D_
console.log(myNewObject)
_x000D_
_x000D_
_x000D_

Explanation

The code above converts the Object into an nested Array ([[<key>,<value>], ...]) wich you can map over. Object.fromEntries converts the Array back to an Object.

The cool thing about this pattern, is that you can now easily take object keys into account while mapping.

Documentation

Browser Support

Object.fromEntries is currently only supported by these browsers/engines, nevertheless there are polyfills available (e.g @babel/polyfill).

Python convert decimal to hex

I think this solution is elegant:

def toHex(dec):
    digits = "0123456789ABCDEF"
    x = (dec % 16)
    rest = dec // 16
    if (rest == 0):
        return digits[x]
    return toHex(rest) + digits[x]

numbers = [0, 11, 16, 32, 33, 41, 45, 678, 574893]
print [toHex(x) for x in numbers]
print [hex(x) for x in numbers]

This output:

['0', 'B', '10', '20', '21', '29', '2D', '2A6', '8C5AD']
['0x0', '0xb', '0x10', '0x20', '0x21', '0x29', '0x2d', '0x2a6', '0x8c5ad']

Calling async method synchronously

If you have an async method called " RefreshList " then, you can call that async method from a non-async method like below.

Task.Run(async () => { await RefreshList(); });

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

I just found out, that by using asset_url helper you solve that problem.

asset_url("backgrounds/pattern.png", image)

How to invoke bash, run commands inside the new shell, and then give control back to user?

You can get the functionality you want by sourcing the script instead of running it. eg:

$cat script
cmd1
cmd2
$ . script
$ at this point cmd1 and cmd2 have been run inside this shell

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

CSS3 has a pseudo-class called :not()

_x000D_
_x000D_
input:not([type='checkbox']) {    
    visibility: hidden;
}
_x000D_
<p>If <code>:not()</code> is supported, you'll only see the checkbox.</p>
                                      
<ul>
  <li>text: (<input type="text">)</li>  
  <li>password (<input type="password">)</li>       
  <li>checkbox (<input type="checkbox">)</li> 
 </ul>
_x000D_
_x000D_
_x000D_


Multiple selectors

As Vincent mentioned, it's possible to string multiple :not()s together:

input:not([type='checkbox']):not([type='submit'])

CSS4, which is supported in many of the latest browser releases, allows multiple selectors in a :not()

input:not([type='checkbox'],[type='submit'])

Legacy support

All modern browsers support the CSS3 syntax. At the time this question was asked, we needed a fall-back for IE7 and IE8. One option was to use a polyfill like IE9.js. Another was to exploit the cascade in CSS:

input {
   // styles for most inputs
}   

input[type=checkbox] {
  // revert back to the original style
} 

input.checkbox {
  // for completeness, this would have worked even in IE3!
} 

Caching a jquery ajax response in javascript/browser

Old question, but my solution is a bit different.

I was writing a single page web app that was constantly making ajax calls triggered by the user, and to make it even more difficult it required libraries that used methods other than jquery (like dojo, native xhr, etc). I wrote a plugin for one of my own libraries to cache ajax requests as efficiently as possible in a way that would work in all major browsers, regardless of which libraries were being used to make the ajax call.

The solution uses jSQL (written by me - a client-side persistent SQL implementation written in javascript which uses indexeddb and other dom storage methods), and is bundled with another library called XHRCreep (written by me) which is a complete re-write of the native XHR object.

To implement all you need to do is include the plugin in your page, which is here.

There are two options:

jSQL.xhrCache.max_time = 60;

Set the maximum age in minutes. any cached responses that are older than this are re-requested. Default is 1 hour.

jSQL.xhrCache.logging = true;

When set to true, mock XHR calls will be shown in the console for debugging.

You can clear the cache on any given page via

jSQL.tables = {}; jSQL.persist();

How do I pass a variable by reference?

Since it seems to be nowhere mentioned an approach to simulate references as known from e.g. C++ is to use an "update" function and pass that instead of the actual variable (or rather, "name"):

def need_to_modify(update):
    update(42) # set new value 42
    # other code

def call_it():
    value = 21
    def update_value(new_value):
        nonlocal value
        value = new_value
    need_to_modify(update_value)
    print(value) # prints 42

This is mostly useful for "out-only references" or in a situation with multiple threads / processes (by making the update function thread / multiprocessing safe).

Obviously the above does not allow reading the value, only updating it.

delete_all vs destroy_all?

You are right. If you want to delete the User and all associated objects -> destroy_all However, if you just want to delete the User without suppressing all associated objects -> delete_all

According to this post : Rails :dependent => :destroy VS :dependent => :delete_all

  • destroy / destroy_all: The associated objects are destroyed alongside this object by calling their destroy method
  • delete / delete_all: All associated objects are destroyed immediately without calling their :destroy method

How do I resolve ClassNotFoundException?

I ran into this as well and tried all of the other solutions. I did not have the .class file in my HTML folder, I only had the .java file. Once I added the .class file the program worked fine.

Change SQLite database mode to read-write

On Linux, give read/write permissions to the entire folder containing the database file.

Also, SELinux might be blocking the write. You need to set the correct permissions.

In my SELinux Management GUI (on Fedora 19), I checked the box on the line labelled httpd_unified (Unify HTTPD handling of all content files), and I was good to go.

Why does modulus division (%) only work with integers?

You're looking for fmod().

I guess to more specifically answer your question, in older languages the % operator was just defined as integer modular division and in newer languages they decided to expand the definition of the operator.

EDIT: If I were to wager a guess why, I would say it's because the idea of modular arithmetic originates in number theory and deals specifically with integers.

How can you strip non-ASCII characters from a string? (in C#)

I believe MonsCamus meant:

parsememo = Regex.Replace(parsememo, @"[^\u0020-\u007E]", string.Empty);

Detect key input in Python

Key input is a predefined event. You can catch events by attaching event_sequence(s) to event_handle(s) by using one or multiple of the existing binding methods(bind, bind_class, tag_bind, bind_all). In order to do that:

  1. define an event_handle method
  2. pick an event(event_sequence) that fits your case from an events list

When an event happens, all of those binding methods implicitly calls the event_handle method while passing an Event object, which includes information about specifics of the event that happened, as the argument.

In order to detect the key input, one could first catch all the '<KeyPress>' or '<KeyRelease>' events and then find out the particular key used by making use of event.keysym attribute.

Below is an example using bind to catch both '<KeyPress>' and '<KeyRelease>' events on a particular widget(root):

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def event_handle(event):
    # Replace the window's title with event.type: input key
    root.title("{}: {}".format(str(event.type), event.keysym))


if __name__ == '__main__':
    root = tk.Tk()
    event_sequence = '<KeyPress>'
    root.bind(event_sequence, event_handle)
    root.bind('<KeyRelease>', event_handle)
    root.mainloop()

Finding what methods a Python object has

Take a list as an object

obj = []

list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))

You get:

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

How to get the nth occurrence in a string?

Working off of kennebec's answer, I created a prototype function which will return -1 if the nth occurence is not found rather than 0.

String.prototype.nthIndexOf = function(pattern, n) {
    var i = -1;

    while (n-- && i++ < this.length) {
        i = this.indexOf(pattern, i);
        if (i < 0) break;
    }

    return i;
}

How can I generate an apk that can run without server with react-native?

Run this command:

react-native run-android --variant=release

Note that --variant=release is only available if you've set up signing with cd android && ./gradlew assembleRelease.

How to print a linebreak in a python function?

>>> A = ['a1', 'a2', 'a3']
>>> B = ['b1', 'b2', 'b3']

>>> for x in A:
        for i in B:
            print ">" + x + "\n" + i

Outputs:

>a1
b1
>a1
b2
>a1
b3
>a2
b1
>a2
b2
>a2
b3
>a3
b1
>a3
b2
>a3
b3

Notice that you are using /n which is not correct!

How to add scroll bar to the Relative Layout?

The following code should do the trick:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="638dp" >

<TextView
    android:id="@+id/textView1"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="64dp"
    android:text="Email" />

<TextView
    android:id="@+id/textView2"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="41dp"
    android:text="Password" />

<TextView
    android:id="@+id/textView3"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView2"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="47dp"
    android:text="Confirm Password" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/textView4"
    android:inputType="textEmailAddress" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignLeft="@+id/editText2"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />


<TextView
    android:id="@+id/textView4"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="42dp"
    android:text="Date of Birth" />

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView4" />

<TextView
    android:id="@+id/textView5"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/datePicker1"
    android:layout_marginTop="60dp"
    android:layout_toLeftOf="@+id/datePicker1"
    android:text="Gender" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView5"
    android:layout_alignBottom="@+id/textView5"
    android:layout_alignLeft="@+id/editText3"
    android:layout_marginLeft="24dp"
    android:text="Male" />

<RadioButton
    android:id="@+id/radioButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/radioButton1"
    android:layout_below="@+id/radioButton1"
    android:layout_marginTop="14dp"
    android:text="Female" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="23dp"
    android:layout_toLeftOf="@+id/radioButton2"
    android:background="@drawable/rectbutton"
    android:text="Sign Up" />

Bootstrap modal: is not a function

Use:

jQuery.noConflict();
$('#prizePopup').modal('toggle');

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

If first variable($a) is null, then assign value of second variable($b) to first variable($a)

 $a = 5;
 $b = 10;   

 $a != ''?$a: $a = $b;

 echo $a;

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

To install the prerequisites for GPU support in TensorFlow 2.1:

  1. Install your latest GPU drivers.
  2. Install CUDA 10.1.
    • If the CUDA installer reports "you are installing an older driver version", you may wish to choose a custom installation and deselect some components. Indeed, note that software bundled with CUDA including GeForce Experience, PhysX, a Display Driver, and Visual Studio integration are not required by TensorFlow.
    • Also note that TensorFlow requires a specific version of the CUDA Toolkit unless you build from source; for TensorFlow 2.1 and 2.2, this is currently version 10.1.
  3. Install cuDNN.
    1. Download cuDNN v7.6.4 for CUDA 10.1. This will require you to sign up to the NVIDIA Developer Program.
    2. Unzip to a suitable location and add the bin directory to your PATH.
  4. Install tensorflow by pip install tensorflow.
  5. You may need to restart your PC.

How to determine a Python variable's type?

a = "cool"
type(a)

//result 'str'
<class 'str'>
or 
do 
`dir(a)` 
to see the list of inbuilt methods you can have on the variable.

PHP Composer behind http proxy

If you have to use credentials try this:

export HTTP_PROXY="http://username:[email protected]:port"

How do I call a JavaScript function on page load?

Another way to do this is by using event listeners, here how you use them:

document.addEventListener("DOMContentLoaded", function() {
  you_function(...);
});

Explanation:

DOMContentLoaded It means when the DOM Objects of the document are fully loaded and seen by JavaScript, also this could have been "click", "focus"...

function() Anonymous function, will be invoked when the event occurs.

Calling a function when ng-repeat has finished

The other solutions will work fine on initial page load, but calling $timeout from the controller is the only way to ensure that your function is called when the model changes. Here is a working fiddle that uses $timeout. For your example it would be:

.controller('myC', function ($scope, $timeout) {
$scope.$watch("ta", function (newValue, oldValue) {
    $timeout(function () {
       test();
    });
});

ngRepeat will only evaluate a directive when the row content is new, so if you remove items from your list, onFinishRender will not fire. For example, try entering filter values in these fiddles emit.

How to insert a file in MySQL database?

The other answers will give you a good idea how to accomplish what you have asked for....

However

There are not many cases where this is a good idea. It is usually better to store only the filename in the database and the file on the file system.

That way your database is much smaller, can be transported around easier and more importantly is quicker to backup / restore.

Non-alphanumeric list order from os.listdir()

ls by default previews the files sorted by name. (ls options can be used to sort by date, size, ...)

files = list(os.popen("ls"))
files = [file.strip("\n") for file in files]

Using ls would have much better performance when the directory contains so many files.

Run chrome in fullscreen mode on Windows

  • Right click the Google Chrome icon and select Properties.
  • Copy the value of Target, for example: "C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe".
  • Create a shortcut on your Desktop.
  • Paste the value into Location of the item, and append --kiosk <your url>:

    "C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe" --kiosk http://www.google.com
    
  • Press Apply, then OK.

  • To start Chrome at Windows startup, copy this shortcut and paste it into the Startup folder (Start -> Program -> Startup).

How to find the sum of an array of numbers

Considering you have the array

const arr = [1, 2, 3, 4];

For me, the most intuitive way is using a for-in

let sum = 0;
for(var value in arr) {
    sum += arr[value];
}

console.log('Array:', arr);
console.log('Sum:', sum);

Yet, you can also use Arrow Functions and the reduce function

const sum = arr.reduce(function (a, b) {
    return a + b;
}, 0);

console.log('Array:', arr);
console.log('Sum:', sum);

They're both gonna output

Array: [ 1, 2, 3, 4]
Sum: 10

Windows equivalent of linux cksum command

Open Windows PowerShell, and use the below command:

Get-FileHash C:\Users\Deepak\Downloads\ubuntu-20.10-desktop-amd64.iso

Compare two dates in Java

The easiest way to compare two dates is converting them to numeric value (like unix timestamp).

You can use Date.getTime() method that return the unix time.

Date questionDate = question.getStartDate();
Date today = new Date();
if((today.getTime() == questionDate.getTime())) {
    System.out.println("Both are equals");
}

How do I add a auto_increment primary key in SQL Server database?

If you have the column it's very easy.

Using the designer, you could set the column as an identity (1,1): right click on the table ? design ? in part left (right click) ? properties ? in identity columns, select #column.


Properties:

enter image description here

Identity column:

enter image description here

How to add images to README.md on GitHub?

I usually host the image on the site, this can link to any hosted image. Just toss this in the readme. Works for .rst files, not sure about .md

.. image:: https://url/path/to/image
   :height: 100px
   :width: 200 px
   :scale: 50 %

Android Studio Run/Debug configuration error: Module not specified

check your build.gradle file and make sure that use apply plugin: 'com.android.application' istead of apply plugin: 'com.android.library'

it worked for me

Windows shell command to get the full path to the current directory?

For Windows we can use

cd

and for Linux

pwd

command is there.

Use querystring variables in MVC controller

My problem was overwriting my query string parameters with default values:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = ""}
);

No matter what I plugged into query string or how only key="" results.

Then got rid of default overwrites using UrlParameter.Optional:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);

now

prices/{key} 

or

prices?key={key} 

both work fine.

CSS Calc Viewport Units Workaround?

Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.

Example here: https://codesandbox.io/s/21r4z95p7j

You can even utilize the bottom gutter space if you so choose, simply by adding another "item".

Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: #334;_x000D_
  color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  min-height: 100vh;_x000D_
  min-width: 100vw;_x000D_
  display: grid;_x000D_
  grid-template-columns: 100%;_x000D_
  grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  background-color: #558;_x000D_
  padding: 2px;_x000D_
  margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
  background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Parcel Sandbox</title>_x000D_
    <meta charset="UTF-8" />_x000D_
    <link rel="stylesheet" href="src/index.css" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="app">_x000D_
      <div class="main">_x000D_
        <div class="item">Item 1</div>_x000D_
        <!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
      </div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to find Oracle Service Name

Found here, no DBA : Checking oracle sid and database name

select * from global_name;

sorting dictionary python 3

Sorting dictionaries by value using comprehensions. I think it's nice as 1 line and no need for functions or lambdas

a = {'b':'foo', 'c':'bar', 'e': 'baz'}
a = {f:a[f] for f in sorted(a, key=a.__getitem__)}

Iterating through a list to render multiple widgets in Flutter?

Basically when you hit 'return' on a function the function will stop and will not continue your iteration, so what you need to do is put it all on a list and then add it as a children of a widget

you can do something like this:

  Widget getTextWidgets(List<String> strings)
  {
    List<Widget> list = new List<Widget>();
    for(var i = 0; i < strings.length; i++){
        list.add(new Text(strings[i]));
    }
    return new Row(children: list);
  }

or even better, you can use .map() operator and do something like this:

  Widget getTextWidgets(List<String> strings)
  {
    return new Row(children: strings.map((item) => new Text(item)).toList());
  }

javascript Unable to get property 'value' of undefined or null reference

you have many HTML and java script mistakes includes: tag, using non UTF-8 encoding for form submission, no need,... You must use document.forms.FORMNAME or document.forms[0] for first appear form in page Corrected:

_x000D_
_x000D_
 function validate_frm_new_user_request()_x000D_
{_x000D_
    alert('test');_x000D_
    var valid = true;_x000D_
_x000D_
    if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
    {_x000D_
        alert ( "Please enter your valid ISID Information." );_x000D_
        document.forms.frm_new_user_request.u_userid.focus();_x000D_
        valid = false;_x000D_
  console.log("FALSE::Empty Value ");_x000D_
    }_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
        <tr align="left">_x000D_
            <td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
            </tr>_x000D_
_x000D_
<tr>_x000D_
            <td align="center" colspan="4">_x000D_
                <input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
                </td>_x000D_
        </tr>_x000D_
    </table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to list physical disks?

Here is a new solution of doing it with doing WMI calls.
Then all you need to do is just to call :

queryAndPrintResult(L"SELECT * FROM Win32_DiskDrive", L"Name");

How to install Android SDK Build Tools on the command line?

As mentioned in other answers, you can use the --filter option to limit the installed packages:

android update sdk --filter ...

The other answers don't mention that you can use constant string identifiers instead of indexes (which will change) for the filter options. This is helpful for unattended or scripted installs. Man for --filter option:

... This also accepts the identifiers returned by 'list sdk --extended'.

android list sdk --all --extended :

Packages available for installation or update: 97
----------
id: 1 or "tools"
     Type: Tool
     Desc: Android SDK Tools, revision 22.6.2
----------
id: 2 or "platform-tools"
     Type: PlatformTool
     Desc: Android SDK Platform-tools, revision 19.0.1
----------
id: 3 or "build-tools-19.0.3"
     Type: BuildTool
     Desc: Android SDK Build-tools, revision 19.0.3

Then you can use the string ids as the filter options to precisely specify the versions you want:

android update sdk --filter tools,platform-tools,build-tools-19.0.3 etc

How to implement a binary search tree in Python?

I find the solutions a bit clumsy on the insert part. You could return the root reference and simplify it a bit:

def binary_insert(root, node):
    if root is None:
        return node
    if root.data > node.data:
        root.l_child = binary_insert(root.l_child, node)
    else:
        root.r_child = binary_insert(root.r_child, node)
    return root

How to dynamically add a style for text-align using jQuery

You have the right idea, as documentation shows:

http://docs.jquery.com/CSS/css#namevalue

Are you sure you're correctly identify this with class or id?

For example, if your class is myElementClass

$('.myElementClass').css('text-align','center');

Also, I haven't worked with Firebug in a while, but are you looking at the dom and not the html? Your source isn't changed by javascript, but the dom is. Look in the dom tab and see if the change was applied.

Return Boolean Value on SQL Select Statement

Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.

SELECT DISTINCT 1 AS Expr1
FROM [User]
WHERE (UserID = 20070022)

Git command to display HEAD commit id?

Use the command:

git rev-parse HEAD

For the short version:

git rev-parse --short HEAD

How to forward declare a template class in namespace std?

I solved that problem.

I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>) and its states (state pattern, forward declaration).

The solution is as follows:

In the *.cpp file, you must include the Header file that you forward, i.e.

ifndef STATE_H_
#define STATE_H_
#include <stdlib.h>
#include "Frame.h"

template <class T>
class LinkFrame;

using namespace std;

template <class T>
class State {

  protected:
    LinkFrame<int> *myFrame;

}

Its cpp:

#include "State.h"
#include "Frame.h"
#include  "LinkFrame.h"

template <class T>
bool State<T>::replace(Frame<T> *f){

And... another class.

Call Python function from MATLAB

Try this MEX file for ACTUALLY calling Python from MATLAB not the other way around as others suggest. It provides fairly decent integration : http://algoholic.eu/matpy/

You can do something like this easily:

[X,Y]=meshgrid(-10:0.1:10,-10:0.1:10);
Z=sin(X)+cos(Y);
py_export('X','Y','Z')
stmt = sprintf(['import matplotlib\n' ...
'matplotlib.use(''Qt4Agg'')\n' ...
'import matplotlib.pyplot as plt\n' ...
'from mpl_toolkits.mplot3d import axes3d\n' ...
'f=plt.figure()\n' ...
'ax=f.gca(projection=''3d'')\n' ...
'cset=ax.plot_surface(X,Y,Z)\n' ...
'ax.clabel(cset,fontsize=9,inline=1)\n' ...
'plt.show()']);
py('eval', stmt);

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

Iterate Multi-Dimensional Array with Nested Foreach Statement

int[,] arr =  { 
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
              };
 for(int i = 0; i < arr.GetLength(0); i++){
      for (int j = 0; j < arr.GetLength(1); j++)
           Console.Write( "{0}\t",arr[i, j]);
      Console.WriteLine();
    }

output:  1  2  3
         4  5  6
         7  8  9

How to pass data from Javascript to PHP and vice versa?

I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:

My simple client side code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
   <title>Test Page</title>
   <script>
    function passVal(){
        var data = {
            fn: "filename",
            str: "this_is_a_dummy_test_string"
        };

        $.post("test.php", data);
    }
    passVal();
   </script>

</head>
<body>
</body>
</html>

And php code on server side:

<?php 
   $fn  = $_POST['fn'];
   $str = $_POST['str'];
   $file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
   echo fwrite($file,$str);
   fclose($file);
?>

Hope this works for you and future readers!

Why is the <center> tag deprecated in HTML?

According to W3Schools.com,

The center element was deprecated in HTML 4.01, and is not supported in XHTML 1.0 Strict DTD.

The HTML 4.01 spec gives this reason for deprecating the tag:

The CENTER element is exactly equivalent to specifying the DIV element with the align attribute set to "center".

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

You're confusing PATH and PYTHONPATH. You need to do this:

export PATH=$PATH:/home/randy/lib/python 

PYTHONPATH is used by the python interpreter to determine which modules to load.

PATH is used by the shell to determine which executables to run.

JPA EntityManager: Why use persist() over merge()?

Either way will add an entity to a PersistenceContext, the difference is in what you do with the entity afterwards.

Persist takes an entity instance, adds it to the context and makes that instance managed (ie future updates to the entity will be tracked).

Merge returns the managed instance that the state was merged to. It does return something what exists in PersistenceContext or creates a new instance of your entity. In any case, it will copy the state from the supplied entity, and return managed copy. The instance you pass in will not be managed (any changes you make will not be part of the transaction - unless you call merge again). Though you can use the returned instance (managed one).

Maybe a code example will help.

MyEntity e = new MyEntity();

// scenario 1
// tran starts
em.persist(e); 
e.setSomeField(someValue); 
// tran ends, and the row for someField is updated in the database

// scenario 2
// tran starts
e = new MyEntity();
em.merge(e);
e.setSomeField(anotherValue); 
// tran ends but the row for someField is not updated in the database
// (you made the changes *after* merging)
      
// scenario 3
// tran starts
e = new MyEntity();
MyEntity e2 = em.merge(e);
e2.setSomeField(anotherValue); 
// tran ends and the row for someField is updated
// (the changes were made to e2, not e)

Scenario 1 and 3 are roughly equivalent, but there are some situations where you'd want to use Scenario 2.

How to compare times in Python?

You can compare datetime.datetime objects directly

E.g:

>>> a
datetime.datetime(2009, 12, 2, 10, 24, 34, 198130)
>>> b
datetime.datetime(2009, 12, 2, 10, 24, 36, 910128)
>>> a < b
True
>>> a > b
False
>>> a == a
True
>>> b == b
True
>>> 

Making macOS Installer Packages which are Developer ID ready

FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:

pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg

Easier way to create circle div than using an image?

You can try the radial-gradient CSS function:

.circle {
    width: 500px;
    height: 500px;
    border-radius: 50%;
    background: #ffffff; /* Old browsers */
    background: -moz-radial-gradient(center, ellipse cover, #ffffff 17%, #ff0a0a 19%, #ff2828 40%, #000000 41%); /* FF3.6-15 */
    background: -webkit-radial-gradient(center, ellipse cover, #ffffff 17%,#ff0a0a 19%,#ff2828 40%,#000000 41%); /* Chrome10-25,Safari5.1-6 */
    background: radial-gradient(ellipse at center, #ffffff 17%,#ff0a0a 19%,#ff2828 40%,#000000 41%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
}

Apply it to a div layer:

<div class="circle"></div>

Import CSV into SQL Server (including automatic table creation)

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

It doesn't matter - they are exactly the same thing. However, the main thing is that you must be consistent

p.s. I struggle with this sort of "whats the right thing" all the time.

Does mobile Google Chrome support browser extensions?

Just use a different browser. Follow the steps given below to install Chrome extensions on your Android device.

Step 1: Open Google Play Store and download Yandex Browser. Install the browser on your phone.

Step 2: In the URL box of your new browser, open 'chrome.google.com/webstore’ by entering the same in the URL address.

Step 3: Look for the Chrome extension that you want and once you have it, tap on 'Add to Chrome.’

The added Chrome extension will now be automatically added to the Yandex browser.

Spark DataFrame groupBy and sort in the descending order (pyspark)

By far the most convenient way is using this:

df.orderBy(df.column_name.desc())

Doesn't require special imports.

Session 'app': Error Installing APK

I changed my USB port and that fixed it for me.

Best way to determine user's locale within browser

You can also try to get the language from the document should might be your first port of call, then falling back to other means as often people will want their JS language to match the document language.

HTML5:

document.querySelector('html').getAttribute('lang')

Legacy:

document.querySelector('meta[http-equiv=content-language]').getAttribute('content')

No real source is necessarily 100% reliable as people can simply put in the wrong language.

There are language detection libraries that might let you determine the language by content.

Escaping special characters in Java Regular Expressions

Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?

If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.

So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:

// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";

The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.

matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
... 

In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

How to make an Android device vibrate? with different frequency?

Try:

import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    //deprecated in API 26 
    v.vibrate(500);
}

Note:

Don't forget to include permission in AndroidManifest.xml file:

<uses-permission android:name="android.permission.VIBRATE"/>

Create a sample login page using servlet and JSP?

As I can see, you are comparing the message with the empty string using ==.

Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.

I hope, it will help you. If any problem, then please revert.

Nikhil Pahariya

Is there a program to decompile Delphi?

I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).

adb devices command not working

Every answer I've read indicates the SUBSYSTEM=="usb". However, my (perhaps ancient) udev needed this to be changed to DRIVER=="usb". At last I can run the adb server as a non-root user... yay.

It can be instructive to look at the output of udevmonitor --env, followed by the output of

udevinfo -a -p <DEVICE_PATH_AS_REPORTED_BY-udevmonitor>

Ruby: How to iterate over a range, but in set increments?

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i
end

How can I print literal curly-brace characters in a string and also use .format on it?

Try doing this:

x = " {{ Hello }} {0} "
print x.format(42)

How to get JSON objects value if its name contains dots?

If json object key/name contains dot......! like

var myJson = {"my.name":"vikas","my.age":27}

Than you can access like

myJson["my.name"]
myJson["my.age"]

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

Force "git push" to overwrite remote files

Another option (to avoid any forced push which can be problematic for other contributors) is to:

  • put your new commits in a dedicated branch
  • reset your master on origin/master
  • merge your dedicated branch to master, always keeping commits from the dedicated branch (meaning creating new revisions on top of master which will mirror your dedicated branch).
    See "git command for making one branch like another" for strategies to simulate a git merge --strategy=theirs.

That way, you can push master to remote without having to force anything.

Using .text() to retrieve only text not nested in child tags

Just like the question, I was trying to extract text in order to do some regex substitution of the text but was getting problems where my inner elements (ie: <i>, <div>, <span>, etc.) were getting also removed.

The following code seems to work well and solved all my problems.

It uses some of the answers provided here but in particular, will only substitute the text when the element is of nodeType === 3.

$(el).contents().each(function() { 
  console.log(" > Content: %s [%s]", this, (this.nodeType === 3));

  if (this.nodeType === 3) {
    var text = this.textContent;
    console.log(" > Old   : '%s'", text);

    regex = new RegExp("\\[\\[" + rule + "\\.val\\]\\]", "g");
    text = text.replace(regex, value);

    regex = new RegExp("\\[\\[" + rule + "\\.act\\]\\]", "g");
    text = text.replace(regex, actual);

    console.log(" > New   : '%s'", text);
    this.textContent = text;
  }
});

What the above does is loop through all the elements of the given el (which was simply obtained with $("div.my-class[name='some-name']");. For each inner element, it basically ignores them. For each portion of text (as determined by if (this.nodeType === 3)) it will apply the regex substitution only to those elements.

The this.textContent = text portion simply replaces the substituted text, which in my case, I was looking for tokens like [[min.val]], [[max.val]], etc.

This short code excerpt will help anyone trying to do what the question was asking ... and a bit more.

android: how to change layout on button click?

First I would suggest putting a Log in each case of your switch to be sure that your code is being called.

Then I would check that the layouts are actually different.

How can one display images side by side in a GitHub README.md?

To piggyback off of @Maruf Hassan

# Title

<table>
  <tr>
    <td>First Screen Page</td>
     <td>Holiday Mention</td>
     <td>Present day in purple and selected day in pink</td>
  </tr>
  <tr>
    <td valign="top"><img src="screenshots/Screenshot_1582745092.png"></td>
    <td valign="top"><img src="screenshots/Screenshot_1582745125.png"></td>
    <td valign="top"><img src="screenshots/Screenshot_1582745139.png"></td>
  </tr>
 </table>

<td valign="top">...</td> is supported by GitHub Markdown. Images with varying heights may not vertically align near the top of the cell. This property handles it for you.

How to simulate a mouse click using JavaScript?

You can use elementFromPoint:

document.elementFromPoint(x, y);

supported in all browsers: https://caniuse.com/#feat=element-from-point

Python Threading String Arguments

from threading import Thread
from time import sleep
def run(name):
    for x in range(10):
        print("helo "+name)
        sleep(1)
def run1():
    for x in range(10):
        print("hi")
        sleep(1)
T=Thread(target=run,args=("Ayla",))
T1=Thread(target=run1)
T.start()
sleep(0.2)
T1.start()
T.join()
T1.join()
print("Bye")

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

How to trim a string in SQL Server before 2017?

SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer

Onclick on bootstrap button

<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>

$('#fire').on('click', function (e) {

     //your awesome code here

})

How to use Session attributes in Spring-mvc

Try this...

@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {

    @ModelAttribute("types")

    public Collection<PetType> populatePetTypes() {
        return this.clinic.getPetTypes();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet, 
            BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId="
                + pet.getOwner().getId();
        }
    }
}

How to create jobs in SQL Server Express edition

The functionality of creating SQL Agent Jobs is not available in SQL Server Express Edition. An alternative is to execute a batch file that executes a SQL script using Windows Task Scheduler.

In order to do this first create a batch file named sqljob.bat

sqlcmd -S servername -U username -P password -i <path of sqljob.sql>

Replace the servername, username, password and path with yours.

Then create the SQL Script file named sqljob.sql

USE [databasename]
--T-SQL commands go here
GO

Replace the [databasename] with your database name. The USE and GO is necessary when you write the SQL script.

sqlcmd is a command-line utility to execute SQL scripts. After creating these two files execute the batch file using Windows Task Scheduler.

NB: An almost same answer was posted for this question before. But I felt it was incomplete as it didn't specify about login information using sqlcmd.

What does the "@" symbol do in SQL?

@ followed by a number is the parameters in the order they're listed in a function.

jQuery - Getting form values for ajax POST

you can use val function to collect data from inputs:

jQuery("#myInput1").val();

http://api.jquery.com/val/

EL access a map value by Integer key

Based on the above post i tried this and this worked fine I wanted to use the value of Map B as keys for Map A:

<c:if test="${not empty activityCodeMap and not empty activityDescMap}">
<c:forEach var="valueMap" items="${auditMap}">
<tr>
<td class="activity_white"><c:out value="${activityCodeMap[valueMap.value.activityCode]}"/></td>
<td class="activity_white"><c:out value="${activityDescMap[valueMap.value.activityDescCode]}"/></td>
<td class="activity_white">${valueMap.value.dateTime}</td>
</tr>
</c:forEach>
</c:if>

"Invalid JSON primitive" in Ajax processing

As noted by jitter, the $.ajax function serializes any object/array used as the data parameter into a url-encoded format. Oddly enough, the dataType parameter only applies to the response from the server - and not to any data in the request.

After encountering the same problem I downloaded and used the jquery-json plugin to correctly encode the request data to the ScriptService. Then, used the $.toJSON function to encode the desired arguments to send to the server:

$.ajax({
    type: "POST",
    url: "EditUserProfile.aspx/DeleteRecord",
    data: $.toJSON(obj),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
    ....
});

Can you do greater than comparison on a date in a Rails 3 search?

Note.
  where(:user_id => current_user.id, :notetype => p[:note_type]).
  where("date > ?", p[:date]).
  order('date ASC, created_at ASC')

or you can also convert everything into the SQL notation

Note.
  where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
  order('date ASC, created_at ASC')

How to disable copy/paste from/to EditText

I've tested this solution and this works

    mSubdomainEditText.setLongClickable(false);
    mSubdomainEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

      public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
      }

      public void onDestroyActionMode(ActionMode mode) {
      }

      public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        return false;
      }

      public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return false;
      }
    });

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date
); 

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

CREATE TABLE Vendor(
    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date
);

CREATE TABLE Inventory(
    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL
);

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

CREATE TABLE Class(
    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)
);

CREATE TABLE Student(
    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)
);  

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
    UNIQUE (StudentID, ClassID)
);

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

SkipSoft.net has some great toolkits. I ran into a similar problem with my Galaxy Nexus.... Ran the corresponding toolkit, which configured my system and downloaded the correct drivers. I then went into Windows Hardware manager after connecting the phone... Windows reported the exclamation that it couldn't find the device driver, so I ran update, and gave it the drivers directory the toolkit had created... and everything started working great. Hope this helps :)