Programs & Examples On #Clutter

An open source software library for creating dynamic graphical user interfaces.

Angular2: Cannot read property 'name' of undefined

The variable selectedHero is null in the template so you cannot bind selectedHero.name as is. You need to use the elvis operator ?. for this case:

<input [ngModel]="selectedHero?.name" (ngModelChange)="selectedHero.name = $event" />

The separation of the [(ngModel)] into [ngModel] and (ngModelChange) is also needed because you can't assign to an expression that uses the elvis operator.

I also think you mean to use:

<h2>{{selectedHero?.name}} details!</h2>

instead of:

<h2>{{hero.name}} details!</h2>

Proper usage of Optional.ifPresent()

Why write complicated code when you could make it simple?

Indeed, if you are absolutely going to use the Optional class, the most simple code is what you have already written ...

if (user.isPresent())
{
    doSomethingWithUser(user.get());
}

This code has the advantages of being

  1. readable
  2. easy to debug (breakpoint)
  3. not tricky

Just because Oracle has added the Optional class in Java 8 doesn't mean that this class must be used in all situation.

Scroll / Jump to id without jQuery

Oxi's answer is just wrong.¹

What you want is:

var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;

Working example:

(function (){
  var i = 20, l = 20, html = '';
  while (i--){
    html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
    html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
    html += '[ Scroll to #DIV' +i+ ' ]</a>';
    html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
  }
  document.write( html );
})();

¹ I haven't got enough reputation to comment on his answer

How to hide output of subprocess in Python 2.7

Why not use commands.getoutput() instead?

import commands

text = "Mario Balotelli" 
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)

Xcode Simulator: how to remove older unneeded devices?

On Mac, check /Library/Developer/Xcode/iOS\ DeviceSupport

iOS DeviceSupport

What is an example of the simplest possible Socket.io example?

Maybe this may help you as well. I was having some trouble getting my head wrapped around how socket.io worked, so I tried to boil an example down as much as I could.

I adapted this example from the example posted here: http://socket.io/get-started/chat/

First, start in an empty directory, and create a very simple file called package.json Place the following in it.

{
"dependencies": {}
}

Next, on the command line, use npm to install the dependencies we need for this example

$ npm install --save express socket.io

This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}

Create a file called server.js This will obviously be our server run by node. Place the following code into it:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

http.listen(3001, function(){

  console.log('listening on *:3001');

});

//for testing, we're just going to send data to the client every second
setInterval( function() {

  /*
    our message we want to send to the client: in this case it's just a random
    number that we generate on the server
  */
  var msg = Math.random();
  io.emit('message', msg);
  console.log (msg);

}, 1000);

Create the last file called index.html and place the following code into it.

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

You can now test this very simple example and see some output similar to the following:

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653

If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.

Why are static variables considered evil?

Its not very object oriented: One reason statics might be considered "evil" by some people is they are contrary the object-oriented paradigm. In particular, it violates the principle that data is encapsulated in objects (that can be extended, information hiding, etc). Statics, in the way you are describing using them, are essentially to use them as a global variable to avoid dealing with issues like scope. However, global variables is one of the defining characteristics of procedural or imperative programming paradigm, not a characteristic of "good" object oriented code. This is not to say the procedural paradigm is bad, but I get the impression your supervisor expects you to be writing "good object oriented code" and you're really wanting to write "good procedural code".

There are many gotchyas in Java when you start using statics that are not always immediately obvious. For example, if you have two copies of your program running in the same VM, will they shre the static variable's value and mess with the state of each other? Or what happens when you extend the class, can you override the static member? Is your VM running out of memory because you have insane numbers of statics and that memory cannot be reclaimed for other needed instance objects?

Object Lifetime: Additionally, statics have a lifetime that matches the entire runtime of the program. This means, even once you're done using your class, the memory from all those static variables cannot be garbage collected. If, for example, instead, you made your variables non-static, and in your main() function you made a single instance of your class, and then asked your class to execute a particular function 10,000 times, once those 10,000 calls were done, and you delete your references to the single instance, all your static variables could be garbage collected and reused.

Prevents certain re-use: Also, static methods cannot be used to implement an interface, so static methods can prevent certain object oriented features from being usable.

Other Options: If efficiency is your primary concern, there might be other better ways to solve the speed problem than considering only the advantage of invocation being usually faster than creation. Consider whether the transient or volatile modifiers are needed anywhere. To preserve the ability to be inlined, a method could be marked as final instead of static. Method parameters and other variables can be marked final to permit certain compiler optimiazations based on assumptions about what can change those variables. An instance object could be reused multiple times rather than creating a new instance each time. There may be compliler optimization switches that should be turned on for the app in general. Perhaps, the design should be set up so that the 10,000 runs can be multi-threaded and take advantage of multi-processor cores. If portablity isn't a concern, maybe a native method would get you better speed than your statics do.

If for some reason you do not want multiple copies of an object, the singleton design pattern, has advantages over static objects, such as thread-safety (presuming your singleton is coded well), permitting lazy-initialization, guaranteeing the object has been properly initialized when it is used, sub-classing, advantages in testing and refactoring your code, not to mention, if at some point you change your mind about only wanting one instance of an object it is MUCH easier to remove the code to prevent duplicate instances than it is to refactor all your static variable code to use instance variables. I've had to do that before, its not fun, and you end up having to edit a lot more classes, which increases your risk of introducing new bugs...so much better to set things up "right" the first time, even if it seems like it has its disadvantages. For me, the re-work required should you decide down the road you need multiple copies of something is probably one of most compelling reasons to use statics as infrequently as possible. And thus I would also disagree with your statement that statics reduce inter-dependencies, I think you will end up with code that is more coupled if you have lots of statics that can be directly accessed, rather than an object that "knows how to do something" on itself.

Creating a singleton in Python

Use a module. It is imported only once. Define some global variables in it - they will be singleton's 'attributes'. Add some functions - the singleton's 'methods'.

Using a SELECT statement within a WHERE clause

It's called correlated subquery. It has it's uses.

How to check if IEnumerable is null or empty?

Jon Skeet's anwser (https://stackoverflow.com/a/28904021/8207463) has a good approach using Extension Method - Any() for NULL and EMPTY. BUT he´s validating the questions´owner in case for NOT NULL. So carefully change Jon´s approach to validate AS NULL to:

If (yourList?.Any() != true) 
{
     ..your code...
}

DO NOT use ( will not validate AS NULL):

If (yourList?.Any() == false) 
{
     ..your code...
}

You can also in case validating AS NOT NULL ( NOT tested just as example but without compiler error) do something like using predicate :

If (yourList?.Any(p => p.anyItem == null) == true) 
{
     ..your code...
}

https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8788153112b7ffd0

For which .NET version you can use it please check:

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netframework-4.8#moniker-applies-to

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

How can I make robocopy silent in the command line except for progress?

robocopy also tends to print empty lines even if it does not do anything. I'm filtering empty lines away using command like this:

robocopy /NDL /NJH /NJS /NP /NS /NC %fromDir% %toDir% %filenames% | findstr /r /v "^$"

How to Store Historical Data

You can use MSSQL Server Auditing feature. From version SQL Server 2012 you will find this feature in all editions:

http://technet.microsoft.com/en-us/library/cc280386.aspx

Setting width/height as percentage minus pixels

  1. Use negative margins on the element you would like to minus pixels off. (desired element)
  2. Make overflow:hidden; on the containing element
  3. Switch to overflow:auto; on the desired element.

It worked for me!

Do you (really) write exception safe code?

Some of us prefer languages like Java which force us to declare all the exceptions thrown by methods, instead of making them invisible as in C++ and C#.

When done properly, exceptions are superior to error return codes, if for no other reason than you don't have to propagate failures up the call chain manually.

That being said, low-level API library programming should probably avoid exception handling, and stick to error return codes.

It's been my experience that it's difficult to write clean exception handling code in C++. I end up using new(nothrow) a lot.

Logging in Scala

I find very convenient using some kind of java logger, sl4j for example, with simple scala wrapper, which brings me such syntax

val #! = new Logger(..) // somewhere deep in dsl.logging.

object User with dsl.logging {

  #! ! "info message"
  #! dbg "debug message"
  #! trace "var a=true"

}

In my opinion very usefull mixin of java proven logging frameworks and scala's fancy syntax.

Efficiency of Java "Double Brace Initialization"?

I second Nat's answer, except I would use a loop instead of creating and immediately tossing the implicit List from asList(elements):

static public Set<T> setOf(T ... elements) {
    Set set=new HashSet<T>(elements.size());
    for(T elm: elements) { set.add(elm); }
    return set;
    }

How do you stash an untracked file?

There are several correct answers here, but I wanted to point out that for new entire directories, 'git add path' will NOT work. So if you have a bunch of new files in untracked-path and do this:

git add untracked-path
git stash "temp stash"

this will stash with the following message:

Saved working directory and index state On master: temp stash
warning: unable to rmdir untracked-path: Directory not empty

and if untracked-path is the only path you're stashing, the stash "temp stash" will be an empty stash. Correct way is to add the entire path, not just the directory name (i.e. end the path with a '/'):

git add untracked-path/
git stash "temp stash"

How to clear the interpreter console?

I use iTerm and the native terminal app for Mac OS.

I just press ? + k

How to delete an SMS from the inbox in Android programmatically?

public boolean deleteSms(String smsId) {
    boolean isSmsDeleted = false;
    try {
        mActivity.getContentResolver().delete(Uri.parse("content://sms/" + smsId), null, null);
        isSmsDeleted = true;

    } catch (Exception ex) {
        isSmsDeleted = false;
    }
    return isSmsDeleted;
}

use this permission in AndroidManifiest

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

How to compare objects by multiple fields

Starting from Steve's answer the ternary operator can be used:

public int compareTo(Person other) {
    int f = firstName.compareTo(other.firstName);
    int l = lastName.compareTo(other.lastName);
    return f != 0 ? f : l != 0 ? l : Integer.compare(age, other.age);
}

Why would one mark local variables and method parameters as "final" in Java?

Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.

The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.

Edit

In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.

How do I make an HTML text box show a hint when empty?

Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's placeholder attribute:

<input name="email" placeholder="Email Address">

In the absence of any styles, in Chrome this looks like:

enter image description here

You can try demos out here and in HTML5 Placeholder Styling with CSS.

Be sure to check the browser compatibility of this feature. Support in Firefox was added in 3.7. Chrome is fine. Internet Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called jQuery HTML5 Placeholder, and then just add the following JavaScript code to enable it.

$('input[placeholder], textarea[placeholder]').placeholder();

How do I update the password for Git?

For those who are looking for how to reset access to the repository. By the example of GitHub. You can change your GitHub profile password and revoke all "Personal access tokens" in "Settings -> Developer settings" of your profile. Also you can optionally wipe all your SSH/PGP keys and OAuth/GitHub apps to be sure that access to the repository is completely blocked. Thus, all the credential managers, on any system will fail at authorisation and prompt you to enter the new credentials.

Integrity constraint violation: 1452 Cannot add or update a child row:

I had this issue when I was accidentally using the WRONG "uuid" in my child record. When that happens the constraint looks from the child to the parent record to ensure that the link is correct. I was generating it manually, when I had already rigged my Model to do it automatically. So my fix was:

$parent = Parent:create($recData); // asssigning autogenerated uuid into $parent

Then when I called my child class to insert children, I passed this var value:

$parent->uuid

Hope that helps.

Detecting an undefined object property

if (somevariable == undefined) {
  alert('the variable is not defined!');
}

You can also make it into a function, as shown here:

function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}

Grant execute permission for a user on all stored procedures in database?

This is a solution that means that as you add new stored procedures to the schema, users can execute them without having to call grant execute on the new stored procedure:

IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'asp_net')
DROP USER asp_net
GO

IF  EXISTS (SELECT * FROM sys.database_principals 
WHERE name = N'db_execproc' AND type = 'R')
DROP ROLE [db_execproc]
GO

--Create a database role....
CREATE ROLE [db_execproc] AUTHORIZATION [dbo]
GO

--...with EXECUTE permission at the schema level...
GRANT EXECUTE ON SCHEMA::dbo TO db_execproc;
GO

--http://www.patrickkeisler.com/2012/10/grant-execute-permission-on-all-stored.html
--Any stored procedures that are created in the dbo schema can be 
--executed by users who are members of the db_execproc database role

--...add a user e.g. for the NETWORK SERVICE login that asp.net uses
CREATE USER asp_net 
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE] 
WITH DEFAULT_SCHEMA=[dbo]
GO

--...and add them to the roles you need
EXEC sp_addrolemember N'db_execproc', 'asp_net';
EXEC sp_addrolemember N'db_datareader', 'asp_net';
EXEC sp_addrolemember N'db_datawriter', 'asp_net';
GO

Reference: Grant Execute Permission on All Stored Procedures

How do you render primitives as wireframes in OpenGL?

In Modern OpenGL(OpenGL 3.2 and higher), you could use a Geometry Shader for this :

#version 330

layout (triangles) in;
layout (line_strip /*for lines, use "points" for points*/, max_vertices=3) out;

in vec2 texcoords_pass[]; //Texcoords from Vertex Shader
in vec3 normals_pass[]; //Normals from Vertex Shader

out vec3 normals; //Normals for Fragment Shader
out vec2 texcoords; //Texcoords for Fragment Shader

void main(void)
{
    int i;
    for (i = 0; i < gl_in.length(); i++)
    {
        texcoords=texcoords_pass[i]; //Pass through
        normals=normals_pass[i]; //Pass through
        gl_Position = gl_in[i].gl_Position; //Pass through
        EmitVertex();
    }
    EndPrimitive();
}

Notices :

JAX-WS client : what's the correct path to access the local WSDL?

For those who are still coming for solution here, the easiest solution would be to use <wsdlLocation>, without changing any code. Working steps are given below:

  1. Put your wsdl to resource directory like : src/main/resource
  2. In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.

    <wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
    <wsdlLocation>/mydir/my.wsdl</wsdlLocation>
    
  3. Then in your java code(with no-arg constructor):

    MyPort myPort = new MyPortService().getMyPort();
    
  4. For completeness, I am providing here full code generation part, with fluent api in generated code.

    <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.5</version>
    
    <dependencies>
        <dependency>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-fluent-api</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-tools</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
    
    <executions>
        <execution>
            <id>wsdl-to-java-generator</id>
            <goals>
                <goal>wsimport</goal>
            </goals>
            <configuration>
                <xjcArgs>
                    <xjcArg>-Xfluent-api</xjcArg>
                </xjcArgs>
                <keep>true</keep>
                <wsdlDirectory>src/main/resources/package</wsdlDirectory>
                <wsdlLocation>/package/my.wsdl</wsdlLocation>
                <sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
                <packageName>full.package.here</packageName>
            </configuration>
        </execution>
    </executions>
    

Java way to check if a string is palindrome

public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
    if (word[i1] != word[i2]) {
        return false;
    }
    ++i1;
    --i2;
}
return true;
}

How to check if pytorch is using the GPU?

Create a tensor on the GPU as follows:

$ python
>>> import torch
>>> print(torch.rand(3,3).cuda()) 

Do not quit, open another terminal and check if the python process is using the GPU using:

$ nvidia-smi

how to load CSS file into jsp

I use this version

<style><%@include file="/WEB-INF/css/style.css"%></style>

How to select label for="XYZ" in CSS?

If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:

itemSelected(id: number){
    console.log('label contains', document.querySelector("label[for='" + id + "']"));
}

How to increase icons size on Android Home Screen?

Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.

Well, "no way" does not mean its impossible:

  • As said, you can write your own launcher as discussed in Stackoverflow.
  • You can resize elements on the home screen, but these elements are AppWidgets. Since API level 14 they can be resized and user can - in limits - change the size. But that are Widgets not Shortcuts for launching icons.

python: how to identify if a variable is an array or a scalar

Previous answers assume that the array is a python standard list. As someone who uses numpy often, I'd recommend a very pythonic test of:

if hasattr(N, "__len__")

Preventing form resubmission

The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.

check if "it's a number" function in Oracle

This is a potential duplicate of Finding rows that don't contain numeric data in Oracle. Also see: How can I determine if a string is numeric in SQL?.

Here's a solution based on Michael Durrant's that works for integers.

SELECT foo
FROM bar
WHERE DECODE(TRIM(TRANSLATE(your_number,'0123456789',' ')), NULL, 'number','contains char') = 'number'

Adrian Carneiro posted a solution that works for decimals and others. However, as Justin Cave pointed out, this will incorrectly classify strings like '123.45.23.234' or '131+234'.

SELECT foo
FROM bar
WHERE DECODE(TRIM(TRANSLATE(your_number,'+-.0123456789',' ')), NULL, 'number','contains char') = 'number'

If you need a solution without PL/SQL or REGEXP_LIKE, this may help.

How to change the server port from 3000?

You can change it inside bs-config.json file as mentioned in the docs https://github.com/johnpapa/lite-server#custom-configuration

For example,

{
  "port": 8000,
  "files": ["./src/**/*.{html,htm,css,js}"],
  "server": { "baseDir": "./src" }
}

How can I put strings in an array, split by new line?

<anti-answer>

As other answers have specified, be sure to use explode rather than split because as of PHP 5.3.0 split is deprecated. i.e. the following is NOT the way you want to do it:

$your_array = split(chr(10), $your_string);

LF = "\n" = chr(10), CR = "\r" = chr(13)

</anti-answer>

Connecting an input stream to an outputstream

In case you are into functional this is a function written in Scala showing how you could copy an input stream to an output stream using only vals (and not vars).

def copyInputToOutputFunctional(inputStream: InputStream, outputStream: OutputStream,bufferSize: Int) {
  val buffer = new Array[Byte](bufferSize);
  def recurse() {
    val len = inputStream.read(buffer);
    if (len > 0) {
      outputStream.write(buffer.take(len));
      recurse();
    }
  }
  recurse();
}

Note that this is not recommended to use in a java application with little memory available because with a recursive function you could easily get a stack overflow exception error

Angular - How to apply [ngStyle] conditions

<ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>

How to get all options in a drop-down list by Selenium WebDriver using C#?

Make sure you reference the WebDriver.Support.dll assembly to gain access to the OpenQA.Selenium.Support.UI.SelectElement dropdown helper class. See this thread for additional details.

Edit: In this screenshot, you can see that I can get the options just fine. Is IE opening up when you create a new InternetExplorerDriver? Screenshot

When to use RSpec let()?

I use let to test my HTTP 404 responses in my API specs using contexts.

To create the resource, I use let!. But to store the resource identifier, I use let. Take a look how it looks like:

let!(:country)   { create(:country) }
let(:country_id) { country.id }
before           { get "api/countries/#{country_id}" }

it 'responds with HTTP 200' { should respond_with(200) }

context 'when the country does not exist' do
  let(:country_id) { -1 }
  it 'responds with HTTP 404' { should respond_with(404) }
end

That keeps the specs clean and readable.

Detecting value change of input[type=text] in jQuery

This combination of events worked for me:

$("#myTextBox").on("input paste", function() {
   alert($(this).val()); 
});

How do I compute derivative using Numpy?

I'll throw another method on the pile...

scipy.interpolate's many interpolating splines are capable of providing derivatives. So, using a linear spline (k=1), the derivative of the spline (using the derivative() method) should be equivalent to a forward difference. I'm not entirely sure, but I believe using a cubic spline derivative would be similar to a centered difference derivative since it uses values from before and after to construct the cubic spline.

from scipy.interpolate import InterpolatedUnivariateSpline

# Get a function that evaluates the linear spline at any x
f = InterpolatedUnivariateSpline(x, y, k=1)

# Get a function that evaluates the derivative of the linear spline at any x
dfdx = f.derivative()

# Evaluate the derivative dydx at each x location...
dydx = dfdx(x)

If using maven, usually you put log4j.properties under java or resources?

If your log4j.properties or log4j.xml file not found under src/main/resources use this PropertyConfigurator.configure("log4j.xml");

   PropertyConfigurator.configure("log4j.xml");
   Logger logger = LoggerFactory.getLogger(MyClass.class);
   logger.error(message);

How to add url parameters to Django template url tag?

First you need to prepare your url to accept the param in the regex: (urls.py)

url(r'^panel/person/(?P<person_id>[0-9]+)$', 'apps.panel.views.person_form', name='panel_person_form'),

So you use this in your template:

{% url 'panel_person_form' person_id=item.id %}

If you have more than one param, you can change your regex and modify the template using the following:

{% url 'panel_person_form' person_id=item.id group_id=3 %}

The Android emulator is not starting, showing "invalid command-line parameter"

NickC is correct. It is also worth pointing out that the SDK location is set in Eclipse > Window menu > Preferences > Android. If your folders are different you can check the 8.3 format of any folder with dir foldername /x at the command prompt.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

Can't comment on Susam Pal's answer but if you're dealing with spaces, I'd surround with quotes:

for f in *.jpg; do mv "$f" "`echo $f | sed s/\ /\-/g`"; done;

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

Just a suggestion, but you might try the Pear Mail_Mime class instead.

http://pear.php.net/package/Mail_Mime/docs

Otherwise you can use a bit of code. Gabi Purcaru method of using rename() won't work the way it's written. See this post http://us3.php.net/manual/en/function.rename.php#97347 . You'll need something like this:

$dir = dirname($_FILES["file"]["tmp_name"]);
$destination = $dir . DIRECTORY_SEPARATOR . $_FILES["file"]["name"];
rename($_FILES["file"]["tmp_name"], $destination);
$geekMail->attach($destination);

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
  tab3.desc = "XYZ" and
  tab4.ss = tab3.ss

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

The configuration property is called hibernate.hbm2ddl.auto

In our development environment we set hibernate.hbm2ddl.auto=create-drop to drop and create a clean database each time we deploy, so that our database is in a known state.

In theory, you can set hibernate.hbm2ddl.auto=update to update your database with changes to your model, but I would not trust that on a production database. An earlier version of the documentation said that this was experimental, at least; I do not know the current status.

Therefore, for our production database, do not set hibernate.hbm2ddl.auto - the default is to make no database changes. Instead, we manually create an SQL DDL update script that applies changes from one version to the next.

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

How do I convert datetime.timedelta to minutes, hours in Python?

I don't think it's a good idea to caculate yourself.

If you just want a pretty output, just covert it into str with str() function or directly print() it.

And if there's further usage of the hours and minutes, you can parse it to datetime object use datetime.strptime()(and extract the time part with datetime.time() mehtod), for example:

import datetime

delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

Static way to get 'Context' in Android?

According to this source you can obtain your own Context by extending ContextWrapper

public class SomeClass extends ContextWrapper {

    public SomeClass(Context base) {
      super(base);
    }

    public void someMethod() {
        // notice how I can use "this" for Context
        // this works because this class has it's own Context just like an Activity or Service
        startActivity(this, SomeRealActivity.class);

        //would require context too
        File cacheDir = getCacheDir();
    }
}

JavaDoc for ContextWrapper

Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.

Where does Vagrant download its .box files to?

On Windows, the location can be found here. I didn't find any documentation on the internet for this, and this wasn't immediately obvious to me:

C:\Users\\{username}\\.vagrant.d\boxes

Regarding C++ Include another class

you need to forward declare the name of the class if you don't want a header:

class ClassTwo;

Important: This only works in some cases, see Als's answer for more information..

Reverse order of foreach list items

Assuming you just need to reverse an indexed array (not associative or multidimensional) a simple for loop would suffice:

$fruits = ['bananas', 'apples', 'pears'];
for($i = count($fruits)-1; $i >= 0; $i--) {
    echo $fruits[$i] . '<br>';
} 

Java array assignment (multiple values)

You may use a local variable, like:

    float[] values = new float[3];
    float[] v = {0.1f, 0.2f, 0.3f};
    float[] values = v;

Excel to JSON javascript code?

js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.

Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file

<!doctype html>
<html>

<head>
    <title>Excel to JSON Demo</title>
    <script src="xlsx.full.min.js"></script>
</head>

<body>

    <script>
        /* set up XMLHttpRequest */
        var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
        var oReq = new XMLHttpRequest();
        oReq.open("GET", url, true);
        oReq.responseType = "arraybuffer";

        oReq.onload = function(e) {
            var arraybuffer = oReq.response;

            /* convert data to binary string */
            var data = new Uint8Array(arraybuffer);
            var arr = new Array();
            for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
            var bstr = arr.join("");

            /* Call XLSX */
            var workbook = XLSX.read(bstr, {
                type: "binary"
            });

            /* DO SOMETHING WITH workbook HERE */
            var first_sheet_name = workbook.SheetNames[0];
            /* Get worksheet */
            var worksheet = workbook.Sheets[first_sheet_name];
            console.log(XLSX.utils.sheet_to_json(worksheet, {
                raw: true
            }));
        }

        oReq.send();
    </script>
</body>
</html>

Input:
Click here to see the input Excel file

Output:
Click here to see the output of above code

What is the minimum I have to do to create an RPM file?

If make config works for your program or you have a shell script which copies your two files to the appropriate place you can use checkinstall. Just go to the directory where your makefile is in and call it with the parameter -R (for RPM) and optionally with the installation script.

How to initialize log4j properly?

You can set the location of your log4j.properties from inside your java app by using:

org.apache.log4j.PropertyConfigurator.configure(file/location/log4j.properties)

More information is available here: https://logging.apache.org/log4j/1.2/manual.html

How to open a new file in vim in a new window

I'm using the following, though it's hardcoded for gnome-terminal. It also changes the CWD and buffer for vim to be the same as your current buffer and it's directory.

:silent execute '!gnome-terminal -- zsh -i -c "cd ' shellescape(expand("%:h")) '; vim' shellescape(expand("%:p")) '; zsh -i"' <cr>

How to install wkhtmltopdf on a linux based (shared hosting) web server

Debian 8 Jessie
This works sudo apt-get install wkhtmltopdf

Iterating over and deleting from Hashtable in Java

So you know the key, value pair that you want to delete in advance? It's just much clearer to do this, then:

 table.delete(key);
 for (K key: table.keySet()) {
    // do whatever you need to do with the rest of the keys
 }

MySQL CURRENT_TIMESTAMP on create and on update

You are using older MySql version. Update your myqsl to 5.6.5+ it will work.

Finding the index of elements based on a condition using python list comprehension

For me it works well:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 1, 2, 3])
>>> np.where(a > 2)[0]
[2 5]

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

if you are using ASP.NET MVC

Open the layout file "_Layout.cshtml" or your custom one

At the part of the code you see, as below:

@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/jquery")

Remove the line "@Scripts.Render("~/bundles/jquery")"

(at the part of the code you see) past as the latest line, as below:

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")

This help me and hope helps you as well.

Convert date field into text in Excel

You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this

="Today is "&TEXT(A1,"dd-mm-yyyy")

You can change the "dd-mm-yyyy" part as required

How to handle query parameters in angular 2

The simple way to do that in Angular 7+ is to:

Define a path in your ?-routing.module.ts

{ path: '/yourpage', component: component-name }

Import the ActivateRoute and Router module in your component and inject them in the constructor

contructor(private route: ActivateRoute, private router: Router){ ... }

Subscribe the ActivateRoute to the ngOnInit

ngOnInit() {

    this.route.queryParams.subscribe(params => {
      console.log(params);
      // {page: '2' }
    })
}

Provide it to a link:

<a [routerLink]="['/yourpage']" [queryParams]="{ page: 2 }">2</a>

Rebuild all indexes in a Database

Also a good script, although my laptop ran out of memory, but this was on a very large table

https://basitaalishan.com/2014/02/23/rebuild-all-indexes-on-all-tables-in-the-sql-server-database/

USE [<mydatabasename>]
Go

--/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--Arguments             Data Type               Description
--------------          ------------            ------------
--@FillFactor           [int]                   Specifies a percentage that indicates how full the Database Engine should make the leaf level
--                                              of each index page during index creation or alteration. The valid inputs for this parameter
--                                              must be an integer value from 1 to 100 The default is 0.
--                                              For more information, see http://technet.microsoft.com/en-us/library/ms177459.aspx.

--@PadIndex             [varchar](3)            Specifies index padding. The PAD_INDEX option is useful only when FILLFACTOR is specified,
--                                              because PAD_INDEX uses the percentage specified by FILLFACTOR. If the percentage specified
--                                              for FILLFACTOR is not large enough to allow for one row, the Database Engine internally
--                                              overrides the percentage to allow for the minimum. The number of rows on an intermediate
--                                              index page is never less than two, regardless of how low the value of fillfactor. The valid
--                                              inputs for this parameter are ON or OFF. The default is OFF.
--                                              For more information, see http://technet.microsoft.com/en-us/library/ms188783.aspx.

--@SortInTempDB         [varchar](3)            Specifies whether to store temporary sort results in tempdb. The valid inputs for this
--                                              parameter are ON or OFF. The default is OFF.
--                                              For more information, see http://technet.microsoft.com/en-us/library/ms188281.aspx.

--@OnlineRebuild        [varchar](3)            Specifies whether underlying tables and associated indexes are available for queries and data
--                                              modification during the index operation. The valid inputs for this parameter are ON or OFF.
--                                              The default is OFF.
--                                              Note: Online index operations are only available in Enterprise edition of Microsoft
--                                                      SQL Server 2005 and above.
--                                              For more information, see http://technet.microsoft.com/en-us/library/ms191261.aspx.

--@DataCompression      [varchar](4)            Specifies the data compression option for the specified index, partition number, or range of
--                                              partitions. The options  for this parameter are as follows:
--                                                  > NONE - Index or specified partitions are not compressed.
--                                                  > ROW  - Index or specified partitions are compressed by using row compression.
--                                                  > PAGE - Index or specified partitions are compressed by using page compression.
--                                              The default is NONE.
--                                              Note: Data compression feature is only available in Enterprise edition of Microsoft
--                                                      SQL Server 2005 and above.
--                                              For more information about compression, see http://technet.microsoft.com/en-us/library/cc280449.aspx.

--@MaxDOP               [int]                   Overrides the max degree of parallelism configuration option for the duration of the index
--                                              operation. The valid input for this parameter can be between 0 and 64, but should not exceed
--                                              number of processors available to SQL Server.
--                                              For more information, see http://technet.microsoft.com/en-us/library/ms189094.aspx.
--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/

-- Ensure a USE <databasename> statement has been executed first.

SET NOCOUNT ON;

DECLARE  @Version                           [numeric] (18, 10)
        ,@SQLStatementID                    [int]
        ,@CurrentTSQLToExecute              [nvarchar](max)
        ,@FillFactor                        [int]        = 100 -- Change if needed
        ,@PadIndex                          [varchar](3) = N'OFF' -- Change if needed
        ,@SortInTempDB                      [varchar](3) = N'OFF' -- Change if needed
        ,@OnlineRebuild                     [varchar](3) = N'OFF' -- Change if needed
        ,@LOBCompaction                     [varchar](3) = N'ON' -- Change if needed
        ,@DataCompression                   [varchar](4) = N'NONE' -- Change if needed
        ,@MaxDOP                            [int]        = NULL -- Change if needed
        ,@IncludeDataCompressionArgument    [char](1);

IF OBJECT_ID(N'TempDb.dbo.#Work_To_Do') IS NOT NULL
    DROP TABLE #Work_To_Do
CREATE TABLE #Work_To_Do
    (
      [sql_id] [int] IDENTITY(1, 1)
                     PRIMARY KEY ,
      [tsql_text] [varchar](1024) ,
      [completed] [bit]
    )

SET @Version = CAST(LEFT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - 1) + N'.' + REPLACE(RIGHT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), LEN(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)))), N'.', N'') AS [numeric](18, 10))

IF @DataCompression IN (N'PAGE', N'ROW', N'NONE')
    AND (
        @Version >= 10.0
        AND SERVERPROPERTY(N'EngineEdition') = 3
        )
BEGIN
    SET @IncludeDataCompressionArgument = N'Y'
END

IF @IncludeDataCompressionArgument IS NULL
BEGIN
    SET @IncludeDataCompressionArgument = N'N'
END

INSERT INTO #Work_To_Do ([tsql_text], [completed])
SELECT 'ALTER INDEX [' + i.[name] + '] ON' + SPACE(1) + QUOTENAME(t2.[TABLE_CATALOG]) + '.' + QUOTENAME(t2.[TABLE_SCHEMA]) + '.' + QUOTENAME(t2.[TABLE_NAME]) + SPACE(1) + 'REBUILD WITH (' + SPACE(1) + + CASE
        WHEN @PadIndex IS NULL
            THEN 'PAD_INDEX =' + SPACE(1) + CASE i.[is_padded]
                    WHEN 1
                        THEN 'ON'
                    WHEN 0
                        THEN 'OFF'
                    END
        ELSE 'PAD_INDEX =' + SPACE(1) + @PadIndex
        END + CASE
        WHEN @FillFactor IS NULL
            THEN ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), REPLACE(i.[fill_factor], 0, 100))
        ELSE ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), @FillFactor)
        END + CASE
        WHEN @SortInTempDB IS NULL
            THEN ''
        ELSE ', SORT_IN_TEMPDB =' + SPACE(1) + @SortInTempDB
        END + CASE
        WHEN @OnlineRebuild IS NULL
            THEN ''
        ELSE ', ONLINE =' + SPACE(1) + @OnlineRebuild
        END + ', STATISTICS_NORECOMPUTE =' + SPACE(1) + CASE st.[no_recompute]
        WHEN 0
            THEN 'OFF'
        WHEN 1
            THEN 'ON'
        END + ', ALLOW_ROW_LOCKS =' + SPACE(1) + CASE i.[allow_row_locks]
        WHEN 0
            THEN 'OFF'
        WHEN 1
            THEN 'ON'
        END + ', ALLOW_PAGE_LOCKS =' + SPACE(1) + CASE i.[allow_page_locks]
        WHEN 0
            THEN 'OFF'
        WHEN 1
            THEN 'ON'
        END + CASE
        WHEN @IncludeDataCompressionArgument = N'Y'
            THEN CASE
                    WHEN @DataCompression IS NULL
                        THEN ''
                    ELSE ', DATA_COMPRESSION =' + SPACE(1) + @DataCompression
                    END
        ELSE ''
        END + CASE
        WHEN @MaxDop IS NULL
            THEN ''
        ELSE ', MAXDOP =' + SPACE(1) + CONVERT([varchar](2), @MaxDOP)
        END + SPACE(1) + ')'
    ,0
FROM [sys].[tables] t1
INNER JOIN [sys].[indexes] i ON t1.[object_id] = i.[object_id]
    AND i.[index_id] > 0
    AND i.[type] IN (1, 2)
INNER JOIN [INFORMATION_SCHEMA].[TABLES] t2 ON t1.[name] = t2.[TABLE_NAME]
    AND t2.[TABLE_TYPE] = 'BASE TABLE'
INNER JOIN [sys].[stats] AS st WITH (NOLOCK) ON st.[object_id] = t1.[object_id]
    AND st.[name] = i.[name]

SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0

WHILE @SQLStatementID IS NOT NULL
BEGIN
    SELECT @CurrentTSQLToExecute = [tsql_text]
    FROM #Work_To_Do
    WHERE [sql_id] = @SQLStatementID

    PRINT @CurrentTSQLToExecute

    EXEC [sys].[sp_executesql] @CurrentTSQLToExecute

    UPDATE #Work_To_Do
    SET [completed] = 1
    WHERE [sql_id] = @SQLStatementID

    SELECT @SQLStatementID = MIN([sql_id])
    FROM #Work_To_Do
    WHERE [completed] = 0
END

How to check if a table is locked in sql server

You can use the sys.dm_tran_locks view, which returns information about the currently active lock manager resources.

Try this

 SELECT 
     SessionID = s.Session_id,
     resource_type,   
     DatabaseName = DB_NAME(resource_database_id),
     request_mode,
     request_type,
     login_time,
     host_name,
     program_name,
     client_interface_name,
     login_name,
     nt_domain,
     nt_user_name,
     s.status,
     last_request_start_time,
     last_request_end_time,
     s.logical_reads,
     s.reads,
     request_status,
     request_owner_type,
     objectid,
     dbid,
     a.number,
     a.encrypted ,
     a.blocking_session_id,
     a.text       
 FROM   
     sys.dm_tran_locks l
     JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
     LEFT JOIN   
     (
         SELECT  *
         FROM    sys.dm_exec_requests r
         CROSS APPLY sys.dm_exec_sql_text(sql_handle)
     ) a ON s.session_id = a.session_id
 WHERE  
     s.session_id > 50

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

Check if string is in a pandas dataframe

Pandas seem to be recommending df.to_numpy since the other methods still raise a FutureWarning: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy

So, an alternative that would work int this case is:

b=a['Names']
c = b.to_numpy().tolist()
if 'Mel' in c:
     print("Mel is in the dataframe column Names")

Play an audio file using jQuery when a button is clicked

What about:

_x000D_
_x000D_
$('#play').click(function() {_x000D_
  const audio = new Audio("https://freesound.org/data/previews/501/501690_1661766-lq.mp3");_x000D_
  audio.play();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Convert array into csv

The accepted answer from Paul is great. I've made a small extension to this which is very useful if you have an multidimensional array like this (which is quite common):

Array
(
    [0] => Array
        (
            [a] => "a"
            [b] => "b"
        )

    [1] => Array
        (
            [a] => "a2"
            [b] => "b2"
        )

    [2] => Array
        (
            [a] => "a3"
            [b] => "b3"
        )

    [3] => Array
        (
            [a] => "a4"
            [b] => "b4"
        )

    [4] => Array
        (
            [a] => "a5"
            [b] => "b5"
        )

)

So I just took Paul's function from above:

/**
  * Formats a line (passed as a fields  array) as CSV and returns the CSV as a string.
  * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
  */
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ( $fields as $field ) {
        if ($field === null && $nullToMysqlNull) {
            $output[] = 'NULL';
            continue;
        }

        // Enclose fields containing $delimiter, $enclosure or whitespace
        if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
            $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
        }
        else {
            $output[] = $field;
        }
    }

    return implode( $delimiter, $output );
}

And added this:

function a2c($array, $glue = "\n")
{
    $ret = [];
    foreach ($array as $item) {
        $ret[] = arrayToCsv($item);
    }
    return implode($glue, $ret);
}

So you can just call:

$csv = a2c($array);

If you want a special line ending you can use the optional parameter "glue" for this.

C: printf a float value

printf("%0k.yf" float_variable_name)

Here k is the total number of characters you want to get printed. k = x + 1 + y (+ 1 for the dot) and float_variable_name is the float variable that you want to get printed.

Suppose you want to print x digits before the decimal point and y digits after it. Now, if the number of digits before float_variable_name is less than x, then it will automatically prepend that many zeroes before it.

C++ compile time error: expected identifier before numeric constant

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

OnClickListener in Android Studio

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_my);
    titolorecuperato = (TextView) findViewById(R.id.textView);
    String stitolo = titolorecuperato.getText().toString();

    Button btnHome = (Button) findViewById(R.id.button);

    btnHome.setOnClickListener(new View.OnClickListener() {

       @Override
        public void onClick(View view) {

       }
});

same thing as Nic007 said before.

You do need to write code inside "onCreate" method. Sorry me too for the indent... (first comment here)

Append a Lists Contents to another List C#

if you want to get "terse" :)

List<string>GlobalStrings = new List<string>(); 

for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});

SSH library for Java

Take a look at the very recently released SSHD, which is based on the Apache MINA project.

Type List vs type ArrayList in Java

It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set.

Set<String> names = new HashSet<String>();

This way, you have to change only one line if you decide to use a TreeSet instead.

Also, methods that operate on sets should specify parameters of type Set:

public static void print(Set<String> s)

Then the method can be used for all set implementations.

In theory, we should make the same recommendation for linked lists, namely to save LinkedList references in variables of type List. However, in the Java library, the List interface is common to both the ArrayList and the LinkedList class. In particular, it has get and set methods for random access, even though these methods are very inefficient for linked lists.

You can’t write efficient code if you don’t know whether random access is efficient or not.

This is plainly a serious design error in the standard library, and I cannot recommend using the List interface for that reason.

To see just how embarrassing that error is, have a look at the source code for the binarySearch method of the Collections class. That method takes a List parameter, but binary search makes no sense for a linked list. The code then clumsily tries to discover whether the list is a linked list, and then switches to a linear search!

The Set interface and the Map interface, are well designed, and you should use them.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

How to set a value for a span using jQuery

Syntax:

$(selector).text() returns the text content.

$(selector).text(content) sets the text content.

$(selector).text(function(index, curContent)) sets text content using a function.

kaynak: https://www.geeksforgeeks.org/jquery-change-the-text-of-a-span-element/

How to concatenate two MP4 files using FFmpeg?

ffmpeg \
  -i input_1.mp4 \
  -i input_2.mp4 \
  -filter_complex '[0:v]pad=iw*2:ih[int];[int][1:v]overlay=W/2:0[vid]' \
  -map [vid] \
  -c:v libx264 \
  -crf 23 \
  -preset veryfast \
  output.mp4

Download multiple files as a zip-file using php

You are ready to do with php zip lib, and can use zend zip lib too,

<?PHP
// create object
$zip = new ZipArchive();   

// open archive 
if ($zip->open('app-0.09.zip') !== TRUE) {
    die ("Could not open archive");
}

// get number of files in archive
$numFiles = $zip->numFiles;

// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
    $file = $zip->statIndex($x);
    printf("%s (%d bytes)", $file['name'], $file['size']);
    print "
";    
}

// close archive
$zip->close();
?>

http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/

and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php

Why can't I have abstract static methods in C#?

Another respondent (McDowell) said that polymorphism only works for object instances. That should be qualified; there are languages that do treat classes as instances of a "Class" or "Metaclass" type. These languages do support polymorphism for both instance and class (static) methods.

C#, like Java and C++ before it, is not such a language; the static keyword is used explicitly to denote that the method is statically-bound rather than dynamic/virtual.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Apache and IIS side by side (both listening to port 80) on windows2003

Either two different IP addresses (like recommended) or one web server is reverse-proxying the other (which is listening on a port <>80).

For instance: Apache listens on port 80, IIS on port 8080. Every http request goes to Apache first (of course). You can then decide to forward every request to a particular (named virtual) domain or every request that contains a particular directory (e.g. http://www.example.com/winapp/) to the IIS.

Advantage of this concept is that you have only one server listening to the public instead of two, you are more flexible as with two distinct servers.

Drawbacks: some webapps are crappily designed and a real pain in the ass to integrate into a reverse-proxy infrastructure. A working IIS webapp is dependent on a working Apache, so we have some inter-dependencies.

Single controller with multiple GET methods in ASP.NET Web API

I am not sure if u have found the answer, but I did this and it works

public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

// GET /api/values/5
public string Get(int id)
{
    return "value";
}

// GET /api/values/5
[HttpGet]
public string GetByFamily()
{
    return "Family value";
}

Now in global.asx

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapHttpRoute(
    name: "DefaultApi2",
    routeTemplate: "api/{controller}/{action}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Changing the default icon in a Windows Forms application

Select your project properties from Project Tab Then Application->Resource->Icon And Manifest->change the default icon

This works in Visual studio 2019 finely Note:Only files with .ico format can be added as icon

How to change the status bar background color and text color on iOS 7?

Swift 4:

// Change status bar background color

let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView

statusBar?.backgroundColor = UIColor.red

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Requirements files use an expanded pip format, which is only useful if you need to complement your setup.py with stronger constraints, for example specifying the exact urls some of the dependencies must come from, or the output of pip freeze to freeze the entire package set to known-working versions. If you don't need the extra constraints, use only a setup.py. If you feel like you really need to ship a requirements.txt anyway, you can make it a single line:

.

It will be valid and refer exactly to the contents of the setup.py that is in the same directory.

In a Bash script, how can I exit the entire script if a certain condition occurs?

I have the same question but cannot ask it because it would be a duplicate.

The accepted answer, using exit, does not work when the script is a bit more complicated. If you use a background process to check for the condition, exit only exits that process, as it runs in a sub-shell. To kill the script, you have to explicitly kill it (at least that is the only way I know).

Here is a little script on how to do it:

#!/bin/bash

boom() {
    while true; do sleep 1.2; echo boom; done
}

f() {
    echo Hello
    N=0
    while
        ((N++ <10))
    do
        sleep 1
        echo $N
        #        ((N > 5)) && exit 4 # does not work
        ((N > 5)) && { kill -9 $$; exit 5; } # works 
    done
}

boom &
f &

while true; do sleep 0.5; echo beep; done

This is a better answer but still incomplete a I really don't know how to get rid of the boom part.

Room persistance library. Delete all

I had issues with delete all method when using RxJava to execute this task on background. This is how I finally solved it:

@Dao
interface UserDao {
    @Query("DELETE FROM User")
    fun deleteAll()
}

and

fun deleteAllUsers() {
    return Maybe.fromAction(userDao::deleteAll)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe ({
            d("database rows cleared: $it")
        }, {
            e(it)
        }).addTo(compositeDisposable)
}

Download JSON object as a file from browser

This would be a pure JS version (adapted from cowboy's):

var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

var a = document.createElement('a');
a.href = 'data:' + data;
a.download = 'data.json';
a.innerHTML = 'download JSON';

var container = document.getElementById('container');
container.appendChild(a);

http://jsfiddle.net/sz76c083/1

SELECT CASE WHEN THEN (SELECT)

I ended up leaving the common properties from the SELECT queries and making a second SELECT query later on in the page. I used a php IF command to call for different scripts depending on the first SELECT query, the scripts contained the second SELECT query.

How to access List elements

It's simple

y = [['vegas','London'],['US','UK']]

for x in y:
    for a in x:
        print(a)

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

I've found that using OnTime can be painful, particularly when:

  1. You're trying to code and the focus on the window gets interrupted every time the event triggers.
  2. You have multiple workbooks open, you close the one that's supposed to use the timer, and it keeps triggering and reopening the workbook (if you forgot to kill the event properly).

This article by Chip Pearson was very illuminating. I prefer to use the Windows Timer now, instead of OnTime.

How do I unload (reload) a Python module?

If you encounter the following error, this answer may help you to get a solution:

Traceback (most recent call last): 
 File "FFFF", line 1, in  
NameError: name 'YYYY' is not defined

OR

Traceback (most recent call last):
 File "FFFF", line 1, in 
 File "/usr/local/lib/python3.7/importlib/__init__.py", line 140, in reload
   raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module

In case you have an import like the one below, you may need to use the sys.modules to get the module you want to reload:

  import importlib
  import sys

  from YYYY.XXX.ZZZ import CCCC
  import AAA.BBB.CC


  def reload(full_name)
    if full_name in sys.modules:
      importlib.reload(sys.modules[full_name])


  reload('YYYY.XXX.ZZZ') # this is fine in both cases
  reload('AAA.BBB.CC')  

  importlib.reload(YYYY.XXX.ZZZ) # in my case: this fails
  importlib.reload(AAA.BBB.CC)   #             and this is ok

The main issue is that the importlib.reload accepts module only not string.

Writing new lines to a text file in PowerShell

Try this;

Add-Content -path $logpath @"
$((get-date).tostring()) Error $keyPath $value
key $key expected: $policyValue
local value is:  $localValue
"@

Java image resize, maintain aspect ratio

Just add one more block to Ozzy's code so the thing looks like this:

public static Dimension getScaledDimension(Dimension imgSize,Dimension boundary) {

    int original_width = imgSize.width;
    int original_height = imgSize.height;
    int bound_width = boundary.width;
    int bound_height = boundary.height;
    int new_width = original_width;
    int new_height = original_height;

    // first check if we need to scale width
    if (original_width > bound_width) {
        //scale width to fit
        new_width = bound_width;
        //scale height to maintain aspect ratio
        new_height = (new_width * original_height) / original_width;
    }

    // then check if we need to scale even with the new height
    if (new_height > bound_height) {
        //scale height to fit instead
        new_height = bound_height;
        //scale width to maintain aspect ratio
        new_width = (new_height * original_width) / original_height;
    }
    // upscale if original is smaller
    if (original_width < bound_width) {
        //scale width to fit
        new_width = bound_width;
        //scale height to maintain aspect ratio
        new_height = (new_width * original_height) / original_width;
    }

    return new Dimension(new_width, new_height);
}

Get counts of all tables in a schema

You have to use execute immediate (dynamic sql).

DECLARE 
v_owner varchar2(40); 
v_table_name varchar2(40); 
cursor get_tables is 
select distinct table_name,user 
from user_tables 
where lower(user) = 'schema_name'; 
begin 
open get_tables; 
loop
    fetch get_tables into v_table_name,v_owner; 
    EXIT WHEN get_tables%NOTFOUND;
    execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED) 
    SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'')     FROM ' || v_table_name; 
end loop;
CLOSE get_tables; 
END; 

How should I declare default values for instance variables in Python?

Using class members to give default values works very well just so long as you are careful only to do it with immutable values. If you try to do it with a list or a dict that would be pretty deadly. It also works where the instance attribute is a reference to a class just so long as the default value is None.

I've seen this technique used very successfully in repoze which is a framework that runs on top of Zope. The advantage here is not just that when your class is persisted to the database only the non-default attributes need to be saved, but also when you need to add a new field into the schema all the existing objects see the new field with its default value without any need to actually change the stored data.

I find it also works well in more general coding, but it's a style thing. Use whatever you are happiest with.

How can I solve equations in Python?

If you only want to solve the extremely limited set of equations mx + c = y for positive integer m, c, y, then this will do:

import re
def solve_linear_equation ( equ ):
    """
    Given an input string of the format "3x+2=6", solves for x.
    The format must be as shown - no whitespace, no decimal numbers,
    no negative numbers.
    """
    match = re.match(r"(\d+)x\+(\d+)=(\d+)", equ)
    m, c, y = match.groups()
    m, c, y = float(m), float(c), float(y) # Convert from strings to numbers
    x = (y-c)/m
    print ("x = %f" % x)

Some tests:

>>> solve_linear_equation("2x+4=12")
x = 4.000000
>>> solve_linear_equation("123x+456=789")
x = 2.707317
>>> 

If you want to recognise and solve arbitrary equations, like sin(x) + e^(i*pi*x) = 1, then you will need to implement some kind of symbolic maths engine, similar to maxima, Mathematica, MATLAB's solve() or Symbolic Toolbox, etc. As a novice, this is beyond your ken.

Click a button programmatically - JS

Though this question is rather old, here's a answer :)

What you are asking for can be achieved by using jQuery's .click() event method and .on() event method

So this could be the code:

// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");

$(document).ready(function() {
    // When the document is ready/loaded, execute function

    // Hide hangoutButton
    hangoutButton.hide();

    // Assign "click"-event-method to userImage
    userImage.on("click", function() {
        console.log("in onclick");
        hangoutButton.click();
    });
});

How to get Spinner selected item value to string?

Get the selected item with Kotlin:

spinner.selectedItem.toString()

Presenting modal in iOS 13 fullscreen

There are multiple ways to do that, and I think each one could fit for one project but not another, so I thought I'll keep them here maybe someone else will run to a different case.

1- Override present

If you have a BaseViewController you can override the present(_ viewControllerToPresent: animated flag: completion:) method.

class BaseViewController: UIViewController {

  // ....

  override func present(_ viewControllerToPresent: UIViewController,
                        animated flag: Bool,
                        completion: (() -> Void)? = nil) {
    viewControllerToPresent.modalPresentationStyle = .fullScreen
    super.present(viewControllerToPresent, animated: flag, completion: completion)
  }

  // ....
}

Using this way you don't need to do any change on any present call, as we just overrode the present method.

2- An extension:

extension UIViewController {
  func presentInFullScreen(_ viewController: UIViewController,
                           animated: Bool,
                           completion: (() -> Void)? = nil) {
    viewController.modalPresentationStyle = .fullScreen
    present(viewController, animated: animated, completion: completion)
  }
}

Usage:

presentInFullScreen(viewController, animated: true)

3- For one UIViewController

let viewController = UIViewController()
viewController.modalPresentationStyle = .fullScreen
present(viewController, animated: true, completion: nil)

4- From Storyboard

Select a segue and set the presentation to FullScreen.
enter image description here

5- Swizzling

extension UIViewController {

  static func swizzlePresent() {

    let orginalSelector = #selector(present(_: animated: completion:))
    let swizzledSelector = #selector(swizzledPresent)

    guard let orginalMethod = class_getInstanceMethod(self, orginalSelector), let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else{return}

    let didAddMethod = class_addMethod(self,
                                       orginalSelector,
                                       method_getImplementation(swizzledMethod),
                                       method_getTypeEncoding(swizzledMethod))

    if didAddMethod {
      class_replaceMethod(self,
                          swizzledSelector,
                          method_getImplementation(orginalMethod),
                          method_getTypeEncoding(orginalMethod))
    } else {
      method_exchangeImplementations(orginalMethod, swizzledMethod)
    }

  }

  @objc
  private func swizzledPresent(_ viewControllerToPresent: UIViewController,
                               animated flag: Bool,
                               completion: (() -> Void)? = nil) {
    if #available(iOS 13.0, *) {
      if viewControllerToPresent.modalPresentationStyle == .automatic {
        viewControllerToPresent.modalPresentationStyle = .fullScreen
      }
    }
    swizzledPresent(viewControllerToPresent, animated: flag, completion: completion)
   }
}

Usage:
In your AppDelegate inside application(_ application: didFinishLaunchingWithOptions) add this line:

UIViewController.swizzlePresent()

Using this way you don't need to do any change on any present call, as we are replacing the present method implementation in runtime.
If you need to know what is swizzling you can check this link: https://nshipster.com/swift-objc-runtime/

Detect click outside element

I hate additional functions so... here is an awesome vue solution without an additional vue methods, only var

  1. create html element, set controls and directive
    <p @click="popup = !popup" v-out="popup">

    <div v-if="popup">
       My awesome popup
    </div>
  1. create a var in data like
data:{
   popup: false,
}
  1. add vue directive. its
Vue.directive('out', {

    bind: function (el, binding, vNode) {
        const handler = (e) => {
            if (!el.contains(e.target) && el !== e.target) {
                //and here is you toggle var. thats it
                vNode.context[binding.expression] = false
            }
        }
        el.out = handler
        document.addEventListener('click', handler)
    },

    unbind: function (el, binding) {
        document.removeEventListener('click', el.out)
        el.out = null
    }
})

Git - remote: Repository not found

If you are on windows got to control pannel -> windows Credentials then remove github credential from generic credential option. Then try to clone

Adding a new line/break tag in XML

This solution worked to me:

<summary>Tootsie roll tiramisu macaroon wafer carrot cake. &#xD;Danish topping sugar plum tart bonbon caramels cake.</summary>

You will have the text in two lines.

This worked to me using the XmlReader.Read method.

Psql could not connect to server: No such file or directory, 5432 error?

The same thing happened to me as I had changed something in the /etc/hosts file. After changing it back to 127.0.0.1 localhost it worked for me.

addClass and removeClass in jQuery - not removing class

I think you're almost there. The thing is, your $(this) in the "close button" listener is not the clickable div. So you want to search it first. try to replace $(this) with $(this).closest(".clickable") . And don't forget the e.stopPropagation() as Guilherme is suggesting. that should be something like:

$( document ).ready(function() {   
    $(document).on("click", ".close_button", function () { 
        alert ("oi");
        e.stopPropagation()
        $(this).closest(".clickable").addClass("spot");
        $(this).closest(".clickable").removeClass("grown");
    });  


    $(document).on("click", ".clickable", function () {
        if ($(this).hasClass("spot")){
            $(this).addClass("grown");
            $(this).removeClass("spot");
        }
    });
});

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

Lists in ConfigParser

As mentioned by Peter Smit (https://stackoverflow.com/a/11866695/7424596) You might want to extend ConfigParser, in addition, an Interpolator can be used to automatically convert into and from the list.

For reference at the bottom you can find code which automatically converts config like:

[DEFAULT]
keys = [
    Overall cost structure, Capacity, RAW MATERIALS,
    BY-PRODUCT CREDITS, UTILITIES, PLANT GATE COST,
    PROCESS DESCRIPTION, AT 50% CAPACITY, PRODUCTION COSTS,
    INVESTMENT, US$ MILLION, PRODUCTION COSTS, US ¢/LB,
    VARIABLE COSTS, PRODUCTION COSTS, MAINTENANCE MATERIALS
  ]

So if you request keys you will get:

<class 'list'>: ['Overall cost structure', 'Capacity', 'RAW MATERIALS', 'BY-PRODUCT CREDITS', 'UTILITIES', 'PLANT GATE COST', 'PROCESS DESCRIPTION', 'AT 50% CAPACITY', 'PRODUCTION COSTS', 'INVESTMENT', 'US$ MILLION', 'PRODUCTION COSTS', 'US ¢/LB', 'VARIABLE COSTS', 'PRODUCTION COSTS', 'MAINTENANCE MATERIALS']

Code:

class AdvancedInterpolator(Interpolation):
    def before_get(self, parser, section, option, value, defaults):
        is_list = re.search(parser.LIST_MATCHER, value)
        if is_list:
            return parser.getlist(section, option, raw=True)
        return value


class AdvancedConfigParser(ConfigParser):

    _DEFAULT_INTERPOLATION = AdvancedInterpolator()

    LIST_SPLITTER = '\s*,\s*'
    LIST_MATCHER = '^\[([\s\S]*)\]$'

    def _to_list(self, str):
        is_list = re.search(self.LIST_MATCHER, str)
        if is_list:
            return re.split(self.LIST_SPLITTER, is_list.group(1))
        else:
            return re.split(self.LIST_SPLITTER, str)


    def getlist(self, section, option, conv=lambda x:x.strip(), *, raw=False, vars=None,
                  fallback=_UNSET, **kwargs):
        return self._get_conv(
                section, option,
                lambda value: [conv(x) for x in self._to_list(value)],
                raw=raw,
                vars=vars,
                fallback=fallback,
                **kwargs
        )

    def getlistint(self, section, option, *, raw=False, vars=None,
            fallback=_UNSET, **kwargs):
        return self.getlist(section, option, int, raw=raw, vars=vars,
                fallback=fallback, **kwargs)

    def getlistfloat(self, section, option, *, raw=False, vars=None,
            fallback=_UNSET, **kwargs):
        return self.getlist(section, option, float, raw=raw, vars=vars,
                fallback=fallback, **kwargs)

    def getlistboolean(self, section, option, *, raw=False, vars=None,
            fallback=_UNSET, **kwargs):
        return self.getlist(section, option, self._convert_to_boolean,
                raw=raw, vars=vars, fallback=fallback, **kwargs)

Ps keep in mind importance of indentdation. As reads in ConfigParser doc string:

Values can span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser's mode, blank lines may be treated as parts of multiline values or ignored.

How to copy files from 'assets' folder to sdcard?

You can also use Guava's ByteStream to copy the files from the assets folder to the SD card. This is the solution I ended up with which copies files recursively from the assets folder to the SD card:

/**
 * Copies all assets in an assets directory to the SD file system.
 */
public class CopyAssetsToSDHelper {

    public static void copyAssets(String assetDir, String targetDir, Context context) 
        throws IOException {
        AssetManager assets = context.getAssets();
        String[] list = assets.list(assetDir);
        for (String f : Objects.requireNonNull(list)) {
            if (f.indexOf(".") > 1) { // check, if this is a file
                File outFile = new File(context.getExternalFilesDir(null), 
                    String.format("%s/%s", targetDir, f));
                File parentFile = outFile.getParentFile();
                if (!Objects.requireNonNull(parentFile).exists()) {
                    if (!parentFile.mkdirs()) {
                        throw new IOException(String.format("Could not create directory %s.", 
                            parentFile));
                    }
                }
                try (InputStream fin = assets.open(String.format("%s/%s", assetDir, f));
                     OutputStream fout = new FileOutputStream(outFile)) {
                    ByteStreams.copy(fin, fout);
                }
            } else { // This is a directory
                copyAssets(String.format("%s/%s", assetDir, f), String.format("%s/%s", targetDir, f), 
                    context);
            }
        }
    }

}

How to make primary key as autoincrement for Room Persistence lib

You can add @PrimaryKey(autoGenerate = true) like this:

@Entity
data class Food(
        var foodName: String, 
        var foodDesc: String, 
        var protein: Double, 
        var carbs: Double, 
        var fat: Double
){
    @PrimaryKey(autoGenerate = true)
    var foodId: Int = 0 // or foodId: Int? = null
    var calories: Double = 0.toDouble()
}

How to access the last value in a vector?

Another way is to take the first element of the reversed vector:

rev(dat$vect1$vec2)[1]

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Here is a possible solution:

From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

Here is invis.vbs:

set args = WScript.Arguments
num = args.Count

if num = 0 then
    WScript.Echo "Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>"
    WScript.Quit 1
end if

sargs = ""
if num > 1 then
    sargs = " "
    for k = 1 to num - 1
        anArg = args.Item(k)
        sargs = sargs & anArg & " "
    next
end if

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False

how to add button click event in android studio

SetOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)

This means in other words (due to your current scenario) that your MainActivity need to implement OnClickListener:

public class Main extends ActionBarActivity implements View.OnClickListener {
   // do your stuff
}

This:

buttonname.setOnClickListener(this);

means that you want to assign listener for your Button "on this instance" -> this instance represents OnClickListener and for this reason your class have to implement that interface.

It's similar with anonymous listener class (that you can also use):

buttonname.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

   }
});

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

What is a Python equivalent of PHP's var_dump()?

I wrote a very light-weight alternative to PHP's var_dump for using in Python and made it open source later.

GitHub: https://github.com/sha256/python-var-dump

You can simply install it using pip:

pip install var_dump

UIView with rounded corners and drop shadow?

This is how you do it, with rounded corners and rounded shadows without bothering with paths.

//Inner view with content
[imageView.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
[imageView.layer setBorderWidth:1.0f];
[imageView.layer setCornerRadius:8.0f];
[imageView.layer setMasksToBounds:YES];

//Outer view with shadow
UIView* shadowContainer = [[UIView alloc] initWithFrame:imageView.frame];
[shadowContainer.layer setMasksToBounds:NO];
[shadowContainer.layer setShadowColor:[[UIColor blackColor] CGColor]];
[shadowContainer.layer setShadowOpacity:0.6f];
[shadowContainer.layer setShadowRadius:2.0f];
[shadowContainer.layer setShadowOffset: CGSizeMake(0.0f, 2.0f)];

[shadowContainer addSubview:imageView];

The view with content, in my case a UIImageView, has a corner radius and therefore has to mask to bounds.

We create another equally sized view for the shadows, set it's maskToBounds to NO and then add the content view to the container view (e.g. shadowContainer).

How to add Google Maps Autocomplete search box?

A significant portion of this code can be eliminated.

HTML excerpt:

<head>
  ...
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
  ...
</head>
<body>
  ...
  <input id="searchTextField" type="text" size="50">
  ...
</body>

Javascript:

function initialize() {
  var input = document.getElementById('searchTextField');
  new google.maps.places.Autocomplete(input);
}

google.maps.event.addDomListener(window, 'load', initialize);

Convert integer into byte array (Java)

You can use BigInteger:

From Integers:

byte[] array = BigInteger.valueOf(0xAABBCCDD).toByteArray();
System.out.println(Arrays.toString(array))
// --> {-86, -69, -52, -35 }

The returned array is of the size that is needed to represent the number, so it could be of size 1, to represent 1 for example. However, the size cannot be more than four bytes if an int is passed.

From Strings:

BigInteger v = new BigInteger("AABBCCDD", 16);
byte[] array = v.toByteArray();

However, you will need to watch out, if the first byte is higher 0x7F (as is in this case), where BigInteger would insert a 0x00 byte to the beginning of the array. This is needed to distinguish between positive and negative values.

Unexpected character encountered while parsing value

I have also encountered this error for a Web API (.Net Core 3.0) action that was binding to a string instead to an object or a JObject. The JSON was correct, but the binder tried to get a string from the JSON structure and failed.

So, instead of:

[HttpPost("[action]")]
public object Search([FromBody] string data)

I had to use the more specific:

[HttpPost("[action]")]
public object Search([FromBody] JObject data)

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

RegEx: Grabbing values between quotation marks

string = "\" foo bar\" \"loloo\""
print re.findall(r'"(.*?)"',string)

just try this out , works like a charm !!!

\ indicates skip character

How to copy an object by value, not by reference

You may use clone() which works well if your object has immutable objects and/or primitives, but it may be a little problematic when you don't have these ( such as collections ) for which you may need to perform a deep clone.

User userCopy = (User) user.clone();//make a copy

for(...) {
    user.age = 1;
    user.id = -1;

    UserDao.update(user)
    user = userCopy; 
}

It seems like you just want to preserve the attributes: age and id which are of type int so, why don't you give it a try and see if it works.

For more complex scenarios you could create a "copy" method:

publc class User { 
    public static User copy( User other ) {
         User newUser = new User();
         newUser.age = other.age;
         newUser.id = other.id;
         //... etc. 
         return newUser;
    }
}

It should take you about 10 minutes.

And then you can use that instead:

     User userCopy = User.copy( user ); //make a copy
     // etc. 

To read more about clone read this chapter in Joshua Bloch "Effective Java: Override clone judiciously"

Which icon sizes should my Windows application's icon include?

From Microsoft MSDN recommendations:

Application icons and Control Panel items: The full set includes 16x16, 32x32, 48x48, and 256x256 (code scales between 32 and 256). The .ico file format is required. For Classic Mode, the full set is 16x16, 24x24, 32x32, 48x48 and 64x64.

So we have already standard recommended sizes of:

  • 16 x 16,
  • 24 x 24,
  • 32 x 32,
  • 48 x 48,
  • 64 x 64,
  • 256 x 256.

If we would like to support high DPI settings, the complete list will include the following sizes as well:

  • 20 x 20,
  • 30 x 30,
  • 36 x 36,
  • 40 x 40,
  • 60 x 60,
  • 72 x 72,
  • 80 x 80,
  • 96 x 96,
  • 128 x 128,
  • 320 x 320,
  • 384 x 384,
  • 512 x 512.

Meaning of $? (dollar question mark) in shell scripts

See The Bash Manual under 3.4.2 Special Parameters:

? - Expands to the exit status of the most recently executed foreground pipeline.

It is a little hard to find because it is not listed as $? (the variable name is "just" ?). Also see the exit status section, of course ;-)

Happy coding.

Javascript - sort array based on another array

_x000D_
_x000D_
function sortFunc(a, b) {
  var sortingArr = ["A", "B", "C"];
  return sortingArr.indexOf(a.type) - sortingArr.indexOf(b.type);
}

const itemsArray = [
  {
    type: "A",
  },
  {
    type: "C",
  },
  {
    type: "B",
  },
];
console.log(itemsArray);
itemsArray.sort(sortFunc);
console.log(itemsArray);
_x000D_
_x000D_
_x000D_

Return positions of a regex match() in Javascript?

_x000D_
_x000D_
var str = 'my string here';

var index = str.match(/hre/).index;

alert(index); // <- 10
_x000D_
_x000D_
_x000D_

How to determine a Python variable's type?

It may be little irrelevant. but you can check types of an object with isinstance(object, type) as mentioned here.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Add repository annotation before your DAO Implementation Class. example:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO{ 
}

Display XML content in HTML page

You can use the old <xmp> tag. I don't know about browser support, but it should still work.

<HTML>

your code/tables

<xmp>
    <catalog>
        <cd>
            <title>Empire Burlesque</title>
            <artist>Bob Dylan</artist>
            <country>USA</country>
            <country>Columbia</country>
            <price>10.90</price>
            <year>1985</year>
        </cd>
    </catalog>
</xmp>

Output:

your code/tables
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <country>Columbia</country>
        <price>10.90</price>
        <year>1985</year>
    </cd>
</catalog>

Unix ls command: show full path when using options

optimized from spacedrop answer ...

ls $(pwd)/*

and you can use ls options

ls -alrt $(pwd)/*

How to change an element's title attribute using jQuery

jqueryTitle({
    title: 'New Title'
});

for first title:

jqueryTitle('destroy');

https://github.com/ertaserdi/jQuery-Title

How to import/include a CSS file using PHP code and not HTML code?

The best way to do it is:

Step 1: Rename your main.css to main.php

Step 2: in your main.php add

<style> ... </style>

Step 3: include it as usual

<?php include 'main.php'; ?>

That is how i did it, and it works smoothly..

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))

If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals("en")

how to set the background color of the whole page in css

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>_x000D_
        webpage_x000D_
      </title>_x000D_
</head>_x000D_
  <body style="background-color:blue;text-align:center">_x000D_
    welcome to my page_x000D_
    </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

Is < faster than <=?

Only if the people who created the computers are bad with boolean logic. Which they shouldn't be.

Every comparison (>= <= > <) can be done in the same speed.

What every comparison is, is just a subtraction (the difference) and seeing if it's positive/negative.
(If the msb is set, the number is negative)

How to check a >= b? Sub a-b >= 0 Check if a-b is positive.
How to check a <= b? Sub 0 <= b-a Check if b-a is positive.
How to check a < b? Sub a-b < 0 Check if a-b is negative.
How to check a > b? Sub 0 > b-a Check if b-a is negative.

Simply put, the computer can just do this underneath the hood for the given op:

a >= b == msb(a-b)==0
a <= b == msb(b-a)==0
a > b == msb(b-a)==1
a < b == msb(a-b)==1

and of course the computer wouldn't actually need to do the ==0 or ==1 either.
for the ==0 it could just invert the msb from the circuit.

Anyway, they most certainly wouldn't have made a >= b be calculated as a>b || a==b lol

How to downgrade python from 3.7 to 3.6

Here is a canonical summary which sums up different solutions for the variety of operating system Python runs on. What follows are possibilities for Microsoft Windows, Linux, macOS and Misc.

As mentioned those are just possibilities - by no means do I claim to have a complete list whatsoever.


Microsoft Windows

Option 1

In general, it's suggested to use virtual environments (I highly suggest looking at the official Python documentation). With this approach, you easily can set up project-specific Python versions (as well as libraries). Easily manageable and the best part: There are lots of tutorials on the internet on how to approach this:

1.) Open command prompt ("cmd") and enter pip install virtualenv.

2.) Install your desired Python version via https://www.python.org/downloads/release; Remember: Do not add to PATH!

3.) Type into the command prompt: virtualenv \path\to\env -p \path\to\python_install.exe, whereas \path\to\env shall be the path where your virtual environment is going to be and \path\to\python_install.exe the one where your freshly (presumably) installed Python version resides.

4.) Done! You now have a virtual environment set up! Now, to activate the virtual environment execute the batch file which is located inside the \path\to\env\Scripts\activate.bat. (cf. this website or an official Python guide)

Option 2

The basic option would be to uninstall the unwanted Python version and re-install the favored one from https://www.python.org/downloads/. To remove the "old" version go to Control Panel -> "Uninstall a program" -> Search for "Python" -> Right-click on the Python name -> Uninstall. Bear in mind that Python usually has a PATH variable stored, hence you should remove it as well - Check the following links for this:

Now double-check whether there are any remaining files where Python used to be stored. Usually, you can find all the Python files at either C:\Program Files (x86)\Pythonxx, C:\Users\username\AppData\Local\Programs\Pythonxx or C:\Pythonxx or all of them. You might have installed it in another directory - check where it once was.

Now after de-installing just re-install the wanted version by going to the download page and follow the usual installation process. I won't go into details on how to install Python.. Lastly, you might check which version is currently installed by opening the command prompt and typing python -V.

Option 3

This approach is pretty similar to the second one - you basically uninstall the old one and replace it by your favored version. The only thing that changes it the part regarding how to uninstall the unwanted Python distribution: Simply execute the Python3 installer you originally used to install Python (it's usually stored in your Python directory as mentioned above; for more assistance check out this). There you get an option to repair or uninstall, proceed by choosing uninstall, and follow the steps provided via the uninstaller.

No matter how you uninstall Python (there are many resources on this topic, for example this Stack Overflow question or a problem thread a user by the name of Vincent Tang posted on the Stack Exchange site Super User, etc.), just reinstall the wanted Python version by following the steps mentioned in Option 2.

Option 4

Option 4 deals with Anaconda. Please refer to this site on how to install Anaconda on Windows. Step 9 is important as you don't want to install it as your default Python - you want to run multiple versions of Python:

Choose whether to register Anaconda as your default Python. Unless you plan on installing and running multiple versions of Anaconda or multiple versions of Python, accept the default and leave this box checked.

Follow the official tutorial I linked above.

Once done you can create the following commands individually in the anaconda prompt: To overwrite the default python version system-wise use conda install python=3.6 or to create a virtual environment go ahead and use conda create -n $PYTHON36_ENV_NAME python=3.6 anaconda whereas $PYTHON36_ENV_NAME is the custom name you can set. Credit where credit is due - the user @CermakM from this thread strongly influenced this snippet.

In my research I encountered a bunch of useful Stack Overflow threads - you might check them out if you go the tough road with Anaconda:

Option 5

What follows isn't a downgrade in the classical sense - though for the sake of completeness I decided to mention this approach as well. On Windows you're also able to run multiple Python versions - an infamous thread on StackOverflow deals with this question, thus I politely refer you to there for further reading purposes.


Linux

Option 1

Pretty analog to the third option for Windows I highly suggest you use a virtual environment such as Anaconda. Anaconda - or short conda - is also available on Linux. Check the official installation documentation here. Once again this thread is highly suggested on how to overwrite a Python version, respectively how to specifically create an environment with your wanted Python version.

Option 2

Another highly suggested virtual environment is Pyenv. The user @Sawan Vaidya described in this Stack Overflow question on how to up-or downgrade a Python version with the help of Pyenv. You can either set a Python version globally or create a local environment - both explained in the mentioned thread.

Option 3

Another user, namely @Jeereddy, has suggested to use the software package management system Homebrew. He explained this option thoroughly in this current question:

$ brew unlink python
$ brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/e128fa1bce3377de32cbf11bd8e46f7334dfd7a6/Formula/python.rb
$ brew switch python 3.6.5

Option 5

No need to reinvent the wheel - this thread is filled with lots of beautiful running approaches such as the one by @Sidharth Taneja.

  1. Download your wanted Python version from https://www.python.org/downloads/release and install it as a normal package.
  2. Run cd /Library/Frameworks/Python.framework/Version
  3. Execute ls to list all installed Python versions
  4. Run sudo rm -rf 3.7, removing Python version 3.7 - can be repeated for whatever version(s) you want to delete
  5. Check python3 -v, it should display the version you originally wanted to have installed

Option 6

What a goldmine this thread is! As @nondetermistic has described in-depth (direct link to his post):

Install Python source code as it is like this:

#Taken Python 3.6 as an example
$ mkdir /home/<user>/python3.6
$ ./configure --prefix=/home/<user>/python3.6/
$ make altinstall

You're now able to either add the downloaded version (/home/<user>/python3.6/bin) to PATH as well as lib to LD_LIBRARY_PATH or just create a virtual environment by: /home/<user>/python3.6/bin/python3.6 -m venv env-python3.6. A very aesthetic and simple solution to run multiple Python versions on your system.


macOS

Option 1

Using pyenv with Homebrew - credit to @Shayan with his reply here:

1.) Installing pyenv with Homebrew:

brew update
brew install pyenv

2.) Cloning the GitHub repository to get latest pyenv version:

 git clone https://github.com/pyenv/pyenv.git ~/.pyenv

3.) Defining the environment variables as follows

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile

4.) Restarting shell so PATH change works

exec "$SHELL"

5.) Checking the available Python versions

pyenv install --list

6.) Installing the wanted Python version, e.g. 3.6

pyenv install 3.6

7.) Setting it globally (you can also go ahead and only use it in a certain environment)

pyenv global 3.6

8.) Check the Python version the system is using - your wanted / downgraded version should be displayed here.

python3 --version

Option 2

Similar to previous approaches you can download Anaconda on macOS as well. For an installation guide click here. The usage is pretty much the same as I've already described in Option 4 of the Windows guide. Please check out above.

Other options

In this case it's getting pretty repetitive. I kindly suggest you to check the following resources for further reading:


Misc

When writing this post I had the problem of not knowing where to draw the line. When looking up the operating systems Python currently supports you get a huge list, including the ones I mentioned, i.e. Linux, Microsoft Windows and macOS, though obviously different Linux distributions are single-handedly treated, e.g. CentOS, Arch Linux or Fedora should deserve a spot as well - or shall I make separate options for Windows 10, 7, etc.?

Due to the high degree of repetitiveness as far as modules like Homebrew, Conda or alike are concerned I decided to limit my list to the "main three" operating systems - distributions like Ubuntu (How do I downgrade my version of python from 3.7.5 to 3.6.5 on ubuntu), CentOS (How to downgrade python version on CentOS?) can be easily researched on Stack Overflow. Most often than not you can apply solutions from the Linux tab for said distributions. The same goes with Windows and macOS (versions).

How to add option to select list in jQuery

It looks like you want this pluging as it follows your existing code, maybe the plug in js file got left out somewhere.

http://www.texotela.co.uk/code/jquery/select/

var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
} 
$("#myselect2").addOption(myOptions, false); 
// use true if you want to select the added options » Run

What does `return` keyword mean inside `forEach` function?

The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {
         break;
      }
      alert(n);
   })
})

You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

Using the Web.Config to set up my SQL database connection string?

If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS

Here is the connectionString in the web config file which you can add:

<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>

Place is just above the system.web tag.

Then you can call it by:

connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;

Fastest method to escape HTML tags as HTML entities?

I'll add XMLSerializer to the pile. It provides the fastest result without using any object caching (not on the serializer, nor on the Text node).

function serializeTextNode(text) {
  return new XMLSerializer().serializeToString(document.createTextNode(text));
}

The added bonus is that it supports attributes which is serialized differently than text nodes:

function serializeAttributeValue(value) {
  const attr = document.createAttribute('a');
  attr.value = value;
  return new XMLSerializer().serializeToString(attr);
}

You can see what it's actually replacing by checking the spec, both for text nodes and for attribute values. The full documentation has more node types, but the concept is the same.

As for performance, it's the fastest when not cached. When you do allow caching, then calling innerHTML on an HTMLElement with a child Text node is fastest. Regex would be slowest (as proven by other comments). Of course, XMLSerializer could be faster on other browsers, but in my (limited) testing, a innerHTML is fastest.


Fastest single line:

new XMLSerializer().serializeToString(document.createTextNode(text));

Fastest with caching:

const cachedElementParent = document.createElement('div');
const cachedChildTextNode = document.createTextNode('');
cachedElementParent.appendChild(cachedChildTextNode);

function serializeTextNode(text) {
  cachedChildTextNode.nodeValue = text;
  return cachedElementParent.innerHTML;
}

https://jsperf.com/htmlentityencode/1

SSL cert "err_cert_authority_invalid" on mobile chrome only

For those having this problem on IIS servers.

Explanation: sometimes certificates carry an URL of an intermediate certificate instead of the actual certificate. Desktop browsers can DOWNLOAD the missing intermediate certificate using this URL. But older mobile browsers are unable to do that. So they throw this warning.

You need to

1) make sure all intermediate certificates are served by the server

2) disable unneeded certification paths in IIS - Under "Trusted Root Certification Authorities", you need to "disable all purposes" for the certificate that triggers the download.

PS. my colleague has wrote a blog post with more detailed steps: https://www.jitbit.com/maxblog/21-errcertauthorityinvalid-on-android-and-iis/

How to search for a string in text files?

if True:
    print "true"

This always happens because True is always True.

You want something like this:

if check():
    print "true"
else:
    print "false"

Good luck!

Make Bootstrap's Carousel both center AND responsive?

On Boostrap 4 simply add mx-auto to your carousel image class.

<div class="carousel-item">
  <img class="d-block mx-auto" src="http://placehold.it/600x400" />
</div> 

Combine with the samples from the bootstrap carousel documentation as desired.

Show default value in Spinner in android

Spinner don't support Hint, i recommend you to make a custom spinner adapter.

check this link : https://stackoverflow.com/a/13878692/1725748

How can I delete using INNER JOIN with SQL Server?

Here is my SQL Server version

DECLARE @ProfileId table(Id bigint)

DELETE FROM AspNetUsers
OUTPUT deleted.ProfileId INTO @ProfileId
WHERE Email = @email

DELETE FROM UserProfiles    
WHERE Id = (Select Id FROM @ProfileId)

store and retrieve a class object in shared preference

Do you need to retrieve the object even after the application shutting donw or just during it's running ?

You can store it into a database.
Or Simply create a custom Application class.

public class MyApplication extends Application {

    private static Object mMyObject;
    // static getter & setter
    ...
}

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ... android:name=".MyApplication">
        <activity ... />
        ...
    </application>
    ...
</manifest>

And then from every activities do :

((MyApplication) getApplication).getMyObject();

Not really the best way but it works.

Bootstrap Collapse not Collapsing

You need jQuery see bootstrap's basic template

Root password inside a Docker container

You can log into the Docker container using the root user (ID = 0) instead of the provided default user when you use the -u option. E.g.

docker exec -u 0 -it mycontainer bash

root (id = 0) is the default user within a container. The image developer can create additional users. Those users are accessible by name. When passing a numeric ID, the user does not have to exist in the container.

from Docker documentation

Update: Of course you can also use the Docker management command for containers to run this:

docker container exec -u 0 -it mycontainer bash

A free tool to check C/C++ source code against a set of coding standards?

The only tool I know is Vera. Haven't used it, though, so can't comment how viable it is. Demo looks promising.

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

How can I decrypt a password hash in PHP?

it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX

<?php
error_reporting(0);

# Coded by L0c4lh34rtz - IndoXploit

# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #

$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")

if(isset($argv[1])) {
    foreach($list as $wordlist) {
        print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
    }
} else {
    print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

Mod of negative number is melting my brain

Please note that C# and C++'s % operator is actually NOT a modulo, it's remainder. The formula for modulo that you want, in your case, is:

float nfmod(float a,float b)
{
    return a - b * floor(a / b);
}

You have to recode this in C# (or C++) but this is the way you get modulo and not a remainder.

Asynchronous file upload (AJAX file upload) using jsp and javascript

I don't believe AJAX can handle file uploads but this can be achieved with libraries that leverage flash. Another advantage of the flash implementation is the ability to do multiple files at once (like gmail).

SWFUpload is a good start : http://www.swfupload.org/documentation

jQuery and some of the other libraries have plugins that leverage SWFUpload. On my last project we used SWFUpload and Java without a problem.

Also helpful and worth looking into is Apache's FileUpload : http://commons.apache.org/fileupload/index.html

Django optional url parameters

You can use nested routes

Django <1.8

urlpatterns = patterns(''
    url(r'^project_config/', include(patterns('',
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include(patterns('',
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ))),
    ))),
)

Django >=1.8

urlpatterns = [
    url(r'^project_config/', include([
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include([
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ])),
    ])),
]

This is a lot more DRY (Say you wanted to rename the product kwarg to product_id, you only have to change line 4, and it will affect the below URLs.

Edited for Django 1.8 and above

How can I make a CSS table fit the screen width?

CSS:

table { 
    table-layout:fixed;
}

Update with CSS from the comments:

td { 
    overflow: hidden; 
    text-overflow: ellipsis; 
    word-wrap: break-word;
}

For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):

@media only screen and (max-width: 480px) {
    /* horizontal scrollbar for tables if mobile screen */
    .tablemobile {
        overflow-x: auto;
        display: block;
    }
}

Sufficient enough.

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

Difference between abstraction and encapsulation?

Many answers and their examples are misleading.

Encapsulation is the packing of data and functions operating on that data into a single component and restricting the access to some of the object's components.
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object's definition.

Abstraction is a mechanism which represent the essential features without including implementation details.

Encapsulation:-- Information hiding.
Abstraction:-- Implementation hiding.

Example:

class foo{
    private:
        int a, b;
    public:
        foo(int x=0, int y=0): a(x), b(y) {}

        int add(){    
            return a+b;   
        } 
}  

Internal representation of any object of foo class is hidden outside the class. --> Encapsulation.
Any accessible member (data/function) of an object of foo is restricted and can only be accessed by that object only.

foo foo_obj(3, 4);
int sum = foo_obj.add();

Implementation of method add is hidden. --> Abstraction.

Remove specific commit

Here is an easy solution:

git rebase -i HEAD~x

(Note: x is the number of commits)

upon executing notepad file will open. Enter drop besides your commit.
If you don’t know Vim, just click on each word pick that you want to edit and then hit the "I" key (for insert mode). Once you’re done typing hit the "esc" key to exit insert mode.



enter image description here

and that's it, you are done... Just sync the git dashboard and the changes will be pushed to remote.

If the commit you drop was already on the remote, you will have to force push. Since --force is considered harmful, use git push --force-with-lease.

MongoDB logging all queries

Once profiling level is set using db.setProfilingLevel(2).

The below command will print the last executed query.
You may change the limit(5) as well to see less/more queries.
$nin - will filter out profile and indexes queries
Also, use the query projection {'query':1} for only viewing query field

db.system.profile.find(
{ 
    ns: { 
        $nin : ['meteor.system.profile','meteor.system.indexes']
    }
} 
).limit(5).sort( { ts : -1 } ).pretty()

Logs with only query projection

db.system.profile.find(
{ 
    ns: { 
        $nin : ['meteor.system.profile','meteor.system.indexes']
    }
},
{'query':1}
).limit(5).sort( { ts : -1 } ).pretty()

Found shared references to a collection org.hibernate.HibernateException

I too got the same issue, someone used BeanUtils.copyProperties(source, target). Here both source and target, are using the same collection as attribute.

So i just used the deep copy as below..

How to Clone Collection in Java - Deep copy of ArrayList and HashSet

What is the difference between GitHub and gist?

My personal understanding or to say my personal usage of Gist and Github is:

  • Github

A big project work. If you wanna build website, develop mobile or web application or do your assignment with your teammates of course use github.

  • Gist

more like a memo. for example you can write the implementation of a small feature and share it to your blog or write down what you think about the project and share it with your teammates. Just like what the above answers said, gist is used for more like code snippet thing. So normally if you work on a project you use github.

How to create a localhost server to run an AngularJS project

If you are a java guy simple place your angular folder in web content folder of your web application and deploy to your tomcat server. Super easy !

Python pandas Filtering out nan from a data selection of a column of strings

Simplest of all solutions:

filtered_df = df[df['name'].notnull()]

Thus, it filters out only rows that doesn't have NaN values in 'name' column.

For multiple columns:

filtered_df = df[df[['name', 'country', 'region']].notnull().all(1)]

How do I show my global Git configuration?

To find all configurations, you just write this command:

git config --list

In my local i run this command .

Md Masud@DESKTOP-3HTSDV8 MINGW64 ~
$ git config --list
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
[email protected]
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
filter.lfs.clean=git-lfs clean -- %f

MySQLDump one INSERT statement for each data row

Use:

mysqldump --extended-insert=FALSE 

Be aware that multiple inserts will be slower than one big insert.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Im using IONIC 5.4.13, cordova 9.0.0 ([email protected])

I might be repeating information but for me problem started appearing after adding some plugin (not sure yet). I tried all above combinations, but nothing worked. It only started working after adding:

   <base-config cleartextTrafficPermitted="true">
       <trust-anchors>
           <certificates src="system" />
       </trust-anchors>
   </base-config>

to file in project at

resources/android/xml/network_security_config.xml

so my network_security_config.xml file now looks like:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
   <base-config cleartextTrafficPermitted="true">
       <trust-anchors>
           <certificates src="system" />
       </trust-anchors>
   </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">10.1.25.10</domain>
    </domain-config>
</network-security-config>

Thanks to all.

How do I find the difference between two values without knowing which is larger?

This does not address the original question, but I thought I would expand on the answer zinturs gave. If you would like to determine the appropriately-signed distance between any two numbers, you could use a custom function like this:

import math

def distance(a, b):
    if (a == b):
        return 0
    elif (a < 0) and (b < 0) or (a > 0) and (b > 0):
        if (a < b):
            return (abs(abs(a) - abs(b)))
        else:
            return -(abs(abs(a) - abs(b)))
    else:
        return math.copysign((abs(a) + abs(b)),b)

print(distance(3,-5))  # -8

print(distance(-3,5))  #  8

print(distance(-3,-5)) #  2

print(distance(5,3))   # -2

print(distance(5,5))   #  0

print(distance(-5,3))  #  8

print(distance(5,-3))  # -8

Please share simpler or more pythonic approaches, if you have one.

Github "Updates were rejected because the remote contains work that you do not have locally."

I followed these steps:

Pull the master:

git pull origin master

This will sync your local repo with the Github repo. Add your new file and then:

git add .

Commit the changes:

git commit -m "adding new file  Xyz"

Finally, push the origin master:

git push origin master

Refresh your Github repo, you will see the newly added files.

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

can you try if.else

> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true"  "false"

> cbind(df1$col)
     [,1]   
[1,] "true" 
[2,] "false"
> cbind(df1$col,col2)
             col2
[1,] "true"  "1" 
[2,] "false" "0" 

How to update maven repository in Eclipse?

You can right-click on your project then Maven > Update Project..., then select Force Update of Snapshots/Releases checkbox then click OK.

Multiple arguments to function called by pthread_create()?

I have the same question as the original poster, Michael.

However I have tried to apply the answers submitted for the original code without success

After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.

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

struct arg_struct
{
   int arg1;
   int arg2;
} *args;

void *print_the_arguments(void *arguments)
{
   struct arg_struct *args = arguments;
   printf("Thread\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   pthread_exit(NULL);
   return NULL;
}

int main()
{
   pthread_t some_thread;
   args = malloc(sizeof(struct arg_struct) * 1);

   args->arg1 = 5;
   args->arg2 = 7;

   printf("Before\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   printf("\n");


   if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
   {
      printf("Uh-oh!\n");
      return -1;
   }

   return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}

How to compare two Carbon Timestamps?

This is how I am comparing 2 dates, now() and a date from the table

@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))
    .....
    .....
@endif

Should work just right. I have used the comparison functions provided by Carbon.

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

Could not load file or assembly 'System.Web.Mvc'

I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the steps here.


EDIT: (by jcolebrand) I went through this link, then had the same issue as Victor below, so I suggest you also add these:

* Microsoft.Web.Infrastructure
* System.Web.Razor
* System.Web.WebPages.Deployment
* System.Web.WebPages.Razor

How to get table cells evenly spaced?

I'm also open to suggestion on how to tidy this up, if there are any? :-)

Well, you could not use the span element, for semantic reasons. And you don't have to define the class PerformanceCell. The cells and rows can be accessed by using PerformanceTable tr {} and PerformanceTable tr {}, respectively.

For the spacing part, I have got the same problem several times. I shamefully admit I avoided the problem, so I am very curious to any answers too.

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

WPF: Setting the Width (and Height) as a Percentage Value

I know it's not XAML, but I did the same thing with SizeChanged event of the textbox:

private void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
{
   TextBlock textBlock = sender as TextBlock;
   FrameworkElement element = textBlock.Parent as FrameworkElement;
   textBlock.Margin = new Thickness(0, 0, (element.ActualWidth / 100) * 20, 0);
}

The textbox appears to be 80% size of its parent (well right side margin is 20%) and stretches when needed.

Output an Image in PHP

(Expanding on the accepted answer...)

I needed to:

  1. log views of a jpg image and an animated gif, and,
  2. ensure that the images are never cached (so every view is logged), and,
  3. also retain the original file extensions.

I accomplished this by creating a "secondary" .htaccess file in the sub-folder where the images are located.
The file contains only one line:

AddHandler application/x-httpd-lsphp .jpg .jpeg .gif

In the same folder, I placed the two 'original' image files (we'll call them orig.jpg and orig.gif), as well as two variations of the [simplified] script below (saved as myimage.jpg and myimage.gif)...

<?php 
  error_reporting(0); //hide errors (displaying one would break the image)

  //get user IP and the pseudo-image's URL
  if(isset($_SERVER['REMOTE_ADDR'])) {$ip =$_SERVER['REMOTE_ADDR'];}else{$ip= '(unknown)';}
  if(isset($_SERVER['REQUEST_URI'])) {$url=$_SERVER['REQUEST_URI'];}else{$url='(unknown)';}

  //log the visit
  require_once('connect.php');            //file with db connection info
  $conn = new mysqli($servername, $username, $password, $dbname);
  if (!$conn->connect_error) {         //if connected then save mySQL record
   $conn->query("INSERT INTO imageclicks (image, ip) VALUES ('$url', '$ip');");
     $conn->close();  //(datetime is auto-added to table with default of 'now')
  } 

  //display the image
  $imgfile='orig.jpg';                             // or 'orig.gif'
  header('Content-Type: image/jpeg');              // or 'image/gif'
  header('Content-Length: '.filesize($imgfile));
  header('Cache-Control: no-cache');
  readfile($imgfile);
?>

The images render (or animate) normally and can be called in any of the normal ways for images (like an <img> tag), and will save a record of the visiting IP, while invisible to the user.

Fixed header table with horizontal scrollbar and vertical scrollbar on

Here is a HTML / CSS only solution (with a little javascript).

Apology to answer the question after this long, but the solution given did not suit me and I found a better one. Here is the easiest way to do it with HTML (no jquery):

Before that, the solution fiddle to the question. https://jsfiddle.net/3vzrunkt/

<div>
    <div style="overflow:hidden;;margin-right:16px" id="headerdiv">
        <table id="headertable" style="min-width:900px" border=1>
            <thead>
                <tr>
                    <th style="width:120px;min-width:120px;">One</th>
                    <th style="width:420px;min-width:420px;">Two</th>
                    <th style="width:120px;min-width:120px;">Three</th>
                    <th style="width:120px;min-width:120px;">Four</th>
                    <th style="width:120px;min-width:120px;">Five</th>
                </tr>
            </thead>
        </table>
    </div>

    <div style="overflow-y:scroll;max-height:200px;" 
         onscroll="document.getElementById('headerdiv').scrollLeft = this.scrollLeft;">
        <table id="bodytable" border=1 style="min-width:900px; border:1px solid">
            <tbody>
                <tr>
                    <td style="width:120px;min-width:120px;">body row1</td>
                    <td style="width:420px;min-width:420px;">body row2</td>
                    <td style="width:120px;min-width:120px;">body row2</td>
                    <td style="width:120px;min-width:120px;">body row2</td>
                    <td style="width:120px;min-width:120px;">body row2 en nog meer</td>
                </tr>
                :
                :
                :
                :

            </tbody>
        </table>
    </div>
</div>

And to explain the solution:

  1. you need and enclosing div no overflow/scroll required

  2. a header div containing the header table with overflow:hidden to ensure that the scrollbar is not displayed. Add margin-right:16px to ensure that the scrollbar is left outside it while synching.

  3. another div for containing the table records and overflow-y:scroll. Note the padding is required to get the scrollbar move right of the header.

  4. And the most important thing the magical js to sync the header and table data:

     onscroll="document.getElementById('headerdiv').scrollLeft = this.scrollLeft;"
    

converting list to json format - quick and easy way

You could return the value using return JsonConvert.SerializeObject(objName); And send it to the front end

Early exit from function?

Using a return will stop the function and return undefined, or the value that you specify with the return command.

function myfunction(){
    if(a=="stop"){
        //return undefined;
        return; /** Or return "Hello" or any other value */
    }
}

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

You can use the following time conversion within SQL like this:

--Convert Time to Integer (Minutes)
DECLARE @timeNow datetime = '14:47'
SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108))

--Convert Minutes to Time
DECLARE @intTime int = (SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108)))
SELECT DATEADD(minute, @intTime, '')

Result: 887 <- Time in minutes and 1900-01-01 14:47:00.000 <-- Minutes to time

How does Git handle symbolic links?

Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.

When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.

If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.

In Maven how to exclude resources from the generated jar?

Exclude specific pattern of file during creation of maven jar using maven-jar-plugin.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <version>2.3</version>
  <configuration>
    <excludes>
      <exclude>**/*.properties</exclude>
      <exclude>**/*.xml</exclude>
      <exclude>**/*.exe</exclude>
      <exclude>**/*.java</exclude>
      <exclude>**/*.xls</exclude>
    </excludes>
  </configuration>
</plugin>

Creating a custom JButton in Java

You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:

try {
    SynthLookAndFeel synth = new SynthLookAndFeel();
    Class aClass = MainFrame.class;
    InputStream stream = aClass.getResourceAsStream("\\default.xml");

    if (stream == null) {
        System.err.println("Missing configuration file");
        System.exit(-1);                
    }

    synth.load(stream, aClass);

    UIManager.setLookAndFeel(synth);
} catch (ParseException pe) {
    System.err.println("Bad configuration file");
    pe.printStackTrace();
    System.exit(-2);
} catch (UnsupportedLookAndFeelException ulfe) {
    System.err.println("Old JRE in use. Get a new one");
    System.exit(-3);
}

From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.

The xml file might look like this:

<synth>
    <style id="button">
        <font name="DIALOG" size="12" style="BOLD"/>
        <state value="MOUSE_OVER">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
        <state value="ENABLED">
            <imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
            <insets top="2" botton="2" right="2" left="2"/>
        </state>
    </style>
    <bind style="button" type="name" key="dirt"/>
</synth>

The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to "dirt").

And a couple of useful links:

http://javadesktop.org/articles/synth/

http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html

Select folder dialog WPF

MVVM + WinForms FolderBrowserDialog as behavior

public class FolderDialogBehavior : Behavior<Button>
{
    public string SetterName { get; set; }

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Click += OnClick;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Click -= OnClick;
    }

    private void OnClick(object sender, RoutedEventArgs e)
    {
        var dialog = new FolderBrowserDialog();
        var result = dialog.ShowDialog();
        if (result == DialogResult.OK && AssociatedObject.DataContext != null)
        {
            var propertyInfo = AssociatedObject.DataContext.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Where(p => p.CanRead && p.CanWrite)
            .Where(p => p.Name.Equals(SetterName))
            .First();

            propertyInfo.SetValue(AssociatedObject.DataContext, dialog.SelectedPath, null);
        }
    }
}

Usage

     <Button Grid.Column="3" Content="...">
            <Interactivity:Interaction.Behaviors>
                <Behavior:FolderDialogBehavior SetterName="SomeFolderPathPropertyName"/>
            </Interactivity:Interaction.Behaviors>
     </Button>

Blogpost: http://kostylizm.blogspot.ru/2014/03/wpf-mvvm-and-winforms-folder-dialog-how.html

Ignore 'Security Warning' running script from command line

To avoid warnings, you can:

Set-ExecutionPolicy bypass

Resetting Select2 value in dropdown with reset button

I'd try something like this:

$(function(){
    $("#searchclear").click(function(){
        $("#d").select2('val', 'All');
    });
});

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

How to use php serialize() and unserialize()

From http://php.net/manual/en/function.serialize.php :

Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).

Unserialize is used to convert the string back to an object.

How to delete selected text in the vi editor

If you want to remove all lines in a file from your current line number, use dG, it will delete all lines (shift g) mean end of file

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Allowed characters in filename

Here is the code to clean file name in python.

import unicodedata

def clean_name(name, replace_space_with=None):
    """
    Remove invalid file name chars from the specified name

    :param name: the file name
    :param replace_space_with: if not none replace space with this string
    :return: a valid name for Win/Mac/Linux
    """

    # ref: https://en.wikipedia.org/wiki/Filename
    # ref: https://stackoverflow.com/questions/4814040/allowed-characters-in-filename
    # No control chars, no: /, \, ?, %, *, :, |, ", <, >

    # remove control chars
    name = ''.join(ch for ch in name if unicodedata.category(ch)[0] != 'C')

    cleaned_name = re.sub(r'[/\\?%*:|"<>]', '', name)
    if replace_space_with is not None:
        return cleaned_name.replace(' ', replace_space_with)
    return cleaned_name

Get DataKey values in GridView RowCommand

foreach (GridViewRow gvr in gvMyGridView.Rows)
{
    string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}

You can use this code while doing an iteration with foreach or for any GridView event like OnRowDataBound.

Here you can input multiple values for DataKeyNames by separating with comma ,. For example, DataKeyNames="ProductID,ItemID,OrderID".

You can now access each of DataKeys by providing its index like below:

string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();

You can also use Key Name instead of its index to get the values from DataKeyNames collection like below:

string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();

Completely cancel a rebase

Use git rebase --abort. From the official Linux kernel documentation for git rebase:

git rebase --continue | --skip | --abort | --edit-todo

LINUX: Link all files from one to another directory

GNU cp has an option to create symlinks instead of copying.

cp -rs /mnt/usr/lib /usr/

Note this is a GNU extension not found in POSIX cp.

Git submodule update

To address the --rebase vs. --merge option:

Let's say you have super repository A and submodule B and want to do some work in submodule B. You've done your homework and know that after calling

git submodule update

you are in a HEAD-less state, so any commits you do at this point are hard to get back to. So, you've started work on a new branch in submodule B

cd B
git checkout -b bestIdeaForBEver
<do work>

Meanwhile, someone else in project A has decided that the latest and greatest version of B is really what A deserves. You, out of habit, merge the most recent changes down and update your submodules.

<in A>
git merge develop
git submodule update

Oh noes! You're back in a headless state again, probably because B is now pointing to the SHA associated with B's new tip, or some other commit. If only you had:

git merge develop
git submodule update --rebase

Fast-forwarded bestIdeaForBEver to b798edfdsf1191f8b140ea325685c4da19a9d437.
Submodule path 'B': rebased into 'b798ecsdf71191f8b140ea325685c4da19a9d437'

Now that best idea ever for B has been rebased onto the new commit, and more importantly, you are still on your development branch for B, not in a headless state!

(The --merge will merge changes from beforeUpdateSHA to afterUpdateSHA into your working branch, as opposed to rebasing your changes onto afterUpdateSHA.)

How to get the Mongo database specified in connection string in C#

The answer below is apparently obsolete now, but works with older drivers. See comments.

If you have the connection string you could also use MongoDatabase directly:

var db =  MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

This error tells you that you do not have the razor engine properly associated with your project.

Solution: In the Solution Explorer window right click on your web project and select "Manage Nuget Packages..." then install "Microsoft ASP.NET Razor". This will make sure that the properly package is installed and it will add the necessary entries into your web.config file.

android : Error converting byte to dex

For some reasons, @ChintanSoni's answer didn't worked. I tried deleting the build folder manually but couldn't delete some files since they were being used by some process. Cleaning and re-building the project didn't help so I opened task manager, selected JAVA(TM) Platform SE binary and pressed on 'End task`.

Then I tried to run the project once again and it started compiling fine.

How to get the second column from command output?

Or use sed & regex.

<some_command> | sed 's/^.* \(".*"$\)/\1/'

Trying to handle "back" navigation button action in iOS

Set the UINavigationControllerDelegate and implement this delegate func (Swift):

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    if viewController is <target class> {
        //if the only way to get back - back button was pressed
    }
}

How do I use the Simple HTTP client in Android?

public static void connect(String url)
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }


    } catch (Exception e) {}
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

Code coverage for Jest built on top of Jasmine

If you are using the NestJS framework, you can get code coverage using this command:

npm run test:cov

How do I stretch a background image to cover the entire HTML element?

In short you can try this....

<div data-role="page" style="background:url('backgrnd.png'); background-repeat: no-repeat; background-size: 100% 100%;" >

Where I have used few css and js...

<link rel="stylesheet" href="css/jquery.mobile-1.0.1.min.css" />
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery.mobile-1.0.1.min.js"></script>

And it is working fine for me.

Excel VBA code to copy a specific string to clipboard

If the place you're gonna paste have no problem with pasting a table formating (like the browser URL bar), I think the easiest way is this:

Sheets(1).Range("A1000").Value = string
Sheets(1).Range("A1000").Copy
MsgBox "Paste before closing this dialog."
Sheets(1).Range("A1000").Value = ""

ASP.Net MVC - Read File from HttpPostedFileBase without save

This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here

You should convert the stream into byte array and then you can read file content

Please refer following link

http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]

Hope this helps

UPDATE :

The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.

Taken from here

// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);

string result = System.Text.Encoding.UTF8.GetString(binData);