Programs & Examples On #Kdb

kdb+ is a proprietary high-performance database developed by Kx Systems.

Google Chromecast sender error if Chromecast extension is not installed or using incognito

How about filtering these errors ?

With the regex filter bellow, we can dismiss cast_sender.js errors :

^((?!cast_sender).)*$

Do not forget to check Regex box.

enter image description here

Another quick solution is to "Hide network messages".

enter image description here

ImportError: No module named dateutil.parser

You can find the dateutil package at https://pypi.python.org/pypi/python-dateutil. Extract it to somewhere and run the command:

python setup.py install

It worked for me!

select from one table, insert into another table oracle sql query

You can use

insert into <table_name> select <fieldlist> from <tables>

draw diagonal lines in div background with CSS

All other answers to this 3-year old question require CSS3 (or SVG). However, it can also be done with nothing but lame old CSS2:

_x000D_
_x000D_
.crossed {_x000D_
    position: relative;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.crossed:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 1px;_x000D_
    bottom: 1px;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: black white;_x000D_
}_x000D_
_x000D_
.crossed:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 1px;_x000D_
    right: 1px;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: white transparent;_x000D_
}
_x000D_
<div class='crossed'></div>
_x000D_
_x000D_
_x000D_

Explanation, as requested:

Rather than actually drawing diagonal lines, it occurred to me we can instead color the so-called negative space triangles adjacent to where we want to see these lines. The trick I came up with to accomplish this exploits the fact that multi-colored CSS borders are bevelled diagonally:

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

To make things fit the way we want, we choose an inner rectangle with dimensions 0 and LINE_THICKNESS pixels, and another one with those dimensions reversed:

_x000D_
_x000D_
.r1 { width: 10px;_x000D_
      height: 0;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: red blue;_x000D_
      margin-bottom: 10px; }_x000D_
.r2 { width: 0;_x000D_
      height: 10px;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: blue transparent; }
_x000D_
<div class='r1'></div><div class='r2'></div>
_x000D_
_x000D_
_x000D_

Finally, use the :before and :after pseudo-selectors and position relative/absolute as a neat way to insert the borders of both of the above rectangles on top of each other into your HTML element of choice, to produce a diagonal cross. Note that results probably look best with a thin LINE_THICKNESS value, such as 1px.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

I lately came up with this error. But it was even more odd. I was working on Android N and everything was going smoothly OK, until I test it on JellyBeans and Lollipop. In which I kept on getting the same DB error.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database 06-10 23:07:03.641: E/SQLiteDatabase(4419):

I had the right permissions in my manifest, including:

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

The problem was this line in my DataBaseHelper.java:

private static String DB_PATH = "/data/data/com.example.quotes/databases";

which needed to be loaded from the context this way:

String DB_PATH = getContext().getApplicationInfo().dataDir+"/databases/";

Now is working properly form SDK 17.

How to retrieve data from sqlite database in android and display it in TextView

TextView tekst = (TextView) findViewById(R.id.editText1); 

You cannot cast EditText to TextView.

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Get JSONArray without array name?

JSONArray has a constructor which takes a String source (presumed to be an array).

So something like this

JSONArray array = new JSONArray(yourJSONArrayAsString);

A full list of all the new/popular databases and their uses?

To file under both 'established' and 'key-value store': Berkeley DB.

Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).

Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.

Is embedding background image data into CSS as Base64 good or bad practice?

You can encode it in PHP :)

<img src="data:image/gif;base64,<?php echo base64_encode(file_get_contents("feed-icon.gif")); ?>">

Or display in our dynamic CSS.php file:

background: url("data:image/gif;base64,<?php echo base64_encode(file_get_contents("feed-icon.gif")); ?>");

1 That’s sort of a “quick-n-dirty” technique but it works. Here is another encoding method using fopen() instead of file_get_contents():

<?php // convert image to dataURL
$img_source = "feed-icon.gif"; // image path/name
$img_binary = fread(fopen($img_source, "r"), filesize($img_source));
$img_string = base64_encode($img_binary);
?>

Source

How to change the sender's name or e-mail address in mutt?

100% Working!

To send HTML contents in the body of the mail on the go with Sender and Recipient mail address in single line, you may try the below,

export EMAIL="[email protected]" && mutt -e "my_hdr Content-Type: text/html" -s "Test Mail" "[email protected]" < body_html.html

File: body_html.html

<HTML>
<HEAD> Test Mail </HEAD>
<BODY>
<p>This is a <strong><span style="color: #ff0000;">test mail!</span></strong></p>
</BODY>
</HTML>

Note: Tested in RHEL, CentOS, Ubuntu.

Python urllib2 Basic Auth Problem

The second parameter must be a URI, not a domain name. i.e.

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, "http://api.foursquare.com/", username, password)

Print content of JavaScript object?

This will give you very nice output with indented JSON object:

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));

The second argument alters the contents of the string before returning it. The third argument specifies how many spaces to use as white space for readability.

How to find sitemap.xml path on websites?

The location of the sitemap affects which URLs that it can include, but otherwise there is no standard. Here is a good link with more explaination: http://www.sitemaps.org/protocol.html#location

How do you get the cursor position in a textarea?

Here's a cross browser function I have in my standard library:

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0;
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len };
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

Use it in your code like this:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function:

function setCursorPos(input, start, end) {
    if (arguments.length < 3) end = start;
    if ("selectionStart" in input) {
        setTimeout(function() {
            input.selectionStart = start;
            input.selectionEnd = end;
        }, 1);
    }
    else if (input.createTextRange) {
        var rng = input.createTextRange();
        rng.moveStart("character", start);
        rng.collapse();
        rng.moveEnd("character", end - start);
        rng.select();
    }
}

http://jsfiddle.net/gilly3/6SUN8/

How to return a file (FileContentResult) in ASP.NET WebAPI

Here is an implementation that streams the file's content out without buffering it (buffering in byte[] / MemoryStream, etc. can be a server problem if it's a big file).

public class FileResult : IHttpActionResult
{
    public FileResult(string filePath)
    {
        if (filePath == null)
            throw new ArgumentNullException(nameof(filePath));

        FilePath = filePath;
    }

    public string FilePath { get; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(File.OpenRead(FilePath));
        var contentType = MimeMapping.GetMimeMapping(Path.GetExtension(FilePath));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        return Task.FromResult(response);
    }
}

It can be simply used like this:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        string filePath = GetSomeValidFilePath();
        return new FileResult(filePath);
    }
}

How can I draw vertical text with CSS cross-browser?

I adapted this from http://snook.ca/archives/html_and_css/css-text-rotation :

<style>
    .Rotate-90
    {
        display: block;
        position: absolute;
        right: -5px;
        top: 15px;
        -webkit-transform: rotate(-90deg);
        -moz-transform: rotate(-90deg);
    }
</style>
<!--[if IE]>
    <style>
        .Rotate-90 {
            filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
            right:-15px; top:5px;
        }
    </style>
    <![endif]-->

Java NIO: What does IOException: Broken pipe mean?

Broken pipe simply means that the connection has failed. It is reasonable to assume that this is unrecoverable, and to then perform any required cleanup actions (closing connections, etc). I don't believe that you would ever see this simply due to the connection not yet being complete.

If you are using non-blocking mode then the SocketChannel.connect method will return false, and you will need to use the isConnectionPending and finishConnect methods to insure that the connection is complete. I would generally code based upon the expectation that things will work, and then catch exceptions to detect failure, rather than relying on frequent calls to "isConnected".

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How do you find the current user in a Windows environment?

In a standard context, each connected user holds an explorer.exe process: The command [tasklist /V|find "explorer"] returns a line that contains the explorer.exe process owner's, with an adapted regex it is possible to obtain the required value. This also runs perfectly under Windows 7.

In rare cases explorer.exe is replaced by another program, the find filter can be adapted to match this case. If the command return an empty line then it is likely that no user is logged on. With Windows 7 it is also possible to run [query session|find ">"].

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

Hibernate SessionFactory vs. JPA EntityManagerFactory

I want to add on this that you can also get Hibernate's session by calling getDelegate() method from EntityManager.

ex:

Session session = (Session) entityManager.getDelegate();

Entity Framework Provider type could not be loaded?

Same problem, but i installed EF 6 through Nuget. EntityFramework.SqlServer was missing for another executable. I simply added the nuget package to that project.

What does "TypeError 'xxx' object is not callable" means?

The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ().

e.g. Class A defines self.a and self.a():

>>> class A:
...     def __init__(self, val):
...         self.a = val
...     def a(self):
...         return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>

Changing three.js background to transparent or other color

I came across this when I started using three.js as well. It's actually a javascript issue. You currently have:

renderer.setClearColorHex( 0x000000, 1 );

in your threejs init function. Change it to:

renderer.setClearColorHex( 0xffffff, 1 );

Update: Thanks to HdN8 for the updated solution:

renderer.setClearColor( 0xffffff, 0);

Update #2: As pointed out by WestLangley in another, similar question - you must now use the below code when creating a new WebGLRenderer instance in conjunction with the setClearColor() function:

var renderer = new THREE.WebGLRenderer({ alpha: true });

Update #3: Mr.doob points out that since r78 you can alternatively use the code below to set your scene's background colour:

var scene = new THREE.Scene(); // initialising the scene
scene.background = new THREE.Color( 0xff0000 );

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

Sounds like mssql jdbc is buffering the entire resultset for you. You can add a connect string parameter saying selectMode=cursor or responseBuffering=adaptive. If you are on version 2.0+ of the 2005 mssql jdbc driver then response buffering should default to adaptive.

http://msdn.microsoft.com/en-us/library/bb879937.aspx

Usage of the backtick character (`) in JavaScript

Summary:

Backticks in JavaScript is a feature which is introduced in ECMAScript 6 // ECMAScript 2015 for making easy dynamic strings. This ECMAScript 6 feature is also named template string literal. It offers the following advantages when compared to normal strings:

  • In Template strings linebreaks are allowed and thus can be multiline. Normal string literals (declared with '' or "") are not allowed to have linebreaks.
  • We can easily interpolate variable values to the string with the ${myVariable} syntax.

Example:

_x000D_
_x000D_
const name = 'Willem';_x000D_
const age = 26;_x000D_
_x000D_
const story = `_x000D_
  My name is: ${name}_x000D_
  And I'm: ${age} years old_x000D_
`;_x000D_
_x000D_
console.log(story);
_x000D_
_x000D_
_x000D_

Browser compatibility:

Template string literal are natively supported by all major browser vendors (except Internet Explorer). So it is pretty save to use in your production code. A more detailed list of the browser compatibilities can be found here.

How to remove all white spaces from a given text file

This answer is similar to other however as some people have been complaining that the output goes to STDOUT i am just going to suggest redirecting it to the original file and overwriting it. I would never normally suggest this but sometimes quick and dirty works.

cat file.txt | tr -d " \t\n\r" > file.txt

What are the differences between Mustache.js and Handlebars.js?

—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:

    {{#variable}}<span class="text">{{.}}</span>{{/variable}}

Fit image to table cell [Pure HTML]

It's all about display: block :)

Updated:

Ok so you have the table, tr and td tags:

<table>
  <tr>
    <td>
      <!-- your image goes here -->
    </td>
  </tr>
</table>

Lets say your table or td (whatever define your width) has property width: 360px;. Now, when you try to replace the html comment with the actual image and set that image property for example width: 100%; which should fully fill out the td cell you will face the problem.

The problem is that your table cell (td) isn't properly filled with the image. You'll notice the space at the bottom of the cell which your image doesn't cover (it's like 5px of padding).

How to solve this in a simpliest way?

You are working with the tables, right? You just need to add the display property to your image so that it has the following:

img {
  width: 100%;
  display: block;
}

Initializing array of structures

There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.

Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data is declared as

typedef struct my_data {
  int a;
  const char *name;
  double x;
} my_data;

then your

my_data data[]={
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

is simply a more compact form of

my_data data[4]={
    { 0, "Peter", 0 },
    { 0, "James", 0 },
    { 0, "John", 0 },
    { 0, "Mike", 0 }
};

I hope you know what the latter does.

C++ Object Instantiation

There is an additional reason, which no one else has mentioned, why you might choose to create your object dynamically. Dynamic, heap based objects allow you to make use of polymorphism.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

You can use the synchronizedCollection/List method in java.util.Collection to get a thread-safe collection from a non-thread-safe one.

How do I find out if a column exists in a VB.Net DataRow

You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".

Notice: Array to string conversion in

The problem is that $money is an array and you are treating it like a string or a variable which can be easily converted to string. You should say something like:

 '.... Money:'.$money['money']

Using the star sign in grep

This may be the answer you're looking for:

grep abc MyFile | grep def

Only thing is... it will output lines were "def" is before OR after "abc"

How do I get Maven to use the correct repositories?

I think what you have missed here is this:

https://maven.apache.org/settings.html#Servers

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.

Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml like this:

<settings ...> 

        .
        .
        .
        <servers>
            <server>
              <id>internal-repository-group</id>
              <username>YOUR-USERNAME-HERE</username>
              <password>YOUR-PASSWORD-HERE</password>
            </server>
        </servers>
</settings>

EDIT:

You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.

The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.

Following is a sample pom of a project using "internal-repository-group"

<repositories>
    <repository>
        <id>internal-repository-group</id>
        <name>repo-name</name>
        <url>http://project.com/yourrepourl/</url>
        <layout>default</layout>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </snapshots>
    </repository>
</repositories>

How to change the background color of a UIButton while it's highlighted?

Try this !!!!

For TouchedDown Event set One color and for TouchUpInside set the other.

- (IBAction)touchedDown:(id)sender {
    NSLog(@"Touched Down");
    btn1.backgroundColor=[UIColor redColor];
}

- (IBAction)touchUpInside:(id)sender {
    NSLog(@"TouchUpInside");
    btn1.backgroundColor=[UIColor whiteColor];    
}

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

I work for a large corporation and encountered this same error, but needed a different work around. My issue was related to proxy settings. I had my proxy set up so I needed to set my no_proxy to whitelist AWS before I was able to get everything to work. You can set it in your bash script as well if you don't want to muddy up your Python code with os settings.

Python:

import os
os.environ["NO_PROXY"] = "s3.amazonaws.com"

Bash:

export no_proxy = "s3.amazonaws.com"

Edit: The above assume a US East S3 region. For other regions: use s3.[region].amazonaws.com where region is something like us-east-1 or us-west-2

Difference between a Structure and a Union

Here's the short answer: a struct is a record structure: each element in the struct allocates new space. So, a struct like

struct foobarbazquux_t {
    int foo;
    long bar;
    double baz; 
    long double quux;
}

allocates at least (sizeof(int)+sizeof(long)+sizeof(double)+sizeof(long double)) bytes in memory for each instance. ("At least" because architecture alignment constraints may force the compiler to pad the struct.)

On the other hand,

union foobarbazquux_u {
    int foo;
    long bar;
    double baz; 
    long double quux;
}

allocates one chunk of memory and gives it four aliases. So sizeof(union foobarbazquux_u) = max((sizeof(int),sizeof(long),sizeof(double),sizeof(long double)), again with the possibility of some addition for alignments.

SQL, How to convert VARCHAR to bigint?

I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.

select CONVERT(bigint,'60') as seconds 

and it returns

60

How can I convert a Word document to PDF?

Docx4j is open source and the best API for convert Docx to pdf without any alignment or font issue.

Maven Dependencies:

<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j-JAXB-Internal</artifactId>
    <version>8.0.0</version>
</dependency>
<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
    <version>8.0.0</version>
</dependency>
<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j-JAXB-MOXy</artifactId>
    <version>8.0.0</version>
</dependency>
<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j-export-fo</artifactId>
    <version>8.0.0</version>
</dependency>

Code:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;

public class DocToPDF {

    public static void main(String[] args) {
        
        try {
            InputStream templateInputStream = new FileInputStream("D:\\\\Workspace\\\\New\\\\Sample.docx");
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
            MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

            String outputfilepath = "D:\\\\Workspace\\\\New\\\\Sample.pdf";
            FileOutputStream os = new FileOutputStream(outputfilepath);
            Docx4J.toPDF(wordMLPackage,os);
            os.flush();
            os.close();
        } catch (Throwable e) {

            e.printStackTrace();
        } 
    }

}

get an element's id

You need to check if is a string to avoid getting a child element

var getIdFromDomObj = function(domObj){
   var id = domObj.id;
   return typeof id  === 'string' ? id : false;
};

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

phpinfo() - is there an easy way for seeing it?

If you have php installed on your local machine try:

$ php -a
Interactive shell

php > phpinfo();

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

Convert NSData to String?

Swift 5:

String(data: data!, encoding: String.Encoding.utf8)

Deleting objects from an ArrayList in Java

Most performant would, I guess, be using the listIterator method and do a reverse iteration:

for (ListIterator<E> iter = list.listIterator(list.size()); iter.hasPrevious();){
    if (weWantToDelete(iter.previous()))  iter.remove();
}

Edit: Much later, one might also want to add the Java 8 way of removing elements from a list (or any collection!) using a lambda or method reference. An in-place filter for collections, if you like:

list.removeIf(e -> e.isBad() && e.shouldGoAway());

This is probably the best way to clean up a collection. Since it uses internal iteration, the collection implementation could take shortcuts to make it as fast as possible (for ArrayLists, it could minimize the amount of copying needed).

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

Reverse Contents in Array

You can use the following example to reverse the contents in an array:

#include <iostream>

int main()
{
    int n, x;

    // order value for var x
    cin >> x;  

    // create array and the value for array is value var x
    int arr[x];

    // loop for insert values for array by reverse  
    for(int i=x; i > 0; i--) {

        // var i is number of elements in array 
        cin >> n;
        arr[i - 1] = n;
    }

    // show element in array
    for(int l = 0; l < x; l++) {
        cout<<arr[l]<<endl;
    }

    return 0;        
}

Unsupported method: BaseConfig.getApplicationIdSuffix()

If this ()Unsupported method: BaseConfig.getApplicationIdSuffix Android Project is old and you have updated Android Studio, what I did was simply CLOSE PROJECT and ran it again. It solved the issue for me. Did not add any dependencies or whatever as described by other answers.

How to pass a user / password in ansible command

When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).

Never used the feature but the docs say you can.

How to generate a random number between a and b in Ruby?

Just note the difference between the range operators:

3..10  # includes 10
3...10 # doesn't include 10

How to get week number in Python?

A lot of answers have been given, but id like to add to them.

If you need the week to display as a year/week style (ex. 1953 - week 53 of 2019, 2001 - week 1 of 2020 etc.), you can do this:

import datetime

year = datetime.datetime.now()
week_num = datetime.date(year.year, year.month, year.day).strftime("%V")
long_week_num = str(year.year)[0:2] + str(week_num)

It will take the current year and week, and long_week_num in the day of writing this will be:

>>> 2006

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

What does git push -u mean?

"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull or git push without arguments. A little bit down, this article explains and demonstrates this concept.

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A and then Ctrl+D. Doing this will detach you from the screen session which you can later resume by doing screen -r.

  • You can also do: Ctrl+A then type :. This will put you in screen command mode. Type the command detach to be detached from the running screen session.

Creating for loop until list.length

The answer depends on what do you need a loop for.

of course you can have a loop similar to Java:

for i in xrange(len(my_list)):

but I never actually used loops like this,

because usually you want to iterate

for obj in my_list

or if you need an index as well

for index, obj in enumerate(my_list)

or you want to produce another collection from a list

map(some_func, my_list)

[somefunc[x] for x in my_list]

also there are itertools module that covers most of iteration related cases

also please take a look at the builtins like any, max, min, all, enumerate

I would say - do not try to write Java-like code in python. There is always a pythonic way to do it.

Get the Id of current table row with Jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>

<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    alert(targ.innerHTML);
}

onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;
}

</script>



<body>

<table id="main"><tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr><tr>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr><tr>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
</tr></table>

</body>
</html>

Center an item with position: relative

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
}

Android WSDL/SOAP service client

Android doesn't come with SOAP library. However, you can download 3rd party library here:
https://github.com/simpligility/ksoap2-android

If you need help using it, you might find this thread helpful:
How to call a .NET Webservice from Android using KSOAP2?

Read .csv file in C

A complete example which leaves the fields as NULL-terminated strings in the original input buffer and provides access to them via an array of char pointers. The CSV processor has been confirmed to work with fields enclosed in "double quotes", ignoring any delimiter chars within them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// adjust BUFFER_SIZE to suit longest line 
#define BUFFER_SIZE 1024 * 1024
#define NUM_FIELDS 10
#define MAXERRS 5
#define RET_OK 0
#define RET_FAIL 1
#define FALSE 0
#define TRUE 1

// char* array will point to fields
char *pFields[NUM_FIELDS];
// field offsets into pFields array:
#define LP          0
#define IMIE        1
#define NAZWISKo    2
#define ULICA       3
#define NUMER       4
#define KOD         5
#define MIEJSCOw    6
#define TELEFON     7
#define EMAIL       8
#define DATA_UR     9

long loadFile(FILE *pFile, long *errcount);
static int  loadValues(char *line, long lineno);
static char delim;

long loadFile(FILE *pFile, long *errcount){

    char sInputBuf [BUFFER_SIZE];
    long lineno = 0L;

    if(pFile == NULL)
        return RET_FAIL;

    while (!feof(pFile)) {

        // load line into static buffer
        if(fgets(sInputBuf, BUFFER_SIZE-1, pFile)==NULL)
            break;

        // skip first line (headers)
        if(++lineno==1)
            continue;

        // jump over empty lines
        if(strlen(sInputBuf)==0)
            continue;
        // set pFields array pointers to null-terminated string fields in sInputBuf
        if(loadValues(sInputBuf,lineno)==RET_FAIL){
           (*errcount)++;
            if(*errcount > MAXERRS)
                break;
        } else {    
            // On return pFields array pointers point to loaded fields ready for load into DB or whatever
            // Fields can be accessed via pFields, e.g.
            printf("lp=%s, imie=%s, data_ur=%s\n", pFields[LP], pFields[IMIE], pFields[DATA_UR]);
        }
    }
    return lineno;
}


static int  loadValues(char *line, long lineno){
    if(line == NULL)
        return RET_FAIL;

    // chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.)
    // can be removed if sure fgets has removed both CR and LF from end of line
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1) == '\n')
        *(line + strlen(line)-1) = '\0';
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1 )== '\n')
        *(line + strlen(line)-1) = '\0';

    char *cptr = line;
    int fld = 0;
    int inquote = FALSE;
    char ch;

    pFields[fld]=cptr;
    while((ch=*cptr) != '\0' && fld < NUM_FIELDS){
        if(ch == '"') {
            if(! inquote)
                pFields[fld]=cptr+1;
            else {
                *cptr = '\0';               // zero out " and jump over it
            }
            inquote = ! inquote;
        } else if(ch == delim && ! inquote){
            *cptr = '\0';                   // end of field, null terminate it
            pFields[++fld]=cptr+1;
        }
        cptr++;
    }   
    if(fld > NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) exceeded on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;
    } else if (fld < NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) not reached on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;    
    }
    return RET_OK;
}

int main(int argc, char **argv)
{
   FILE *fp;
   long errcount = 0L;
   long lines = 0L;

   if(argc!=3){
       printf("Usage: %s csvfilepath delimiter\n", basename(argv[0]));
       return (RET_FAIL);
   }   
   if((delim=argv[2][0])=='\0'){
       fprintf(stderr,"delimiter must be specified\n");
       return (RET_FAIL);
   }
   fp = fopen(argv[1] , "r");
   if(fp == NULL) {
      fprintf(stderr,"Error opening file: %d\n",errno);
      return(RET_FAIL);
   }
   lines=loadFile(fp,&errcount);
   fclose(fp);
   printf("Processed %ld lines, encountered %ld error(s)\n", lines, errcount);
   if(errcount>0)
        return(RET_FAIL);
    return(RET_OK); 
}

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

or use display property with table-cell;

css

.table-layout {
    display:table;
    width:100%;
}
.table-layout .table-cell {
    display:table-cell;
    border:solid 1px #ccc;
}

.fixed-width-200 {
    width:200px;
}

html

<div class="table-layout">
    <div class="table-cell fixed-width-200">
        <p>fixed width div</p>
    </div>
    <div class="table-cell">
        <p>fluid width div</p>    
    </div>
</div>

http://jsfiddle.net/DnGDz/

Add CSS3 transition expand/collapse

http://jsfiddle.net/Bq6eK/215/

I did not modify your code for this solution, I wrote my own instead. My solution isn't quite what you asked for, but maybe you could build on it with existing knowledge. I commented the code as well so you know what exactly I'm doing with the changes.

As a solution to "avoid setting the height in JavaScript", I just made 'maxHeight' a parameter in the JS function called toggleHeight. Now it can be set in the HTML for each div of class expandable.

I'll say this up front, I'm not super experienced with front-end languages, and there's an issue where I need to click the 'Show/hide' button twice initially before the animation starts. I suspect it's an issue with focus.

The other issue with my solution is that you can actually figure out what the hidden text is without pressing the show/hide button just by clicking in the div and dragging down, you can highlight the text that's not visible and paste it to a visible space.

My suggestion for a next step on top of what I've done is to make it so that the show/hide button changes dynamically. I think you can figure out how to do that with what you already seem to know about showing and hiding text with JS.

Converting string into datetime

See my answer.

In real-world data this is a real problem: multiple, mismatched, incomplete, inconsistent and multilanguage/region date formats, often mixed freely in one dataset. It's not ok for production code to fail, let alone go exception-happy like a fox.

We need to try...catch multiple datetime formats fmt1,fmt2,...,fmtn and suppress/handle the exceptions (from strptime()) for all those that mismatch (and in particular, avoid needing a yukky n-deep indented ladder of try..catch clauses). From my solution

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):
    for fmt in fmts:
        try:
            return datetime.strptime(s, fmt)
        except:
            continue

    return None # or reraise the ValueError if no format matched, if you prefer

Positioning background image, adding padding

first off, to be a bit of a henpeck, its best NOT to use just the <background> tag. rather, use the proper, more specific, <background-image> tag.

the only way that i'm aware of to do such a thing is to build the padding into the image by extending the matte. since the empty pixels aren't stripped, you have your padding right there. so if you need a 10px border, create 10px of empty pixels all around your image. this is mui simple in Photoshop, Fireworks, GIMP, &c.

i'd also recommend trying out the PNG8 format instead of the dying GIF... much better.

there may be an alternate solution to your problem if we knew a bit more of how you're using it. :) it LOOKS like you're trying to add an accordion button. this would be best placed in the HTML because then you can target it with JavaScript/PHP; something you cannot do if it's in the background (at least not simply). in such a case, you can style the heck out of the image you currently have in CSS by using the following:

#hello img { padding: 10px; }

WR!

How can I change the app display name build with Flutter?

First Rename your AndroidManifest.xml file

android:label="Your App Name"

Second Rename Your Application Name in Pubspec.yaml file name: Your Application Name

Third Change Your Application logo

flutter_icons:
   android: "launcher_icon"
   ios: true
   image_path: "assets/path/your Application logo.formate"

Fourth Run

flutter pub pub run flutter_launcher_icons:main

Make an image responsive - the simplest way

Images should be set like this

img { max-width: 100%; }

Put icon inside input element in a form

You Can Try this : Bootstrap-4 Beta
https://www.codeply.com/go/W25zyByhec

<div class="container">
            <form>
                <div class="row">
                    <div class="input-group mb-3 col-sm-6">
                      <input type="text" class="form-control border-right-0" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
                        <div class="input-group-prepend bg-white">
                            <span class="input-group-text border-left-0 rounded-right bg-white" id="basic-addon1"><i class="fas fa-search"></i></span>
                        </div>
                    </div>
                </div>
            </form>
        </div>

??

How to link html pages in same or different folders?

use the relative path

main page might be: /index.html

secondary page: /otherFolder/otherpage.html

link would be like so:

<a href="/otherFolder/otherpage.html">otherpage</a>

How do I remove a property from a JavaScript object?

Two ways to delete an object

  1. using for in

    function deleteUser(key) {
    
     const newUsers = {}; 
     for (const uid in users) {
           if (uid !== key) {
           newUsers[uid] = users[uid];
     }
     return newUsers
    }
    

or

delete users[key]

c++ string array initialization

With support for C++11 initializer lists it is very easy:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

using Strings = vector<string>;

void foo( Strings const& strings )
{
    for( string const& s : strings ) { cout << s << endl; }
}

auto main() -> int
{
    foo( Strings{ "hi", "there" } ); 
}

Lacking that (e.g. for Visual C++ 10.0) you can do things like this:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

typedef vector<string> Strings;

void foo( Strings const& strings )
{
    for( auto it = begin( strings );  it != end( strings );  ++it )
    {
        cout << *it << endl;
    }
}

template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }

template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
    v.push_back( a );
    return v;
}

int main()
{
    foo( r( Strings() ) << "hi" << "there" ); 
}

get path for my .exe

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

Why does git revert complain about a missing -m option?

Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of

$ git lola
*   2582152 (HEAD, master) Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

Note: git lola is a non-standard but useful alias.

No dice with git revert:

$ git revert HEAD
fatal: Commit 2582152... is a merge but no -m option was given.

Charles Bailey gave an excellent answer as usual. Using git revert as in

$ git revert --no-edit -m 1 HEAD
[master e900aad] Revert "Merge branch 'otherguy'"
 0 files changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 bar

effectively deletes bar and produces a history of

$ git lola
* e900aad (HEAD, master) Revert "Merge branch 'otherguy'"
*   2582152 Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

But I suspect you want to throw away the merge commit:

$ git reset --hard HEAD^
HEAD is now at b7e7176 baz

$ git lola
* b7e7176 (HEAD, master) baz
| * c7256de (otherguy) bar
|/  
* 9968f79 foo

As documented in the git rev-parse manual

<rev>^, e.g. HEAD^, v1.5.1^0
A suffix ^ to a revision parameter means the first parent of that commit object. ^<n> means the n-th parent (i.e. <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when <rev> is the object name of a tag object that refers to a commit object.

so before invoking git reset, HEAD^ (or HEAD^1) was b7e7176 and HEAD^2 was c7256de, i.e., respectively the first and second parents of the merge commit.

Be careful with git reset --hard because it can destroy work.

Driver executable must be set by the webdriver.ie.driver system property

For spring :

File inputFile = new ClassPathResource("\\chrome\\chromedriver.exe").getFile();
System.setProperty("webdriver.chrome.driver",inputFile.getCanonicalPath());

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.

\begin{description} 
     <YOUR TEXT HERE> 
\end{description}
  • This only worked on windows latex compiler

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

Try:

InputStream inputStream= // Your InputStream from your database.
Reader reader = new InputStreamReader(inputStream,"UTF-8");

InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");

saxParser.parse(is, handler);

If it's anything else than UTF-8, just change the encoding part for the good one.

How to add results of two select commands in same query

Yes. It is possible :D

SELECT  SUM(totalHours) totalHours
FROM
        ( 
            select sum(hours) totalHours from resource
            UNION ALL
            select sum(hours) totalHours from projects-time
        ) s

As a sidenote, the tablename projects-time must be delimited to avoid syntax error. Delimiter symbols vary on RDBMS you are using.

How to change options of <select> with jQuery?

Old school of doing things by hand has always been good for me.

  1. Clean the select and leave the first option:

        $('#your_select_id').find('option').remove()
        .end().append('<option value="0">Selec...</option>')
        .val('whatever');
    
  2. If your data comes from a Json or whatever (just Concat the data):

        var JSONObject = JSON.parse(data);
        newOptionsSelect = '';
        for (var key in JSONObject) {
            if (JSONObject.hasOwnProperty(key)) {
                var newOptionsSelect = newOptionsSelect + '<option value="'+JSONObject[key]["value"]+'">'+JSONObject[key]["text"]+'</option>';
            }
        }
    
        $('#your_select_id').append( newOptionsSelect );
    
  3. My Json Objetc:

        [{"value":1,"text":"Text 1"},{"value":2,"text":"Text 2"},{"value":3,"text":"Text 3"}]
    

This solution is ideal for working with Ajax, and answers in Json from a database.

SQL Server - Return value after INSERT

This is how I use OUTPUT INSERTED, when inserting to a table that uses ID as identity column in SQL Server:

'myConn is the ADO connection, RS a recordset and ID an integer
Set RS=myConn.Execute("INSERT INTO M2_VOTELIST(PRODUCER_ID,TITLE,TIMEU) OUTPUT INSERTED.ID VALUES ('Gator','Test',GETDATE())")
ID=RS(0)

JavaScript implementation of Gzip

I ported an implementation of LZMA from a GWT module into standalone JavaScript. It's called LZMA-JS.

intellij incorrectly saying no beans of type found for autowired repository

What you need to do is add

@ComponentScan("package/include/your/annotation/component") in AppConfiguration.java.

Since I think your AppConfiguraion.java's package is deeper than your annotation component (@Service, @Component...)'s package,

such as "package/include/your/annotation/component/deeper/config".

How do you allow spaces to be entered using scanf?

You can use the fgets() function to read a string or use scanf("%[^\n]s",name); so string reading will terminate upon encountering a newline character.

How to use Visual Studio Code as Default Editor for Git

For what I understand, VSCode is not in AppData anymore.

So Set the default git editor by executing that command in a command prompt window:

git config --global core.editor "'C:\Program Files (x86)\Microsoft VS Code\code.exe' -w"

The parameter -w, --wait is to wait for window to be closed before returning. Visual Studio Code is base on Atom Editor. if you also have atom installed execute the command atom --help. You will see the last argument in the help is wait.

Next time you do a git rebase -i HEAD~3 it will popup Visual Studio Code. Once VSCode is close then Git will take back the lead.

Note: My current version of VSCode is 0.9.2

I hope that help.

Enter key press in C#

private void Input_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            MessageBox.Show("Enter pressed");
        }
    }

This worked for me.

SSL Connection / Connection Reset with IISExpress

I am summarizing the steps that helped me in resolving this issue:

  1. Make sure the SSL port range(used by IIS express) is between 44300-44398

During installation, IIS Express uses Http.sys to reserve ports 44300 through 44399 for SSL use. This enables standard users (without elevated privileges) of IISExpress to configure and use SSL. For more details on this refer here

  1. Run the below command as administrator in Command prompt. This will output the SSL Certificate bindings in the computer. From this list, find out the certificate used by IIS express for the corresponding port :

netsh http show sslcert > sslcert.txt

  1. Look for the below items in the sslcert.txt (in my case the IIS express was running at port 44300)

IP:port : 0.0.0.0:44300

Certificate Hash : eb380ba6bd10fb4f597cXXXXXXXXXX

Application ID : {214124cd-d05b-4309-XXX-XXXXXXX}

  1. Also look in the IIS express management console (RUN (Ctrl+R) -> inetmgr.exe) and find if the corresponding certificate exists in the Server Certificates

(Click on the ServerRoot -> under section IIS () -> Open the Server Certificates)

  1. If your localhost by default uses a different certificate other than the one listed in Step 3, continue with the below steps

netsh http delete sslcert ipport=0.0.0.0:44300

netsh http add sslcert ipport=0.0.0.0:44300 certhash=New_Certificate_Hash_without_space appid={214124cd-d05b-4309-XXX-XXXXXXX}

The New_Certificate_Hash will be your default certificate tied-up with your localhost (That we found in step 4) or the one which you want to add as a new certificate.

P.S. Thank you for your answer uos?? (which helped me in resolving this issue)

How to put scroll bar only for modal-body?

A simple js solution to set modal height proportional to body's height :

$(document).ready(function () {
    $('head').append('<style type="text/css">.modal .modal-body {max-height: ' + ($('body').height() * .8) + 'px;overflow-y: auto;}.modal-open .modal{overflow-y: hidden !important;}</style>');
});

body's height has to be 100% :

html, body {
    height: 100%;
    min-height: 100%;
}

I set modal body height to 80% of body, this can be of course customized.

Hope it helps.

How to specify new GCC path for CMake

Change CMAKE_<LANG>_COMPILER path without triggering a reconfigure

I wanted to compile with an alternate compiler, but also pass -D options on the command-line which would get wiped out by setting a different compiler. This happens because it triggers a re-configure. The trick is to disable the compiler detection with NONE, set the paths with FORCE, then enable_language.

project( sample_project NONE )

set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" FORCE )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" FORCE )

enable_language( C CXX )

Use a Toolchain file

The more sensible choice is to create a toolchain file.

set( CMAKE_SYSTEM_NAME Darwin )

set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" )

Then you invoke Cmake with an additional flag

cmake -D CMAKE_TOOLCHAIN_FILE=/path/to/toolchain_file.cmake ...

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

How to log out user from web site using BASIC authentication?

Here's a very simple Javascript example using jQuery:

function logout(to_url) {
    var out = window.location.href.replace(/:\/\//, '://log:out@');

    jQuery.get(out).error(function() {
        window.location = to_url;
    });
}

This log user out without showing him the browser log-in box again, then redirect him to a logged out page

jQuery Ajax PUT with parameters

Can you provide an example, because put should work fine as well?

Documentation -

The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url) -

$.ajax({
  url: '/echo/html/',
  type: 'PUT',
  data: "name=John&location=Boston",
  success: function(data) {
    alert('Load was performed.');
  }
});

Demo tested from jQuery 1.3.2 onwards on Chrome.

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Here are my 2 cents = 5 methods ;)

I like encapsulate these details and have AppCode tell me how to finish my sentences.

void dispatch_after_delay(float delayInSeconds, dispatch_queue_t queue, dispatch_block_t block) {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, queue, block);
}

void dispatch_after_delay_on_main_queue(float delayInSeconds, dispatch_block_t block) {
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_after_delay(delayInSeconds, queue, block);
}

void dispatch_async_on_high_priority_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), block);
}

void dispatch_async_on_background_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block);
}

void dispatch_async_on_main_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_main_queue(), block);
}

Parsing string as JSON with single quotes?

If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.

var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');

The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()

Clearing all cookies with JavaScript

//Delete all cookies
function deleteAllCookies() {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + '=;' +
            'expires=Thu, 01-Jan-1970 00:00:01 GMT;' +
            'path=' + '/;' +
            'domain=' + window.location.host + ';' +
            'secure=;';
    }
}

Execute a PHP script from another PHP script

If it is a linux box you would run something like:

php /folder/script.php

On Windows, you would need to make sure your php.exe file is part of your PATH, and do a similar approach to the file you want to run:

php C:\folder\script.php

How to apply two CSS classes to a single element

1) Use multiple classes inside the class attribute, separated by whitespace (ref):

<a class="c1 c2">aa</a>

2) To target elements that contain all of the specified classes, use this CSS selector (no space) (ref):

.c1.c2 {
}

What is your favorite C programming trick?

While reading Quake 2 source code I came up with something like this:

double normals[][] = {
  #include "normals.txt"
};

(more or less, I don't have the code handy to check it now).

Since then, a new world of creative use of the preprocessor opened in front of my eyes. I no longer include just headers, but entire chunks of code now and then (it improves reusability a lot) :-p

Thanks John Carmack! xD

Javascript - Track mouse position

I believe that we are overthinking this,

_x000D_
_x000D_
function mouse_position(e)_x000D_
{_x000D_
//do stuff_x000D_
}
_x000D_
<body onmousemove="mouse_position(event)"></body>
_x000D_
_x000D_
_x000D_

How to import CSV file data into a PostgreSQL table?

If you need simple mechanism to import from text/parse multiline CSV you could use:

CREATE TABLE t   -- OR INSERT INTO tab(col_names)
AS
SELECT
   t.f[1] AS col1
  ,t.f[2]::int AS col2
  ,t.f[3]::date AS col3
  ,t.f[4] AS col4
FROM (
  SELECT regexp_split_to_array(l, ',') AS f
  FROM regexp_split_to_table(
$$a,1,2016-01-01,bbb
c,2,2018-01-01,ddd
e,3,2019-01-01,eee$$, '\n') AS l) t;

DBFiddle Demo

PUT vs. POST in REST

At the risk of restating what has already been said, it seems important to remember that PUT implies that the client controls what the URL is going to end up being, when creating a resource. So part of the choice between PUT and POST is going to be about how much you can trust the client to provide correct, normalized URL that are coherent with whatever your URL scheme is.

When you can't fully trust the client to do the right thing, it would be more appropriate to use POST to create a new item and then send the URL back to the client in the response.

Escape invalid XML characters in C#

Use SecurityElement.Escape

using System;
using System.Security;

class Sample {
  static void Main() {
    string text = "Escape characters : < > & \" \'";
    string xmlText = SecurityElement.Escape(text);
//output:
//Escape characters : &lt; &gt; &amp; &quot; &apos;
    Console.WriteLine(xmlText);
  }
}

How to restore default perspective settings in Eclipse IDE

From the Window menu, Reset Perspective

How to extract Month from date in R

Her is another R base approach:

From your example: Some date:

Some_date<-"01/01/1979"

We tell R, "That is a Date"

Some_date<-as.Date(Some_date)

We extract the month:

months(Some_date)

output: [1] "January"

Finally, we can convert it to a numerical variable:

as.numeric(as.factor(months(Some_date)))

outpt: [1] 1

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is Linux specific and is an environment variable pointing to directories where the dynamic loader should look for shared libraries.

Try to add the directory where your .dll is in the PATH variable. Windows will automatically look in the directories listet in this environment variable. LD_LIBRARY_PATH probably won't solve the problem (unless the JVM uses it - I do not know about that).

What is the difference between MOV and LEA?

As stated in the other answers:

  • MOV will grab the data at the address inside the brackets and place that data into the destination operand.
  • LEA will perform the calculation of the address inside the brackets and place that calculated address into the destination operand. This happens without actually going out to the memory and getting the data. The work done by LEA is in the calculating of the "effective address".

Because memory can be addressed in several different ways (see examples below), LEA is sometimes used to add or multiply registers together without using an explicit ADD or MUL instruction (or equivalent).

Since everyone is showing examples in Intel syntax, here are some in AT&T syntax:

MOVL 16(%ebp), %eax       /* put long  at  ebp+16  into eax */
LEAL 16(%ebp), %eax       /* add 16 to ebp and store in eax */

MOVQ (%rdx,%rcx,8), %rax  /* put qword at  rcx*8 + rdx  into rax */
LEAQ (%rdx,%rcx,8), %rax  /* put value of "rcx*8 + rdx" into rax */

MOVW 5(%bp,%si), %ax      /* put word  at  si + bp + 5  into ax */
LEAW 5(%bp,%si), %ax      /* put value of "si + bp + 5" into ax */

MOVQ 16(%rip), %rax       /* put qword at rip + 16 into rax                 */
LEAQ 16(%rip), %rax       /* add 16 to instruction pointer and store in rax */

MOVL label(,1), %eax      /* put long at label into eax            */
LEAL label(,1), %eax      /* put the address of the label into eax */

How to get query string parameter from MVC Razor markup?

For Asp.net Core 2

ViewContext.ModelState["id"].AttemptedValue

Get width height of remote image from url

Get image size with jQuery
(depending on which formatting method is more suitable for your preferences):

function getMeta(url){
    $('<img/>',{
        src: url,
        on: {
            load: (e) => {
                console.log('image size:', $(e.target).width(), $(e.target).height());
            },
        }
    });
}

or

function getMeta(url){
    $('<img/>',{
        src: url,
    }).on({
        load: (e) => {
            console.log('image size:', $(e.target).width(), $(e.target).height());
        },
    });
}

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

Connecting to a network folder with username/password in Powershell

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either use net use or the WScript.Network object, calling the MapNetworkDrive function:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist

How to store(bitmap image) and retrieve image from sqlite database in android?

If you are working with Android's MediaStore database, here is how to store an image and then display it after it is saved.

on button click write this

 Intent in = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            in.putExtra("crop", "true");
            in.putExtra("outputX", 100);
            in.putExtra("outputY", 100);
            in.putExtra("scale", true);
            in.putExtra("return-data", true);

            startActivityForResult(in, 1);

then do this in your activity

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

            Bitmap bmp = (Bitmap) data.getExtras().get("data");

            img.setImageBitmap(bmp);
            btnadd.requestFocus();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] b = baos.toByteArray();
            String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);

            byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
            Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
                    bytarray.length);

        }

    }

What is "git remote add ..." and "git push origin master"?

  1. The .git at the end of the repository name is just a convention. Typically, on git servers repositories are kept in directories named project.git. The git client and protocol honours this convention by testing for project.git when only project is specified.

  2. git://[email protected]/peter/first_app.git is not a valid git url. git repositories can be identified and accessed via various url schemes specified here. [email protected]:peter/first_app.git is the ssh url mentioned on that page.

  3. git is flexible. It allows you to track your local branch against almost any branch of any repository. While master (your local default branch) tracking origin/master (the remote default branch) is a popular situation, it is not universal. Many a times you may not want to do that. This is why the first git push is so verbose. It tells git what to do with the local master branch when you do a git pull or a git push.

  4. The default for git push and git pull is to work with the current branch's remote. This is a better default than origin master. The way git push determines this is explained here.

git is fairly elegant and comprehensible but there is a learning curve to walk through.

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

As per the documentation: This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.

This function is only available at Python start-up time, when Python scans the environment. It has to be called in a system-wide module, sitecustomize.py, After this module has been evaluated, the setdefaultencoding() function is removed from the sys module.

The only way to actually use it is with a reload hack that brings the attribute back.

Also, the use of sys.setdefaultencoding() has always been discouraged, and it has become a no-op in py3k. The encoding of py3k is hard-wired to "utf-8" and changing it raises an error.

I suggest some pointers for reading:

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

My issue was due to what physical USB female port I plugged the Arduino cable into on my D-Link DUB-H7 (USB hub) on Windows 10. I had my Arduino plugged into one of the two ports way on the right (in the image below). The USB cable fit, and it powers the Arduino fine, but the Arduino wasn't seeing the port for some reason.

enter image description here

Windows does not recognize these two ports. Any of the other ports are fair game. In my case, the Tools > Port menu was grayed out. In this scenario, the "Ports" section in the object explorer was hidden. So to show the hidden devices, I chose View > show hidden. COM1 was what showed up originally. When I changed it to COM3, it didn't work.

There are many places where the COM port can be configured.

Windows > Control Panel > Device Manager > Ports > right click Arduino > Properties > Port Settings > Advanced > COM Port Number: [choose port]

Windows > Start Menu > Arduino > Tools > Ports > [choose port]

Windows > Start Menu > Arduino > File > Preferences > @ very bottom, there is a label named "More preferences can be edited directly in the file".

C:\Users{user name}\AppData\Local\Arduino15\preferences.txt

target_package = arduino
target_platform = avr
board = uno
software=ARDUINO
# Warn when data segment uses greater than this percentage
build.warn_data_percentage = 75

programmer = arduino:avrispmkii

upload.using = bootloader
upload.verify = true

serial.port=COM3
serial.databits=8
serial.stopbits=1
serial.parity=N
serial.debug_rate=9600

# I18 Preferences

# default chosen language (none for none)
editor.languages.current = 

The user preferences.txt overrides this one:

C:\Users{user name}\Desktop\avrdude.conf

... search for "com" ... "com1" is the default

Why is Event.target not Element in Typescript?

JLRishe's answer is correct, so I simply use this in my event handler:

if (event.target instanceof Element) { /*...*/ }

Globally catch exceptions in a WPF application?

In addition what others mentioned here, note that combining the Application.DispatcherUnhandledException (and its similars) with

<configuration>
  <runtime>  
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>

in the app.config will prevent your secondary threads exception from shutting down the application.

What are the main performance differences between varchar and nvarchar SQL Server data types?

Always use nvarchar.

You may never need the double-byte characters for most applications. However, if you need to support double-byte languages and you only have single-byte support in your database schema it's really expensive to go back and modify throughout your application.

The cost of migrating one application from varchar to nvarchar will be much more than the little bit of extra disk space you'll use in most applications.

Youtube iframe wmode issue

Add &amp;wmode=transparent to the url and you're done, tested.

I use that technique in my own wordpress plugin YouTube shortcode

Check its source code if you encounter any issue.

Delete directory with files in it?

If you are not sure, Given path is directory or file then you can use this function to delete path

function deletePath($path) {
        if(is_file($path)){
            unlink($path);
        } elseif(is_dir($path)){
            $path = (substr($path, -1) !== DIRECTORY_SEPARATOR) ? $path . DIRECTORY_SEPARATOR : $path;
            $files = glob($path . '*');
            foreach ($files as $file) {
                deleteDirPath($file);
            }
            rmdir($path);
        } else {
            return false;
        }
}

Parsing JSON string in Java

you have an extra "}" in each object, you may write the json string like this:

public class ShowActivity {   
    private final static String  jString = "{" 
    + "    \"geodata\": [" 
    + "        {" 
    + "                \"id\": \"1\"," 
    + "                \"name\": \"Julie Sherman\","                  
    + "                \"gender\" : \"female\"," 
    + "                \"latitude\" : \"37.33774833333334\"," 
    + "                \"longitude\" : \"-121.88670166666667\""            
    + "                }" 
    + "        }," 
    + "        {" 
    + "                \"id\": \"2\"," 
    + "                \"name\": \"Johnny Depp\","          
    + "                \"gender\" : \"male\"," 
    + "                \"latitude\" : \"37.336453\"," 
    + "                \"longitude\" : \"-121.884985\""            
    + "                }" 
    + "        }" 
    + "    ]" 
    + "}"; 
}

Change route params without reloading in Angular 2

For me it was actually a mix of both with Angular 4.4.5.

Using router.navigate kept destroying my url by not respecting the realtiveTo: activatedRoute part.

I've ended up with:

this._location.go(this._router.createUrlTree([this._router.url], { queryParams: { profile: value.id } }).toString())

Parse a URI String into Name-Value Collection

org.apache.http.client.utils.URLEncodedUtils

is a well known library that can do it for you

import org.apache.hc.client5.http.utils.URLEncodedUtils

String url = "http://www.example.com/something.html?one=1&two=2&three=3&three=3a";

List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), Charset.forName("UTF-8"));

for (NameValuePair param : params) {
  System.out.println(param.getName() + " : " + param.getValue());
}

Outputs

one : 1
two : 2
three : 3
three : 3a

Oracle: Import CSV file

SQL Loader helps load csv files into tables: SQL*Loader

If you want sqlplus only, then it gets a bit complicated. You need to locate your sqlloader script and csv file, then run the sqlldr command.

Import pandas dataframe column as string not int

Just want to reiterate this will work in pandas >= 0.9.1:

In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

I'm creating an issue about detecting integer overflows also.

EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247

Update as it helps others:

To have all columns as str, one can do this (from the comment):

pd.read_csv('sample.csv', dtype = str)

To have most or selective columns as str, one can do this:

# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)

How to change environment's font size?

In Visual Studio Code, the font-size can be easily changed from the Settings tab.

The simplest way to do this is to press Ctrl + Shift + P and then type 'Settings'. This will show you a few results. Choose 'Settings(UI)'. The Settings tab will get opened in the editor. Now you can change the font settings from here. This will only affect the editor's font.

Or, you can also click on the settings icon on the left bottom of the window and search for font from there.

enter image description here

In order to change the font size of the entire environment, you may consider pressing ctrl++. This will work like zooming into the whole environment, resulting in an increased font-size.

Select Settings(UI)

UIImageView - How to get the file name of the image assigned?

Or you can use the restoration identifier, like this:

let myImageView = UIImageView()
myImageView.image = UIImage(named: "anyImage")
myImageView.restorationIdentifier = "anyImage" // Same name as image's name!

// Later, in UI Tests:
print(myImageView.restorationIdentifier!) // Prints "anyImage"

Basically in this solution you're using the restoration identifier to hold the image's name, so you can use it later anywhere. If you update the image, you must also update the restoration identifier, like this:

myImageView.restorationIdentifier = "newImageName"

I hope that helps you, good luck!

Handling onchange event in HTML.DropDownList Razor MVC

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })

where

@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

PHP : send mail in localhost

I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.

<?php
include 'nav.php';
/*
    Download PhpMailer from the following link:
    https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
    Extract the PHPMailer-master folder into your xampp->htdocs folder
    Make changes in the following code and its done :-)

    You will receive the mail with the name Root User.
    To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
    And change the name here: 
    public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some   //other folder
ini_set("SMTP","ssl://smtp.gmail.com"); 
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP();  // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject  = "Eventbook";
$mail->Body     = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo  //Fill in the document.location thing
'<script type="text/javascript">
                        if(confirm("Your mail has been sent"))
                        document.location = "/";
        </script>';
}
?>

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

Reading in a JSON File Using Swift

Updated for Swift 3 with safest way

    private func readLocalJsonFile() {

    if let urlPath = Bundle.main.url(forResource: "test", withExtension: "json") {

        do {
            let jsonData = try Data(contentsOf: urlPath, options: .mappedIfSafe)

            if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String: AnyObject] {

                if let personArray = jsonDict["person"] as? [[String: AnyObject]] {

                    for personDict in personArray {

                        for (key, value) in personDict {

                            print(key, value)
                        }
                        print("\n")
                    }
                }
            }
        }

        catch let jsonError {
            print(jsonError)
        }
    }
}

enter image description here

How to avoid soft keyboard pushing up my layout?

I had the same problem, but setting windowSoftInputMode did not help, and I did not want to change the upper view to have isScrollContainer="false" because I wanted it to scroll.

My solution was to define the top location of the navigation tools instead of the bottom. I'm using Titanium, so I'm not sure exactly how this would translate to android. Defining the top location of the navigation tools view prevented the soft keyboard from pushing it up, and instead covered the nav controls like I wanted.

Chrome blocks different origin requests

This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).

To avoid it, the browser check the Same-origin policy

Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:

generate random string for div id

Based on HTML 4, the id should start from letter:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

So, one of the solutions could be (alphanumeric):

  var length = 9;
  var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter

  // Convert it to base 36 (numbers + letters), and grab the first 9 characters
  // after the decimal.
  var id = prefix + Math.random().toString(36).substr(2, length);

Another solution - generate string with letters only:

  var length = 9;
  var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);

How do I convert Long to byte[] and back in java

 public static long bytesToLong(byte[] bytes) {
        if (bytes.length > 8) {
            throw new IllegalMethodParameterException("byte should not be more than 8 bytes");

        }
        long r = 0;
        for (int i = 0; i < bytes.length; i++) {
            r = r << 8;
            r += bytes[i];
        }

        return r;
    }



public static byte[] longToBytes(long l) {
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        while (l != 0) {
            bytes.add((byte) (l % (0xff + 1)));
            l = l >> 8;
        }
        byte[] bytesp = new byte[bytes.size()];
        for (int i = bytes.size() - 1, j = 0; i >= 0; i--, j++) {
            bytesp[j] = bytes.get(i);
        }
        return bytesp;
    }

Characters allowed in a URL

The characters allowed in a URI are either reserved or unreserved (or a percent character as part of a percent-encoding)

http://en.wikipedia.org/wiki/Percent-encoding#Types_of_URI_characters

says these are RFC 3986 unreserved characters (sec. 2.3) as well as reserved characters (sec 2.2) if they need to retain their special meaning. And also a percent character as part of a percent-encoding.

Detect the Enter key in a text input field

It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.

        <script type="text/javascript"> 
        function stopRKey(evt) { 
          var evt = (evt) ? evt : ((event) ? event : null); 
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
          if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
        } 

        document.onkeypress = stopRKey; 

        </script>

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

If you'd start Tomcat manually (not as service), then the CATALINA_OPTS environment variable is the way to go. If you'd start it as a service, then the settings are probably stored somewhere in the registry. I have Tomcat 6 installed in my machine and I found the settings at the HKLM\SOFTWARE\Apache Software Foundation\Procrun 2.0\Tomcat6\Parameters\Java key.

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

I got this issue on a Web API project. Finally figured out that it was in my "///" method comments. I have these comments set to auto-generate documentation for the API methods. Something in my comments made it go crazy. I deleted all the carriage returns, special characters, etc. Not really sure which thing it didn't like, but it worked.

"CAUTION: provisional headers are shown" in Chrome debugger

I believe it happens when the actual request is not sent. Usually happens when you are loading a cached resource.

Jquery get input array field

I think the best way, is to use a Propper Form and to use jQuery.serializeArray.

<!-- a form with any type of input -->
<form class="a-form">
    <select name="field[something]">...</select>
    <input type="checkbox" name="field[somethingelse]" ... />
    <input type="radio" name="field[somethingelse2]" ... />
    <input type="text" name="field[somethingelse3]" ... />
</form>

<!-- sample ajax call -->
<script>
$(document).ready(function(){
    $.ajax({
        url: 'submit.php',
        type: 'post',
        data: $('form.a-form').serializeArray(),
        success: function(response){
            ...
        }
    });
});
</script>

The Values will be available in PHP as $_POST['field'][INDEX].

Entity Framework code first unique column

EF doesn't support unique columns except keys. If you are using EF Migrations you can force EF to create unique index on UserName column (in migration code, not by any annotation) but the uniqueness will be enforced only in the database. If you try to save duplicate value you will have to catch exception (constraint violation) fired by the database.

Only using @JsonIgnore during serialization, but not deserialization

Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore to the getter.

Which you've tried:

Add @JsonIgnore on the getter method only

Do this, and also add a specific @JsonProperty annotation for your JSON "password" field name to the setter method for the password on your object.

More recent versions of Jackson have added READ_ONLY and WRITE_ONLY annotation arguments for JsonProperty. So you could also do something like:

@JsonProperty(access = Access.WRITE_ONLY)
private String password;

Docs can be found here.

A regular expression to exclude a word/string

As you want to exclude both words, you need a conjuction:

^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$

Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.

splitting a string into an array in C++ without using vector

#define MAXSPACE 25

string line =  "test one two three.";
string arr[MAXSPACE];
string search = " ";
int spacePos;
int currPos = 0;
int k = 0;
int prevPos = 0;

do
{

    spacePos = line.find(search,currPos);

    if(spacePos >= 0)
    {

        currPos = spacePos;
        arr[k] = line.substr(prevPos, currPos - prevPos);
        currPos++;
        prevPos = currPos;
        k++;
    }


}while( spacePos >= 0);

arr[k] = line.substr(prevPos,line.length());

for(int i = 0; i < k; i++)
{
   cout << arr[i] << endl;
}

PHP foreach loop through multidimensional array

<?php
$first = reset($arr_nav); // Get the first element
$last  = end($arr_nav);   // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) { 
   $first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
   $last['class'] = 'last';
}

Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

How to write JUnit test with Spring Autowire?

You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:

@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
    @Autowired
    private WebApplicationContext wac;
}

How to mount the android img file under linux?

I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img files all the time.

Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount

"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...

So, how to get the file from the inside of userdata.img?" To load .img files you have to select loop and load the .img Select loop

Next you select mount Select mount

Furius ISO mount handles all the other options loading the .img file to your /home/dir.

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Just my 2 Cents here ..

Bootstrap.yml or Bootstrap.properties is used to fetch the config from Spring Cloud Server.

For Example, in My Bootstrap.properties file I have the following Config

spring.application.name=Calculation-service
spring.cloud.config.uri=http://localhost:8888

On starting the application , It tries to fetch the configuration for the service by connecting to http://localhost:8888 and looks at Calculation-service.properties present in Spring Cloud Config server

You can validate the same from logs of Calcuation-Service when you start it up

INFO 10988 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How do I convert a String to a BigInteger?

According to the documentation:

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

It means that you can use a String to initialize a BigInteger object, as shown in the following snippet:

sum = sum.add(new BigInteger(newNumber));

Package php5 have no installation candidate (Ubuntu 16.04)

Currently, I am using Ubuntu 16.04 LTS. Me too was facing same problem while Fetching the Postgress Database values using Php so i resolved it by using the below commands.

Mine PHP version is 7.0, so i tried the below command.

apt-get install php-pgsql

Remember to restart Apache.

/etc/init.d/apache2 restart

How to parse XML using jQuery?

I went the way of jQuery's .parseXML() however found that the XML path syntax of 'Page[Name="test"] > controls > test' wouldn't work (if anyone knows why please shout out!).

Instead I chained together the individual .find() results into something that looked like this:

$xmlDoc.find('Page[Name="test"]')
       .find('contols')
       .find('test')

The result achieves the same as what I would expect the one shot find.

SQL Server Output Clause into a scalar variable

Over a year later... if what you need is get the auto generated id of a table, you can just

SELECT @ReportOptionId = SCOPE_IDENTITY()

Otherwise, it seems like you are stuck with using a table.

Duplicate symbols for architecture x86_64 under Xcode

I just encoutered the problem. The pod deintegrate or Removing podfile.lock ways would be helpful for you, but try the following sequence , that may be more helpful than deintegrating the pod files

  • Comment all the pods in Podfile
  • run the pod install, it will remove Pods folder from the project
  • Uncomment all the pods in Podfile
  • run again pod install

android pinch zoom

I have an open source library that does this very well. It's a four gesture library that comes with an out-of-the-box pan zoom setting. You can find it here: https://bitbucket.org/warwick/hacergestov3 Or you can download the demo app here: https://play.google.com/store/apps/details?id=com.WarwickWestonWright.HacerGestoV3Demo This is a pure canvas library so it can be used in pretty any scenario. Hope this helps.

How to remove numbers from string using Regex.Replace?

the best design is:

public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

Check whether a value exists in JSON object

Why not JSON.stringify and .includes()?

You can easily check if a JSON object includes a value by turning it into a string and checking the string.

console.log(JSON.stringify(JSONObject).includes("dog"))
--> true

Edit: make sure to check browser compatibility for .includes()

Algorithm for solving Sudoku

Not gonna write full code, but I did a sudoku solver a long time ago. I found that it didn't always solve it (the thing people do when they have a newspaper is incomplete!), but now think I know how to do it.

  • Setup: for each square, have a set of flags for each number showing the allowed numbers.
  • Crossing out: just like when people on the train are solving it on paper, you can iteratively cross out known numbers. Any square left with just one number will trigger another crossing out. This will either result in solving the whole puzzle, or it will run out of triggers. This is where I stalled last time.
  • Permutations: there's only 9! = 362880 ways to arrange 9 numbers, easily precomputed on a modern system. All of the rows, columns, and 3x3 squares must be one of these permutations. Once you have a bunch of numbers in there, you can do what you did with the crossing out. For each row/column/3x3, you can cross out 1/9 of the 9! permutations if you have one number, 1/(8*9) if you have 2, and so forth.
  • Cross permutations: Now you have a bunch of rows and columns with sets of potential permutations. But there's another constraint: once you set a row, the columns and 3x3s are vastly reduced in what they might be. You can do a tree search from here to find a solution.

How do I execute multiple SQL Statements in Access' Query Editor?

create a macro like this

Option Compare Database

Sub a()

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

End Sub

How can I check if character in a string is a letter? (Python)

I found a good way to do this with using a function and basic code. This is a code that accepts a string and counts the number of capital letters, lowercase letters and also 'other'. Other is classed as a space, punctuation mark or even Japanese and Chinese characters.

def check(count):

    lowercase = 0
    uppercase = 0
    other = 0

    low = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
    upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'



    for n in count:
        if n in low:
            lowercase += 1
        elif n in upper:
            uppercase += 1
        else:
            other += 1

    print("There are " + str(lowercase) + " lowercase letters.")
    print("There are " + str(uppercase) + " uppercase letters.")
    print("There are " + str(other) + " other elements to this sentence.")

height: calc(100%) not working correctly in CSS

try setting both html and body to height 100%;

html, body {background: blue; height:100%;}

How Exactly Does @param Work - Java

@param won't affect the number. It's just for making javadocs.

More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

Creating a UICollectionView programmatically

Apple Docs:

- (id)initWithFrame:(CGRect)frame 
      collectionViewLayout:(UICollectionViewLayout *)layoutParameters

Use this method when initializing a collection view object programmatically. If you specify nil for the layout parameter, you must assign a layout object to the collectionViewLayout property before displaying the collection view onscreen. If you do not, the collection view will be unable to present any items onscreen.

This method is the designated initializer.

This method is used to initialize the UICollectionView. here you provide frame and a UICollectionViewLayout object.

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

At the end, add UICollectionView as a subview to your view.

Now collection view is added pro grammatically. You can go on learning.
Happy learning!! Hope it helps you.

make div's height expand with its content

This problem arises when the Child elements of a Parent Div are floated. Here is the Latest Solution of the problem:

In your CSS file write the following class called .clearfix along with the pseudo selector :after

.clearfix:after {
    content: "";
    display: table;
    clear: both;
}

Then, in your HTML, add the .clearfix class to your parent Div. For example:

<div class="clearfix">
    <div></div>
    <div></div>
</div>

It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "". Also, overflow: auto; might solve the problem but it causes other problems like showing the scroll-bar and is not recommended.

Source: Blog of Lisa Catalano and Chris Coyier

How do I center an anchor element in CSS?

I think you can't do that with inline elements like anchor, span. But to make it work you have to set the display to block.

<a href="http://www.example.com" style="text-align:center;display:block;">example</a>

Cycles in family tree software

I hate commenting on such a screwed up situation, but the easiest way to not rejigger all of your invariants is to create a phantom vertex in your graph that acts as a proxy back to the incestuous dad.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Let me add an example here:

I'm trying to build Alluxio on windows platform and got the same issue, it's because the pom.xml contains below step:

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <inherited>false</inherited>
        <executions>
          <execution>
            <id>Check that there are no Windows line endings</id>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
            </configuration>
          </execution>
        </executions>
      </plugin>

The .sh file is not executable on windows so the error throws.

Comment it out if you do want build Alluxio on windows.

Handling JSON Post Request in Go

There are two reasons why json.Decoder should be preferred over json.Unmarshal - that are not addressed in the most popular answer from 2013:

  1. February 2018, go 1.10 introduced a new method json.Decoder.DisallowUnknownFields() which addresses the concern of detecting unwanted JSON-input
  2. req.Body is already an io.Reader. Reading its entire contents and then performing json.Unmarshal wastes resources if the stream was, say a 10MB block of invalid JSON. Parsing the request body, with json.Decoder, as it streams in would trigger an early parse error if invalid JSON was encountered. Processing I/O streams in realtime is the preferred go-way.

Addressing some of the user comments about detecting bad user input:

To enforce mandatory fields, and other sanitation checks, try:

d := json.NewDecoder(req.Body)
d.DisallowUnknownFields() // catch unwanted fields

// anonymous struct type: handy for one-time use
t := struct {
    Test *string `json:"test"` // pointer so we can test for field absence
}{}

err := d.Decode(&t)
if err != nil {
    // bad JSON or unrecognized json field
    http.Error(rw, err.Error(), http.StatusBadRequest)
    return
}

if t.Test == nil {
    http.Error(rw, "missing field 'test' from JSON object", http.StatusBadRequest)
    return
}

// optional extra check
if d.More() {
    http.Error(rw, "extraneous data after JSON object", http.StatusBadRequest)
    return
}

// got the input we expected: no more, no less
log.Println(*t.Test)

Playground

Typical output:

$ curl -X POST -d "{}" http://localhost:8082/strict_test

expected json field 'test'

$ curl -X POST -d "{\"Test\":\"maybe?\",\"Unwanted\":\"1\"}" http://localhost:8082/strict_test

json: unknown field "Unwanted"

$ curl -X POST -d "{\"Test\":\"oops\"}g4rB4g3@#$%^&*" http://localhost:8082/strict_test

extraneous data after JSON

$ curl -X POST -d "{\"Test\":\"Works\"}" http://localhost:8082/strict_test 

log: 2019/03/07 16:03:13 Works

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

Overlaying histograms with ggplot2 in R

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

docs.ggplot2.org/current/geom_histogram.html

Download and install an ipa from self hosted url on iOS

To distribute your app over-the-air (OTA, this means without using TestFlight or the official App Store), you may need to create 3 different files, namely:

  • The .ipa file (using an ad-hoc provisioning profile)
  • index.html
  • manifest.plist

You can use Beta Builder to generate these files:

  1. Archive your build.
  2. Save the .ipa on the Desktop.
  3. Download a small utility Beta Builder from here. This does most of the required task.
  4. Open the tool and select your .ipa file, then provide the path you will be placing the build on https://myWeb.com/MY_TEST_APP in the beta builder.
  5. Generate all the files.
  6. Now upload index.html, your_App.ipa, & manifest.plist to your server path https://myWeb.com/MY_TEST_APP
  7. Now share the link of index.html. Once you open this file, you will be asked to Tap on install.
  8. It will install your_App.ipa on your device.

You can also do this more manually.

index.html

<a href="itms-services://?action=download-manifest&url=https://myWeb.com/MY_TEST_APP/manifest.plist">Install App</a>

manifest.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>http://YOUR_SERVER_URL/YOUR-IPA-FILE.ipa</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>com.yourCompany.productName</string>
                <key>bundle-version</key>
                <string>1.0.0</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>YOUR APP NAME</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>

If the app refuses to install or run, you may need to check the following items:

  • The provisioning profile you've used when compiling/archiving your app
  • The URLs in both index.html and manifest.plist
  • The plist file may possibly need to be hosted on an HTTPS server. You can use Dropbox for this if necessary.
  • Your device UUIDs may need to be registered inside Apple Developer Center unless you have an Enterprise licence
  • You may need to manually enable access to the app within Settings > Profiles

When is the finalize() method called in Java?

An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection. Generally an object becomes eligible for garbage collection in Java on following cases:

  1. All references of that object explicitly set to null e.g. object = null
  2. Object is created inside a block and reference goes out scope once control exit that block.
  3. Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
  4. If an object has only live references via WeakHashMap it will be eligible for garbage collection.

How to set a default value in react-select

I guess you need something like this:

const MySelect = props => (
<Select
    {...props}
    value={props.options.filter(option => option.label === 'Some label')}
    onChange={value => props.input.onChange(value)}
    onBlur={() => props.input.onBlur(props.input.value)}
    options={props.options}
    placeholder={props.placeholder}
  />
);

Oracle PL/SQL string compare issue

Let's fill in the gaps in your code, by adding the other branches in the logic, and see what happens:

SQL> DECLARE
  2   str1  varchar2(4000);
  3   str2  varchar2(4000);
  4  BEGIN
  5     str1:='';
  6     str2:='sdd';
  7     IF(str1<>str2) THEN
  8      dbms_output.put_line('The two strings is not equal');
  9     ELSIF (str1=str2) THEN
 10      dbms_output.put_line('The two strings are the same');
 11     ELSE
 12      dbms_output.put_line('Who knows?');
 13     END IF;
 14   END;
 15  /
Who knows?

PL/SQL procedure successfully completed.

SQL>

So the two strings are neither the same nor are they not the same? Huh?

It comes down to this. Oracle treats an empty string as a NULL. If we attempt to compare a NULL and another string the outcome is not TRUE nor FALSE, it is NULL. This remains the case even if the other string is also a NULL.

How can I determine whether a specific file is open in Windows?

Try Handle. Filemon & Regmon are also great for trying to figure out what the duce program foo is doing to your system.

How can I concatenate strings in VBA?

The main (very interesting) difference for me is that:
"string" & Null -> "string"
while
"string" + Null -> Null

But that's probably more useful in database apps like Access.

Java: splitting a comma-separated string but ignoring commas in quotes

what about a one-liner using String.split()?

String s = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
String[] split = s.split( "(?<!\".{0,255}[^\"]),|,(?![^\"].*\")" );

How to handle Pop-up in Selenium WebDriver using Java

You can handle popup window or alert box:

Alert alert = driver.switchTo().alert();
alert.accept();

You can also decline the alert box:

Alert alert = driver.switchTo().alert();
alert().dismiss();

What is the difference between <html lang="en"> and <html lang="en-US">?

XML Schema requires that the xml namespace be declared and imported before using xml:lang (and other xml namespace values) RELAX NG predeclares the xml namespace, as in XML, so no additional declaration is needed.

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

Simple answer

If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080

If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Could not create work tree dir 'example.com'.: Permission denied

I was facing same issue then I read first few lines of this question and I realised that I was trying to run command at the root directory of my bash profile instead of CD/my work project folder. I switched back to my work folder and able to clone the project successfully

SQL Server 2008: How to query all databases sizes?

sometimes SECURITY issues prevent from asking for all the db's and you need to query one by one with the db prefix, for those cases i created this dynamic query

go
declare @Results table ([Name] nvarchar(max), [DataFileSizeMB] int, [LogFileSizeMB] int);

declare @QaQuery nvarchar(max)
declare @name nvarchar(max)

declare MY_CURSOR cursor 
  local static read_only forward_only
for 
select name from master.dbo.sysdatabases where name not in ('master', 'tempdb', 'model', 'msdb', 'rdsadmin');

open MY_CURSOR
fetch next from MY_CURSOR into @name
while @@FETCH_STATUS = 0
begin 
    if(len(@name)>0)
    begin
        print @name + ' Column Exist'
        set @QaQuery = N'select 
                            '''+@name+''' as Name
                            ,sum(case when type = 0 then size else 0 end) as DataFileSizeMB
                            ,sum(case when type = 1 then size else 0 end) as LogFileSizeMB
                        from ['+@name+'].sys.database_files
                        group by replace(name, ''_log'', '''')';

        insert @Results exec sp_executesql @QaQuery;
    end
  fetch next from MY_CURSOR into @name
end
close MY_CURSOR
deallocate MY_CURSOR

select * from @Results order by DataFileSizeMB desc
go

FontAwesome icons not showing. Why?

For version 5:

If you downloaded the free package from this site:

https://fontawesome.com/download

The fonts are in the all.css and all.min.css file.

So your reference will look something like this:

<link href="/MyProject/Content/fontawesome-free-5.10.1-web/css/all.min.css" rel="stylesheet">

The fontawesome.css file does not include the font reference.

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

If this is a SQL question, and I understand what you are asking, (it's not entirely clear), just add distinct to the query

   Select Distinct * From TempTable

Python locale error: unsupported locale setting

python looks for .UFT-8, but you probably have .utf8 try installing the .UFT-8 packages with sudo dpkg-reconfigure locales

Remove object from a list of objects in python

If you know the array location you can can pass it into itself. If you are removing multiple items I suggest you remove them in reverse order.

#Setup array
array = [55,126,555,2,36]
#Remove 55 which is in position 0
array.remove(array[0])

How do I get the current location of an iframe?

I like your server side idea, even if my proposed implementation of it sounds a little bit ghetto.

You could set the .innerHTML of the iframe to the HTML contents you grab server side. Depending on how you grab this, you will have to pay attention to relative versus absolute paths.

Plus, depending on how the page you are grabbing interacts with other pages, this could totally not work (cookies being set for the page you are grabbing won't work across domains, maybe state is being tracked in Javascript... Lots of reasons this might not work.)

I don't believe that tracking the current state of the page you are trying to mirror is theoretically possible, but I'm not sure. The site could track all sorts of things server side, you won't have access to this state. Imagine the case where on a page load a variable is set to a random value server-side, how would you capture this state?

Do these ideas help with anything?

-Brian J. Stinar-

Generate list of all possible permutations of a string

Though this doesn't answer your question exactly, here's one way to generate every permutation of the letters from a number of strings of the same length: eg, if your words were "coffee", "joomla" and "moodle", you can expect output like "coodle", "joodee", "joffle", etc.

Basically, the number of combinations is the (number of words) to the power of (number of letters per word). So, choose a random number between 0 and the number of combinations - 1, convert that number to base (number of words), then use each digit of that number as the indicator for which word to take the next letter from.

eg: in the above example. 3 words, 6 letters = 729 combinations. Choose a random number: 465. Convert to base 3: 122020. Take the first letter from word 1, 2nd from word 2, 3rd from word 2, 4th from word 0... and you get... "joofle".

If you wanted all the permutations, just loop from 0 to 728. Of course, if you're just choosing one random value, a much simpler less-confusing way would be to loop over the letters. This method lets you avoid recursion, should you want all the permutations, plus it makes you look like you know Maths(tm)!

If the number of combinations is excessive, you can break it up into a series of smaller words and concatenate them at the end.

How to append text to a text file in C++?

You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.

...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...

You can find more information about the open modes here and about fstreams here.

What is the question mark for in a Typescript parameter name

This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.

export interface ISearchResult {  
  title: string;  
  listTitle:string;
  entityName?: string,
  lookupName?:string,
  lookupId?:string  
}

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

This latest announcement list snippet might be of interest if you'll be upgrading to 8.4:

Until 8.4 comes out with a super-effient native one, you can add the array_accum() function in the PostgreSQL documentation for rolling up any column into an array, which can then be used by application code, or combined with array_to_string() to format it as a list:

http://www.postgresql.org/docs/current/static/xaggr.html

I'd link to the 8.4 development docs but they don't seem to list this feature yet.

I can't install python-ldap

sudo apt-get install build-essential python3-dev python2.7-dev libldap2-dev libsasl2-dev slapd ldap-utils python-tox lcov valgrind

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

Fake "click" to activate an onclick method

just call "onclick"!

here's an example html:

<div id="c" onclick="alert('hello')">Click me!</div>
<div onclick="document.getElementById('c').onclick()">Fake click the previous link!</div>

Can I embed a .png image into an html page?

There are a few base64 encoders online to help you with this, this is probably the best I've seen:

http://www.greywyvern.com/code/php/binary2base64

As that page shows your main options for this are CSS:

div.image {
  width:100px;
  height:100px;
  background-image:url(data:image/png;base64,iVBORwA<MoreBase64SringHere>); 
}

Or the <img> tag itself, like this:

<img alt="My Image" src="data:image/png;base64,iVBORwA<MoreBase64SringHere>" />

iOS start Background Thread

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

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

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

Testing web application on Mac/Safari when I don't own a Mac

Unfortunately you cannot run MacOS X on anything but a genuine Mac.

MacOS X Server however can be run in VMWare. A stopgap solution would be to install it inside a VM. But you should be aware that MacOS X Server and MacOS X are not exactly the same, and your testing is not going to be exactly what the user has. Not to mention the $499 price tag.

Simplest way is to buy yourself a cheap mac mini or a laptop with a broken screen used on ebay, plug it onto your network and access it via VNC to do your testing.

If you can decode JWT, how are they secure?

Let's discuss from the very beginning:

JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs. Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.

So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.

The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage. enter image description here

Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.

So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.

So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.

Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.

Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource. enter image description here

All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.

enter image description here

So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

How can I make a SQL temp table with primary key and auto-incrementing field?

You are just missing the words "primary key" as far as I can see to meet your specified objective.

For your other columns it's best to explicitly define whether they should be NULL or NOT NULL though so you are not relying on the ANSI_NULL_DFLT_ON setting.

CREATE TABLE #tmp
(
ID INT IDENTITY(1, 1) primary key ,
AssignedTo NVARCHAR(100),
AltBusinessSeverity NVARCHAR(100),
DefectCount int
);

insert into #tmp 
select 'user','high',5 union all
select 'user','med',4


select * from #tmp

Getting Database connection in pure JPA setup

Since the code suggested by @Pascal is deprecated as mentioned by @Jacob, I found this another way that works for me.

import org.hibernate.classic.Session;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.engine.SessionFactoryImplementor;

Session session = (Session) em.getDelegate();
SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider cp = sfi.getConnectionProvider();
Connection connection = cp.getConnection();

How do you create a REST client for Java?

Try looking at http-rest-client

https://github.com/g00dnatur3/http-rest-client

Here is a simple example:

RestClient client = RestClient.builder().build();
String geocoderUrl = "http://maps.googleapis.com/maps/api/geocode/json"
Map<String, String> params = Maps.newHashMap();
params.put("address", "beverly hills 90210");
params.put("sensor", "false");
JsonNode node = client.get(geocoderUrl, params, JsonNode.class);

The library takes care of json serialization and binding for you.

Here is another example,

RestClient client = RestClient.builder().build();
String url = ...
Person person = ...
Header header = client.create(url, person);
if (header != null) System.out.println("Location header is:" + header.value());

And one last example,

RestClient client = RestClient.builder().build();
String url = ...
Person person = client.get(url, null, Person.class); //no queryParams

Cheers!

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

JAX-WS and BASIC authentication, when user names and passwords are in a database

In your client SOAP handler you need to set javax.xml.ws.security.auth.username and javax.xml.ws.security.auth.password property as follow:

public class ClientHandler implements SOAPHandler<SOAPMessageContext>{

    public boolean handleMessage(final SOAPMessageContext soapMessageContext)
    {
        final Boolean outInd = (Boolean)soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outInd.booleanValue())
        {
          try 
          {
               soapMessageContext.put("javax.xml.ws.security.auth.username", <ClientUserName>);
               soapMessageContext.put("javax.xml.ws.security.auth.password", <ClientPassword>);
          } 
          catch (Exception e)
          {
               e.printStackTrace();
               return false;
          }
         }
      return true;
     }
}