Programs & Examples On #Wimpy

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

Get DOM content of cross-domain iframe

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

How to store an array into mysql?

You can use the php serialize function to store array in MySQL.

<?php

$array = array("Name"=>"Shubham","Age"=>"17","website"=>"http://mycodingtricks.com");

$string_array = serialize($array);

echo $string_array;

?>

It’s output will be :

a:3{s:4:"Name";s:7:"Shubham";s:3:"Age";s:2:"17";s:7:"website";s:25:"http://mycodingtricks.com";}

And then you can use the php unserialize function to decode the data.

I think you should visit this page on storing array in mysql.

How to reload or re-render the entire page using AngularJS

Use the following code without intimate reload notification to the user. It will render the page

var currentPageTemplate = $route.current.templateUrl;
$templateCache.remove(currentPageTemplate);
$window.location.reload();

How can I set my Cygwin PATH to find javac?

Java binaries may be under "Program Files" or "Program Files (x86)": those white spaces will likely affect the behaviour.

In order to set up env variables correctly, I suggest gathering some info before starting:

  • Open DOS shell (type cmd into 'RUN' box) go to C:\
  • type "dir /x" and take note of DOS names (with ~) for "Program Files *" folders

Cygwin configuration:

go under C:\cygwin\home\, then open .bash_profile and add the following two lines (conveniently customized in order to match you actual JDK path)

export JAVA_HOME="/cygdrive/c/PROGRA~1/Java/jdk1.8.0_65"
export PATH="$JAVA_HOME/bin:$PATH"

Now from Cygwin launch

javac -version

to check if the configuration is successful.

how does array[100] = {0} set the entire array to 0?

If your compiler is GCC you can also use following syntax:

int array[256] = {[0 ... 255] = 0};

Please look at http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html#Designated-Inits, and note that this is a compiler-specific feature.

How to change the text of a label?

I just went through this myself and found the solution. See an ASP.NET label server control actually gets redered as a span (not an input), so using the .val() property to get/set will not work. Instead you must use the 'text' property on the span in conjuntion with using the controls .ClientID property. The following code will work:

$("#<%=lblVessel.ClientID %>").text('NewText');

Jquery open popup on button click for bootstrap

Give an ID to uniquely identify the button, lets say myBtn

// when DOM is ready
$(document).ready(function () {

     // Attach Button click event listener 
    $("#myBtn").click(function(){

         // show Modal
         $('#myModal').modal('show');
    });
});

JSFIDDLE

Get a random boolean in python?

Adam's answer is quite fast, but I found that random.getrandbits(1) to be quite a lot faster. If you really want a boolean instead of a long then

bool(random.getrandbits(1))

is still about twice as fast as random.choice([True, False])

Both solutions need to import random

If utmost speed isn't to priority then random.choice definitely reads better

$ python -m timeit -s "import random" "random.choice([True, False])"
1000000 loops, best of 3: 0.904 usec per loop
$ python -m timeit -s "import random" "random.choice((True, False))" 
1000000 loops, best of 3: 0.846 usec per loop
$ python -m timeit -s "import random" "random.getrandbits(1)"
1000000 loops, best of 3: 0.286 usec per loop
$ python -m timeit -s "import random" "bool(random.getrandbits(1))"
1000000 loops, best of 3: 0.441 usec per loop
$ python -m timeit -s "import random" "not random.getrandbits(1)"
1000000 loops, best of 3: 0.308 usec per loop
$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
1000000 loops, best of 3: 0.262 usec per loop  # not takes about 20us of this

Added this one after seeing @Pavel's answer

$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.115 usec per loop

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

I had the same issue using Windows, got if fixed by opening it in Notepad++ and changing the encoding from "UCS-2 LE BOM" to "UTF-8".

fail to change placeholder color with Bootstrap 3

Assign the placeholder to a class selector like this:

.form-control::-webkit-input-placeholder { color: white; }  /* WebKit, Blink, Edge */
.form-control:-moz-placeholder { color: white; }  /* Mozilla Firefox 4 to 18 */
.form-control::-moz-placeholder { color: white; }  /* Mozilla Firefox 19+ */
.form-control:-ms-input-placeholder { color: white; }  /* Internet Explorer 10-11 */
.form-control::-ms-input-placeholder { color: white; }  /* Microsoft Edge */

It will work then since a stronger selector was probably overriding your global. I'm on a tablet so i cant inspect and confirm which stronger selector it was :) But it does work I tried it in your fiddle.

This also answers your second question. By assigning it to a class or id and giving an input only that class you can control what inputs to style.

Select distinct rows from datatable in Linq

If it's not a typed dataset, then you probably want to do something like this, using the Linq-to-DataSet extension methods:

var distinctValues = dsValues.AsEnumerable()
                        .Select(row => new {
                            attribute1_name = row.Field<string>("attribute1_name"),
                            attribute2_name = row.Field<string>("attribute2_name")
                         })
                        .Distinct();

Make sure you have a using System.Data; statement at the beginning of your code in order to enable the Linq-to-Dataset extension methods.

Hope this helps!

How to disable mouse right click on a web page?

You can use the oncontextmenu event for doing this.

But if the user turns off javascript then you won't be able to handle this.

window.oncontextmenu = function () {
   return false;
}

will disable right click menu.

Row count where data exists

This works for me. Returns the number that Excel displays in the bottom status line when a pivot column is filtered and I need the count of the visible cells.

Global Const DashBoardSheet = "DashBoard"
Global Const ProfileColRng = "$L:$L"
.
.
.
Sub MySub()
Dim myreccnt as long
.
.
.
myreccnt = GetFilteredPivotRowCount(DashBoardSheet, ProfileColRng)
.
.
.
End Sub

Function GetFilteredPivotRowCount(sheetname As String, cntrange As String) As long

Dim reccnt As Long

reccnt = Sheets(sheetname).Range(cntrange).SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count - 1

GetFilteredPivotRowCount = reccnt

End Function

Store JSON object in data attribute in HTML jQuery

For me it work like that, as I need to store it in template...

// Generate HTML
var gridHtml = '<div data-dataObj=\''+JSON.stringify(dataObj).replace(/'/g, "\\'");+'\'></div>';

// Later
var dataObj = $('div').data('dataObj'); // jQuery automatically unescape it

Check if application is installed - Android

Those who are looking for Kotlin solution can use this method,

Here I have shared full code, and also handled enabled status. Check If Application is Installed in Android Kotlin

fun isAppInstalled(packageName: String, context: Context): Boolean {
        return try {
            val packageManager = context.packageManager
            packageManager.getPackageInfo(packageName, 0)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }

Define: What is a HashSet?

A HashSet has an internal structure (hash), where items can be searched and identified quickly. The downside is that iterating through a HashSet (or getting an item by index) is rather slow.

So why would someone want be able to know if an entry already exists in a set?

One situation where a HashSet is useful is in getting distinct values from a list where duplicates may exist. Once an item is added to the HashSet it is quick to determine if the item exists (Contains operator).

Other advantages of the HashSet are the Set operations: IntersectWith, IsSubsetOf, IsSupersetOf, Overlaps, SymmetricExceptWith, UnionWith.

If you are familiar with the object constraint language then you will identify these set operations. You will also see that it is one step closer to an implementation of executable UML.

Finding child element of parent pure javascript

The children property returns an array of elements, like so:

parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]

There are alternatives to querySelector, like document.getElementsByClassName('parent')[0] if you so desire.


Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

children = document.querySelectorAll('.parent .child1');

The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

  1. Open the xampp/php/php.ini file in any editor
  2. Search ";extension=php_intl.dll"
  3. Remove the starting semicolon ( ; )

    Like: ;extension=php_intl.dll to extension=php_intl.dll

This helped me.

Spring Boot without the web server

The simplest solution. in your application.properties file. add the following property as mentioned by a previous answer:

spring.main.web-environment=false

For version 2.0.0 of Spring boot starter, use the following property :

spring.main.web-application-type=none

For documentation on all properties use this link : https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

How to use vagrant in a proxy environment?

On a Windows host

open a CMD prompt;

set HTTP_PROXY=http://proxy.yourcorp.com:80
set HTTPS_PROXY=https://proxy.yourcorp.com:443

Substitute the address and port in the above snippets to whatever is appropriate for your situation. The above will remain set until you close the CMD prompt. If it works for you, consider adding them permanently to your environment variables so that you won't have to set them every time you open a new CMD prompt.

Increasing Google Chrome's max-connections-per-server limit to more than 6

IE is even worse with 2 connection per domain limit. But I wouldn't rely on fixing client browsers. Even if you have control over them, browsers like chrome will auto update and a future release might behave differently than you expect. I'd focus on solving the problem within your system design.

Your choices are to:

  1. Load the images in sequence so that only 1 or 2 XHR calls are active at a time (use the success event from the previous image to check if there are more images to download and start the next request).

  2. Use sub-domains like serverA.myphotoserver.com and serverB.myphotoserver.com. Each sub domain will have its own pool for connection limits. This means you could have 2 requests going to 5 different sub-domains if you wanted to. The downfall is that the photos will be cached according to these sub-domains. BTW, these don't need to be "mirror" domains, you can just make additional DNS pointers to the exact same website/server. This means you don't have the headache of administrating many servers, just one server with many DNS records.

How can I stop the browser back button using JavaScript?

I had this problem with React (class component).

And I solved it easily:

componentDidMount() {
    window.addEventListener("popstate", e => {
        this.props.history.goForward();
    }
}

I've used HashRouter from react-router-dom.

count (non-blank) lines-of-code in bash

cat foo.c | sed '/^\s*$/d' | wc -l

And if you consider comments blank lines:

cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l

Although, that's language dependent.

ASP.NET Core Identity - get current user

Just if any one is interested this worked for me. I have a custom Identity which uses int for a primary key so I overrode the GetUserAsync method

Override GetUserAsync

public override Task<User> GetUserAsync(ClaimsPrincipal principal)
{
    var userId = GetUserId(principal);
    return FindByNameAsync(userId);
}

Get Identity User

var user = await _userManager.GetUserAsync(User);

If you are using a regular Guid primary key you don't need to override GetUserAsync. This is all assuming that you token is configured correctly.

public async Task<string> GenerateTokenAsync(string email)
{
    var user = await _userManager.FindByEmailAsync(email);
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_tokenProviderOptions.SecretKey);

    var userRoles = await _userManager.GetRolesAsync(user);
    var roles = userRoles.Select(o => new Claim(ClaimTypes.Role, o));

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture)),
        new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
        new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
        new Claim(JwtRegisteredClaimNames.Email, user.Email),
    }
    .Union(roles);

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(claims),
        Expires = DateTime.UtcNow.AddHours(_tokenProviderOptions.Expires),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);

    return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token)).Result;
}

How to detect the screen resolution with JavaScript?

just for future reference:

function getscreenresolution()
{
    window.alert("Your screen resolution is: " + screen.height + 'x' + screen.width);
}

Best way to copy from one array to another

There are lots of solutions:

b = Arrays.copyOf(a, a.length);

Which allocates a new array, copies over the elements of a, and returns the new array.

Or

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

Which copies the source array content into a destination array that you allocate yourself.

Or

b = a.clone();

which works very much like Arrays.copyOf(). See this thread.

Or the one you posted, if you reverse the direction of the assignment in the loop:

b[i] = a[i]; // NOT a[i] = b[i];

Detecting a redirect in ajax request?

You can now use fetch API/ It returns redirected: *boolean*

Why is setState in reactjs Async instead of Sync?

setState is asynchronous. You can see in this documentation by Reactjs

React intentionally “waits” until all components call setState() in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.

However, you might still be wondering why React doesn’t just update this.state immediately without re-rendering.

The reason is this would break the consistency between props and state, causing issues that are very hard to debug.

You can still perform functions if it is dependent on the change of the state value:

Option 1: Using callback function with setState

this.setState({
   value: newValue
},()=>{
   // It is an callback function.
   // Here you can access the update value
   console.log(this.state.value)
})

Option 2: using componentDidUpdate This function will be called whenever the state of that particular class changes.

componentDidUpdate(prevProps, prevState){
    //Here you can check if value of your desired variable is same or not.
    if(this.state.value !== prevState.value){
        // this part will execute if your desired variable updates
    }
}

What's a good IDE for Python on Mac OS X?

"Which editor/IDE for ...?" is a longstanding way to start a "My dog is too prettier than yours!" slapfest. Nowadays most editors from vim upwards can be used, there are multiple good alternatives, and even IDEs that started as C or Java tools work pretty well with Python and other dynamic languages.

That said, having tried a bunch of IDEs (Eclipse, NetBeans, XCode, Komodo, PyCharm, ...), I am a fan of ActiveState's Komodo IDE. I use it on Mac OS X primarily, though I've used it for years on Windows as well. The one license follows you to any platform.

Komodo is well-integrated with popular ActiveState builds of the languages themselves (esp. for Windows), works well with the fabulous (and Pythonic) Mercurial change management system (among others), and has good-to-excellent abilities for core tasks like code editing, syntax coloring, code completion, real-time syntax checking, and visual debugging. It is a little weak when it comes to pre-integrated refactoring and code-check tools (e.g. rope, pylint), but it is extensible and has a good facility for integrating external and custom tools.

Some of the things I like about Komodo go beyond the write-run-debug loop. ActiveState has long supported the development community (e.g. with free language builds, package repositories, a recipes site, ...), since before dynamic languages were the trend. The base Komodo Edit editor is free and open source, an extension of Mozilla's Firefox technologies. And Komodo is multi-lingual. I never end up doing just Python, just Perl, or just whatever. Komodo works with the core language (Python, Perl, Ruby, PHP, JavaScript) alongside supporting languages (XML, XSLT, SQL, X/HTML, CSS), non-dynamic languages (Java, C, etc.), and helpers (Makefiles, INI and config files, shell scripts, custom little languages, etc.) Others can do that too, but Komodo puts them all in once place, ready to go. It's a Swiss Army Knife for dynamic languages. (This is contra PyCharm, e.g., which is great itself, but I'd need like a half-dozen of JetBrains' individual IDEs to cover all the things I do).

Komodo IDE is by no means perfect, and editors/IDEs are the ultimate YMMV choice. But I am regularly delighted to use it, and every year I re-up my support subscription quite happily. Indeed, I just remembered! That's coming up this month. Credit card: Out. I have no commercial connection to ActiveState--just a happy customer.

php $_POST array empty upon form submission

In addition to MRMage's post:

I had to set this variable to solve the problem that some $_POST variables (with an large array > 1000 items) disappeared:

suhosin.request.max_vars = 2500

"request", not "post" was the solution...

Maven version with a property

I have two recommendation for you

  1. Use CI Friendly Revision for all your artifacts. You can add -Drevision=2.0.1 in .mvn/maven.config file. So basically you define your version only at one location.
  2. For all external dependency create a property in parent file. You can use Apache Camel Parent Pom as reference

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

Proxy Basic Authentication in C#: HTTP 407 error

You can use like this, it works!

        WebProxy proxy = new WebProxy
        {
            Address = new Uri(""),
            Credentials = new NetworkCredential("", "")
        };

        HttpClientHandler httpClientHandler = new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true
        };

        HttpClient client = new HttpClient(httpClientHandler);

        HttpResponseMessage response = await client.PostAsync("...");

How to change line color in EditText

This is the best tool that you can use for all views and its FREE many thanks to @Jérôme Van Der Linden.

The Android Holo Colors Generator allows you to easily create Android components such as EditText or spinner with your own colours for your Android application. It will generate all necessary nine patch assets plus associated XML drawable and styles which you can copy straight into your project.

http://android-holo-colors.com/

UPDATE 1

This domain seems expired but the project is an open source you can find here

https://github.com/jeromevdl/android-holo-colors

try it

this image put in the background of EditText

android:background="@drawable/textfield_activated"

enter image description here


UPDATE 2

For API 21 or higher, you can use android:backgroundTint

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Underline color change"
        android:backgroundTint="@android:color/holo_red_light" />

Update 3 Now We have with back support AppCompatEditText

Note: We need to use app:backgroundTint instead of android:backgroundTint

<android.support.v7.widget.AppCompatEditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:hint="Underline color change"
    app:backgroundTint="@color/blue_gray_light" />

Update 4 AndroidX version

  <androidx.appcompat.widget.AppCompatEditText

    app:backgroundTint="@color/blue_gray_light" />

Css height in percent not working

Make it 100% of the viewport height:

div {
  height: 100vh;
}

Works in all modern browsers and IE>=9, see here for more info.

How to parse freeform street/postal address out of text, and into components

libpostal: an open-source library to parse addresses, training with data from OpenStreetMap, OpenAddresses and OpenCage.

https://github.com/openvenues/libpostal (more info about it)

Other tools/services:

Java converting int to hex and back again

Java's parseInt method is actally a bunch of code eating "false" hex : if you want to translate -32768, you should convert the absolute value into hex, then prepend the string with '-'.

There is a sample of Integer.java file :

public static int parseInt(String s, int radix)

The description is quite explicit :

* Parses the string argument as a signed integer in the radix 
* specified by the second argument. The characters in the string 
...
...
* parseInt("0", 10) returns 0
* parseInt("473", 10) returns 473
* parseInt("-0", 10) returns 0
* parseInt("-FF", 16) returns -255

How to validate an email address in JavaScript

Here is a function I use for front end email validation. (The Regular Expression came from parsley.js)

<!DOCTYPE html>
<html>
<head>
    <title>Our Company</title>
    <style>
        .form-style {
            color: #ccc;
        }
    </style>
</head>
<body>
    <h1>Email Validation Form Example</h1>
    <input type="text" name="email" id="emailInput" class="form-style">
    <script>
        function validateEmail(emailAddress) {
            var regularExpression = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))){2,6}$/i;
             return regularExpression.test(emailAddress);
        }

        function showEmailValidationState(event) {
            if (validateEmail(event.target.value)) {
                document.getElementById("emailInput").style.color = 'black';
            }
        }
    document.getElementById("emailInput").addEventListener("keyup", showEmailValidationState);
    </script>
</body>
</html>

Compare object instances for equality by their attributes

If you want to get an attribute-by-attribute comparison, and see if and where it fails, you can use the following list comprehension:

[i for i,j in 
 zip([getattr(obj_1, attr) for attr in dir(obj_1)],
     [getattr(obj_2, attr) for attr in dir(obj_2)]) 
 if not i==j]

The extra advantage here is that you can squeeze it one line and enter in the "Evaluate Expression" window when debugging in PyCharm.

SQLite3 database or disk is full / the database disk image is malformed

I have seen this happen when the database gets corrupted, have you tried cloning it into a new one ?

Safley copy a s SQLite db

Safely copy a SQLite database

It's trivially easy to copy a SQLite database. It's less trivial to do this in a way that won't corrupt it. Here's how:

shell$ sqlite3 some.db
sqlite> begin immediate;
<press CTRL+Z>
shell$ cp some.db some.db.backup
shell$ exit
sqlite> rollback;

This will give you a nice clean backup that's sure to be in a proper state, since writing to the database half-way through your copying process is impossible.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

Get table names using SELECT statement in MySQL

This below query worked for me. This can able to show the databases,tables,column names,data types and columns count.

**select table_schema Schema_Name ,table_name TableName,column_name ColumnName,ordinal_position "Position",column_type DataType,COUNT(1) ColumnCount
FROM information_schema.columns
GROUP by table_schema,table_name,column_name,ordinal_position, column_type;**

Pretty-Printing JSON with PHP

If you used only $json_string = json_encode($data, JSON_PRETTY_PRINT);, you will get in the browser something like this (using the Facebook link from the question :) ): enter image description here

but if you used a chrome Extension like JSONView (even without the PHP option above), then you get a more pretty readable debuggable solution where you can even Fold/Collapse each single JSON object easily like this: enter image description here

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

Size-limited queue that holds last N elements in Java

Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.

I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):

public LimitedSizeQueue implements Queue
{
  private int maxSize;
  private LinkedList storageArea;

  public LimitedSizeQueue(final int maxSize)
  {
    this.maxSize = maxSize;
    storageArea = new LinkedList();
  }

  public boolean offer(ElementType element)
  {
    if (storageArea.size() < maxSize)
    {
      storageArea.addFirst(element);
    }
    else
    {
      ... remove last element;
      storageArea.addFirst(element);
    }
  }

  ... the rest of this class

A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:

public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
    private int maxSize;
    private CircularFifoBuffer storageArea;

    public LimitedSizeQueue(final int maxSize)
    {
        if (maxSize > 0)
        {
            this.maxSize = maxSize;
            storateArea = new CircularFifoBuffer(maxSize);
        }
        else
        {
            throw new IllegalArgumentException("blah blah blah");
        }
    }

    ... implement the Queue interface using the CircularFifoBuffer class
}

How to change the icon of an Android app in Eclipse?

You can find an easy guide here

The step are 2: - Copy the icon in the correct folder/folders - Change the AndroidManifest.xml

Check file size before upload

JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.

append multiple values for one key in a dictionary

Here is an alternative way of doing this using the not in operator:

# define an empty dict
years_dict = dict()

for line in list:
    # here define what key is, for example,
    key = line[0]
    # check if key is already present in dict
    if key not in years_dict:
        years_dict[key] = []
    # append some value 
    years_dict[key].append(some.value)

Using SQL LIKE and IN together

Use the longer version of IN which is a bunch of OR.

SELECT * FROM tablename 
WHERE column LIKE 'M510%'
OR column LIKE 'M615%'
OR column LIKE 'M515%'
OR column LIKE 'M612%';

What is the usefulness of PUT and DELETE HTTP request methods?

Although I take the risk of not being popular I say they are not useful nowadays.

I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.

Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.

Let's take an example:

  • /api/entity/list/{id} vs GET /api/entity/{id}
  • /api/entity/add/{id} vs POST /api/entity
  • /api/entity/edit/{id} vs PUT /api/entity/{id}
  • /api/entity/delete/{id} vs DELETE /api/entity/{id}

On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.

Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.

In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.

Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards

Assets file project.assets.json not found. Run a NuGet package restore

Another one, if by any chance you're using Dropbox, check for Conflicted in file names, do a search in your repo and delete all those conflicted files.

This may have happened if you have moved the files around.

Android Fragment no view found for ID?

use childFragmentManager instead of activity!!.supportFragmentManager

Binding List<T> to DataGridView in WinForm

After adding new item to persons add:

myGrid.DataSource = null;
myGrid.DataSource = persons;

Functions that return a function

Returning b is returning a function object. In Javascript, functions are just objects, like any other object. If you find that not helpful, just replace the word "object" with "thing". You can return any object from a function. You can return a true/false value. An integer (1,2,3,4...). You can return a string. You can return a complex object with multiple properties. And you can return a function. a function is just a thing.

In your case, returning b returns the thing, the thing is a callable function. Returning b() returns the value returned by the callable function.

Consider this code:

function b() {
   return 42;
}

Using the above definition, return b(); returns the value 42. On the other hand return b; returns a function, that itself returns the value of 42. They are two different things.

How do I convert seconds to hours, minutes and seconds?

I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:

from time import strftime
from time import gmtime

strftime("%H:%M:%S", gmtime(666))
'00:11:06'

strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'

gmtime is used to convert seconds to special tuple format that strftime() requires.

Note: Truncates after 23:59:59

How to align an input tag to the center without specifying the width?

you can use this two simple line code :

_x000D_
_x000D_
    display: block;
    margin:auto;
_x000D_
_x000D_
_x000D_

How do I download a file using VBA (without Internet Explorer)

This solution is based from this website: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

It is slightly modified to overwrite existing file and to pass along login credentials.

Sub DownloadFile()

Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send

If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

End Sub

How to remove selected commit log entries from a Git repository while keeping their changes?

Just collected all people's answers:(m new to git plz use it for reference only)

git rebase to delete any commits

git log

-first check from which commit you want to rebase

git rebase -i HEAD~1

-Here i want to rebase on the second last commit- commit count starts from '1')
-this will open the command line editor (called vim editor i guess)

Then the screen will look something like this:

pick 0c2236d Added new line.

Rebase 2a1cd65..0c2236d onto 2a1cd65 (1 command)

#

Commands:

p, pick = use commit

r, reword = use commit, but edit the commit message

e, edit = use commit, but stop for amending

s, squash = use commit, but meld into previous commit

f, fixup = like "squash", but discard this commit's log message

x, exec = run command (the rest of the line) using shell

d, drop = remove commit

#

These lines can be re-ordered; they are executed from top to bottom.

#

If you remove a line here THAT COMMIT WILL BE LOST.

#

However, if you remove everything, the rebase will be aborted.

#

Note that empty commits are commented out ~ ~

~
~
~
~
~
~
~
~
~

Here change the first line as per your need (using the commands listed above i.e. 'drop' to remove commit etc.) Once done the editing press ':x' to save and exit editor(this is for vim editor only)

And then

git push

If its showing problem then you need to forcefully push the changes to remote(ITS VERY CRITICAL : dont force push if you are working in team)

git push -f origin

Using Sockets to send and receive data

I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream:

Client:

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

Server:

Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());

boolean done = false;
while(!done) {
  byte messageType = dIn.readByte();

  switch(messageType)
  {
  case 1: // Type A
    System.out.println("Message A: " + dIn.readUTF());
    break;
  case 2: // Type B
    System.out.println("Message B: " + dIn.readUTF());
    break;
  case 3: // Type C
    System.out.println("Message C [1]: " + dIn.readUTF());
    System.out.println("Message C [2]: " + dIn.readUTF());
    break;
  default:
    done = true;
  }
}

dIn.close();

Obviously, you can send all kinds of data, not just bytes and strings (UTF).

Note that writeUTF writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535 bytes to send. This makes it possible for readUTF to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.

Warning: implode() [function.implode]: Invalid arguments passed

You are getting the error because $ret is not an array.

To get rid of the error, at the start of your function, define it with this line: $ret = array();

It appears that the get_tags() call is returning nothing, so the foreach is not run, which means that $ret isn't defined.

Illegal pattern character 'T' when parsing a date string to java.util.Date

There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:

import java.time.Instant;
public static void main(String[] args) {
    String date="2010-10-02T12:23:23Z";
    try {
        Instant myDate = Instant.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant directly, can be done via Calendar in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:

myDate.toString().substring(0,4);

How do I break out of nested loops in Java?

As most of the answers are suggesting to use the labels or return. The problem with labels is that it is not considered good practice in the industry because labels make your code difficult to read for other programmers. As for the return statement answers, The code example in the question is not inside some method. As the return statement will end the method and hence the loop will be broken with it. But that is not breaking off the loop that is ending the function. As, for the specific code example, this would be the good solution:

boolean endNestedLoop=false;

for (Type type : types) {

for (Type t : types2) {

if (some condition) {

endNestedLoop=true;

// Do something and break...

break; // Breaks out of the inner loop

}

if(endNestLoop)

break;

}

}

This way code is easy to read.

How can I check if my Element ID has focus?

Compare document.activeElement with the element you want to check for focus. If they are the same, the element is focused; otherwise, it isn't.

// dummy element
var dummyEl = document.getElementById('myID');

// check for focus
var isFocused = (document.activeElement === dummyEl);

hasFocus is part of the document; there's no such method for DOM elements.

Also, document.getElementById doesn't use a # at the beginning of myID. Change this:

var dummyEl = document.getElementById('#myID');

to this:

var dummyEl = document.getElementById('myID');

If you'd like to use a CSS query instead you can use querySelector (and querySelectorAll).

Detect click outside Angular component

Binding to document click through @Hostlistener is costly. It can and will have a visible performance impact if you overuse(for example, when building a custom dropdown component and you have multiple instances created in a form).

I suggest adding a @Hostlistener() to the document click event only once inside your main app component. The event should push the value of the clicked target element inside a public subject stored in a global utility service.

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {

  constructor(private utilitiesService: UtilitiesService) {}

  @HostListener('document:click', ['$event'])
  documentClick(event: any): void {
    this.utilitiesService.documentClickedTarget.next(event.target)
  }
}

@Injectable({ providedIn: 'root' })
export class UtilitiesService {
   documentClickedTarget: Subject<HTMLElement> = new Subject<HTMLElement>()
}

Whoever is interested for the clicked target element should subscribe to the public subject of our utilities service and unsubscribe when the component is destroyed.

export class AnotherComponent implements OnInit {

  @ViewChild('somePopup', { read: ElementRef, static: false }) somePopup: ElementRef

  constructor(private utilitiesService: UtilitiesService) { }

  ngOnInit() {
      this.utilitiesService.documentClickedTarget
           .subscribe(target => this.documentClickListener(target))
  }

  documentClickListener(target: any): void {
     if (this.somePopup.nativeElement.contains(target))
        // Clicked inside  
     else
        // Clicked outside
  }

MySQL - SELECT all columns WHERE one column is DISTINCT

The problem comes from instinctively believing that DISTINCT is a local pre-modifier for a column.

Hence, you "should" be able to type

XXbadXX SELECT col1, DISTINCT col2 FROM mytable XXbadXX

and have it return unique values for col2. Sadly, no. DISTINCT is actually a global post-modifier for SELECT, that is, as opposed to SELECT ALL (returning all answers) it is SELECT DISTINCT (returning all unique answers). So a single DISTINCT acts on ALL the columns that you give it.

This makes it real hard to use DISTINCT on a single column, while getting the other columns, without doing major extremely ugly backflips.

The correct answer is to use a GROUP BY on the columns that you want to have unique answers: SELECT col1, col2 FROM mytable GROUP BY col2 will give you arbitrary unique col2 rows, with their col1 data as well.

Print the address or pointer for value in C

Since you already seem to have solved the basic pointer address display, here's how you would check the address of a double pointer:

char **a;
char *b;
char c = 'H';

b = &c;
a = &b;

You would be able to access the address of the double pointer a by doing:

printf("a points at this memory location: %p", a);
printf("which points at this other memory location: %p", *a);

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

FWIW, it smells like an error (or at least a potential source of future pain) to be using files from /usr/include when cross-compiling.

Android : How to set onClick event for Button in List item of ListView

In your custom adapter inside getView method :

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do things Here 
    }
});

Storing and displaying unicode string (??????) using PHP and MySQL

CREATE DATABASE hindi_test
CHARACTER SET utf8
COLLATE utf8_unicode_ci;
USE hindi_test;
CREATE TABLE `hindi` (`data` varchar(200) COLLATE utf8_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `hindi` (`data`) VALUES('????????');

Send email from localhost running XAMMP in PHP using GMAIL mail server

Here's the link that gives me the answer:

[Install] the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip

[Modify] the php.ini file to use it (commented out the other lines):

[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25

; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(ignore the "Unix only" bit, since we actually are using sendmail)

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

To access a Gmail account protected by 2-factor verification, you will need to create an application-specific password. (source)

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

PowerShell: Run command from script's directory

There are answers with big number of votes, but when I read your question, I thought you wanted to know the directory where the script is, not that where the script is running. You can get the information with powershell's auto variables

$PSScriptRoot - the directory where the script exists, not the target directory the script is running in
$PSCommandPath - the full path of the script

For example, I have $profile script that finds visual studio solution file and start it. I wanted to store the full path, once a solution file is started. But I wanted to save the file where the original script exists. So I used $PsScriptRoot.

How do I use an image as a submit button?

<form id='formName' name='formName' onsubmit='redirect();return false;'>
        <div class="style7">
    <input type='text' id='userInput' name='userInput' value=''>
    <img src="BUTTON1.JPG" onclick="document.forms['formName'].submit();">
</div>
</form>

how to use List<WebElement> webdriver

Try the following code:

//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
  System.out.println(e.getText());
}

It will returns with the whole content of the <li> tags, like:

<a class="extra">Vše</a> (950)</li>

But you can easily get the number now from it, for example by using split() and/or substring().

How to determine if string contains specific substring within the first X characters

shorter version:

found = Value1.StartsWith("abc");

sorry, but I am a stickler for 'less' code.


Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith

public static class StackOverflowExtensions
{
    public static bool StartsWith(this String val, string findString, int count)
    {
        return val.Substring(0, count).Contains(findString);
    }
}

Efficient way to determine number of digits in an integer

int numberOfDigits(int n){

    if(n<=9){
        return 1;
    }
    return 1 + numberOfDigits(n/10);
}

This is what i would do, if you want it for base 10.Its pretty fast and you prolly wont get a stack overflock buy counting integers

Copy Image from Remote Server Over HTTP

This answer helped to me download image from server to client side.

<a download="original_file.jpg" href="file/path.jpg">
  <img src="file/path.jpg" class="img-responsive" width="600" />
</a>

How to Add Stacktrace or debug Option when Building Android Studio Project

On the Mac version of Android Studio Beta 1.2, it's under

Android Studio->preferences->Build, Execution, Deployment->Compiler

Count frequency of words in a list and sort by frequency

Try this:

words = []
freqs = []

for line in sorted(original list): #takes all the lines in a text and sorts them
    line = line.rstrip() #strips them of their spaces
    if line not in words: #checks to see if line is in words
        words.append(line) #if not it adds it to the end words
        freqs.append(1) #and adds 1 to the end of freqs
    else:
        index = words.index(line) #if it is it will find where in words
        freqs[index] += 1 #and use the to change add 1 to the matching index in freqs

Twitter Bootstrap - how to center elements horizontally or vertically

With bootstrap 4 you can use flex

<div class="d-flex justify-content-center align-items-center">
    <button type="submit" class="btn btn-primary">Create</button>
</div>

source: bootstrap 4.1

Converting a string to a date in DB2

Based on your own answer, I'm guessing that your column has data formatted like this:

'DD/MM/YYYY HH:MI:SS'

The actual separators between Day/Month/Year don't matter, nor does anything that comes after the year.

You don't say what version of DB2 you are using or what platform it's running on, so I'm going to assume that it's on Linux, UNIX or Windows.

Almost any recent version of DB2 for Linux/UNIX/Windows (8.2 or later, possibly even older versions), you can do this using the TRANSLATE function:

select 
   date(translate('GHIJ-DE-AB',column_with_date,'ABCDEFGHIJ'))
from
   yourtable

With this solution it doesn't matter what comes after the date in your column.

In DB2 9.7, you can also use the TO_DATE function (similar to Oracle's TO_DATE):

date(to_date(column_with_date,'DD-MM-YYYY HH:MI:SS'))

This requires your data match the formatting string; it's easier to understand when looking at it, but not as flexible as the TRANSLATE option.

How can I remove an SSH key?

Check if folder .ssh is on your system

  1. Go to folder --> /Users/administrator/.ssh/id_ed25519.pub

If not, then

  1. Open Terminal.

Paste in the terminal

  1. Check user ? ssh -T [email protected]

Remove existing SSH keys

  1. Remove existing SSH keys ? rm ~/.ssh/github_rsa.pub

Create New

  1. Create new SSH key ? ssh-keygen -t rsa -b 4096 -C "[email protected]"

  2. The public key has been saved in "/Users/administrator/.ssh/id_ed25519.pub."

  3. Open the public key saved path.

  4. Copy the SSH key ? GitLab Account ? Setting ? SSH Key ? Add key

  5. Test again from the terminal ? ssh -T [email protected]

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

My situation was a bit different.

  • JAVA_HOME was set properly to point to 1.7
  • Other Maven projects were working/building fine with 1.7 features.
  • PATH was set properly.
  • Everything was up-to-date.

Still my simple new Maven project was not working. What I noticed was the difference in the logs when I ran mvn clean install. For my older Maven projects, it showed

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ oldProject---

But for my new project it showed:

[INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ newProject ---

So, I looked at the POM.xml and noticed this thing in the old project's POM:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Basically, this plugin tells which compiler version to use for compilation. Just added it to the new project's POM.xml and things worked.

Hope it is useful to someone.

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

HTML.ActionLink method

If you want to go all fancy-pants, here's how you can extend it to be able to do this:

@(Html.ActionLink<ArticlesController>(x => x.Details(), article.Title, new { id = article.ArticleID }))

You will need to put this in the System.Web.Mvc namespace:

public static class MyProjectExtensions
{
    public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName));
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    public static MvcHtmlString ActionLink<TController, TAction>(this HtmlHelper htmlHelper, Expression<Action<TController, TAction>> expression, string linkText, object routeValues)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText, object routeValues, object htmlAttributes) where TController : Controller
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

        var attributes = AnonymousObjectToKeyValue(htmlAttributes);

        var link = new TagBuilder("a");

        string actionName = ExpressionHelper.GetExpressionText(expression);
        string controllerName = typeof(TController).Name.Replace("Controller", "");

        link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
        link.MergeAttributes(attributes, true);
        link.SetInnerText(linkText);

        return new MvcHtmlString(link.ToString());
    }

    private static Dictionary<string, object> AnonymousObjectToKeyValue(object anonymousObject)
    {
        var dictionary = new Dictionary<string, object>();

        if (anonymousObject == null) return dictionary;

        foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
        {
            dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(anonymousObject));
        }

        return dictionary;
    }
}

This includes two overrides for Route Values and HTML Attributes, also, all of your views would need to add: @using YourProject.Controllers or you can add it to your web.config <pages><namespaces>

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

A field initializer cannot reference the nonstatic field, method, or property

private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; is a field initializer and executes first (before any field without an initializer is set to its default value and before the invoked instance constructor is executed). Instance fields that have no initializer will only have a legal (default) value after all instance field initializers are completed. Due to the initialization order, instance constructors are executed last, which is why the instance is not created yet the moment the initializers are executed. Therefore the compiler cannot allow any instance property (or field) to be referenced before the class instance is fully constructed. This is because any access to an instance variable like reminder implicitly references the instance (this) to tell the compiler the concrete memory location of the instance to use.

This is also the reason why this is not allowed in an instance field initializer.

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple_name.

The only type members that are guaranteed to be initialized before instance field initializers are executed are class (static) field initializers and class (static) constructors and class methods. Since static members are instance independent, they can be referenced at any time:

class SomeOtherClass
{
  private static Reminders reminder = new Reminders();

  // This operation is allowed,
  // since the compiler can guarantee that the referenced class member is already initialized
  // when this instance field initializer executes
  private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

That's why instance field initializers are only allowed to reference a class member (static member). This compiler initialization rules will ensure a deterministic type instantiation.

For more details I recommend this document: Microsoft Docs: Class declarations.

This means that an instance field that references another instance member to initialize its value, must be initialized from the instance constructor or the referenced member must be declared static.

Set a cookie to never expire

All cookies expire as per the cookie specification, so this is not a PHP limitation.

Use a far future date. For example, set a cookie that expires in ten years:

setcookie(
  "CookieName",
  "CookieValue",
  time() + (10 * 365 * 24 * 60 * 60)
);

Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.

  1. Data can be passed as a string using the @ string literal, pass string value, one way binding.
  2. Data can be passed as an object using the = string literal, pass object, 2 ways binding.
  3. Data can be passed as a function the & string literal, calls external function, can pass data from directive to controller.

Querying data by joining two tables in two database on different servers

You could try the following:

select customer1.Id,customer1.Name,customer1.city,CustAdd.phone,CustAdd.Country
from customer1
inner join [EBST08].[Test].[dbo].[customerAddress] CustAdd
on customer1.Id=CustAdd.CustId

Create an array with same element repeated multiple times

I discovered this today while trying to make a 2D array without using loops. In retrospect, joining a new array is neat; I tried mapping a new array, which doesn't work as map skips empty slots.

"#".repeat(5).split('').map(x => 0)

The "#" char can be any valid single character. The 5 would be a variable for the number of elements you want. The 7 would be the value you want to fill your array with.

The new fill method is better, and when I coded this I didn't know it existed, nor did I know repeat is es6; I'm going to write a blog post about using this trick in tandem with reduce to do cool things.

http://jburger.us.to/2016/07/14/functionally-create-a-2d-array/

What is the parameter "next" used for in Express?

Before understanding next, you need to have a little idea of Request-Response cycle in node though not much in detail. It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);

let’s have a look at a very simple example.

app.get('/hello', function (req, res, next) {
  res.send('USER')
})

Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.

Now let’s take a look at another example.

app.get('/hello', function (req, res, next) {
  res.send("Hello World !!!!");
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.

But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.

app.get('/hello', function (req, res, next) {
  if(some condition){
    next();
    return;
  }
  res.send("Hello World !!!!");  
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

What’s the next doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!" response.

So, next pass the control to the next function in the middleware stack.

What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.

Something like below:-

app.get('/hello', function (req, res, next) {
  // Your piece of logic
  next();
});

app.get('/hello', function (req, res, next) {
  res.send("Hello !!!!");
});

In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();

What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.

Difference between $(document.body) and $('body')

The answers here are not actually completely correct. Close, but there's an edge case.

The difference is that $('body') actually selects the element by the tag name, whereas document.body references the direct object on the document.

That means if you (or a rogue script) overwrites the document.body element (shame!) $('body') will still work, but $(document.body) will not. So by definition they're not equivalent.

I'd venture to guess there are other edge cases (such as globally id'ed elements in IE) that would also trigger what amounts to an overwritten body element on the document object, and the same situation would apply.

How to connect to a MySQL Data Source in Visual Studio

After a lot of searching and trying many solutions, I got it finally:

  1. uninstall connector

  2. uninstall MySQL for Visual Studio from control panel

    click here

  3. reinstall them according to the table below

    click here

  4. copy the assembly files from C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5 to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE

  5. log off and reopen your solution

  6. enjoy

How to find all the dependencies of a table in sql server

You can use free tool called Advanced SQL Server Dependencies http://advancedsqlserverdependencies.codeplex.com/

It supports all database objects (tables, views, etc.) and can find dependencies across multiple databases (in case of synonyms).

Regular expression that matches valid IPv6 addresses

Just matching local ones from an origin with square brackets included. I know it's not as comprehensive but in javascript the other ones had difficult to trace issues primarily that of not working, so this seems to get me what I needed for now. extra capitals A-F aren't needed either.

^\[([0-9a-fA-F]{1,4})(\:{1,2})([0-9a-fA-F]{1,4})(\:{1,2})([0-9a-fA-F]{1,4})(\:{1,2})([0-9a-fA-F]{1,4})(\:{1,2})([0-9a-fA-F]{1,4})\]

Jinnko's version is simplified and better I see.

Signed versus Unsigned Integers

According to what we learned in class, signed integers can represent both positive and negative numbers, while unsigned integers are only non-negative.

For example, looking at an 8-bit number:

unsigned values 0 to 255

signed values range from -128 to 127

Can't find bundle for base name /Bundle, locale en_US

In my case the problem was using the language tag "en_US" in Locale.forLanguageTag(..) instead of "en-US" - use a dash instead of underline!

Also use Locale.forLanguageTag("en-US") instead of new Locale("en_US") or new Locale("en_US") to define a language ("en") with a region ("US") - but new Locale("en") works.

How do I validate a date string format in python?

The Python dateutil library is designed for this (and more). It will automatically convert this to a datetime object for you and raise a ValueError if it can't.

As an example:

>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)

This raises a ValueError if the date is not formatted correctly:

>>> parse("2003-09-251")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
    ret = default.replace(**repl)
ValueError: day is out of range for month

dateutil is also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: dateutil parsing examples.

It also handles timezones if you need that.

Update based on comments: parse also accepts the keyword argument dayfirst which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g.

>>> parse('11/12/2001')
>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12
>>> parse('11/12/2001', dayfirst=True)
>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11

How to calculate probability in a normal distribution given mean & standard deviation?

The formula cited from wikipedia mentioned in the answers cannot be used to calculate normal probabilites. You would have to write a numerical integration approximation function using that formula in order to calculate the probability.

That formula computes the value for the probability density function. Since the normal distribution is continuous, you have to compute an integral to get probabilities. The wikipedia site mentions the CDF, which does not have a closed form for the normal distribution.

EOFError: end of file reached issue with Net::HTTP

I find that I run into Net::HTTP and Net::FTP problems like this periodically, and when I do, surrounding the call with a timeout() makes all of those issues vanish. So where this will occasionally hang for 3 minutes or so and then raise an EOFError:

res = Net::HTTP.post_form(uri, args)

This always fixes it for me:

res = timeout(120) { Net::HTTP.post_form(uri, args) }

Task continuation on UI thread

Got here through google because i was looking for a good way to do things on the ui thread after being inside a Task.Run call - Using the following code you can use await to get back to the UI Thread again.

I hope this helps someone.

public static class UI
{
    public static DispatcherAwaiter Thread => new DispatcherAwaiter();
}

public struct DispatcherAwaiter : INotifyCompletion
{
    public bool IsCompleted => Application.Current.Dispatcher.CheckAccess();

    public void OnCompleted(Action continuation) => Application.Current.Dispatcher.Invoke(continuation);

    public void GetResult() { }

    public DispatcherAwaiter GetAwaiter()
    {
        return this;
    }
}

Usage:

... code which is executed on the background thread...
await UI.Thread;
... code which will be run in the application dispatcher (ui thread) ...

Make element fixed on scroll

Here you go, no frameworks, short and simple:

var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;

window.addEventListener('scroll', function(){
    if (document.documentElement.scrollTop > elTop){
        el.style.position = 'fixed';
        el.style.top = '0px';
    }
    else
    {
        el.style.position = 'static';
        el.style.top = 'auto';
    }
});

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

How do I install ASP.NET MVC 5 in Visual Studio 2012?

Microsoft has provided for you on their MSDN blogs: MVC 5 for VS2012. From that blog:

We have released ASP.NET and Web Tools 2013.1 for Visual Studio 2012. This release brings a ton of great improvements, and include some fantastic enhancements to ASP.NET MVC 5, Web API 2, Scaffolding and Entity Framework to users of Visual Studio 2012 and Visual Studio 2012 Express for Web.

You can download and start using these features now.

The download link is to a Web Platform Installer that will allow you to start a new MVC5 project from VS2012.

Removing Java 8 JDK from Mac

If you uninstall all the files but it still fails, use this line:

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk

jQuery - passing value from one input to another

Get input1 data to send them to input2 immediately

<div>
<label>Input1</label>
 <input type="text" id="input1" value="">
</div>

</br>
<label>Input2</label>
<input type="text" id="input2" value="">

<script type="text/javascript">
        $(document).ready(function () {
            $("#input1").keyup(function () {
                var value = $(this).val();
                $("#input2").val(value);
            });
        });
</script>

How do I access my webcam in Python?

import cv2 as cv

capture = cv.VideoCapture(0)

while True:
    isTrue,frame = capture.read()
    cv.imshow('Video',frame)
    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

0 <-- refers to the camera , replace it with file path to read a video file

cv.waitKey(20) & 0xFF==ord('d') <-- to destroy window when key is pressed

How do I convert uint to int in C#?

Convert.ToInt32() takes uint as a value.

Replacing objects in array

This is how I do it in TypeScript:

const index = this.array.indexOf(this.objectToReplace);
this.array[index] = newObject;

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

How/When does Execute Shell mark a build as failure in Jenkins?

First things first, hover the mouse over the grey area below. Not part of the answer, but absolutely has to be said:

If you have a shell script that does "checkout, build, deploy" all by itself, then why are you using Jenkins? You are foregoing all the features of Jenkins that make it what it is. You might as well have a cron or an SVN post-commit hook call the script directly. Jenkins performing the SVN checkout itself is crucial. It allows the builds to be triggered only when there are changes (or on timer, or manual, if you prefer). It keeps track of changes between builds. It shows those changes, so you can see which build was for which set of changes. It emails committers when their changes caused successful or failed build (again, as configured as you prefer). It will email committers when their fixes fixed the failing build. And more and more. Jenkins archiving the artifacts also makes them available, per build, straight off Jenkins. While not as crucial as the SVN checkout, this is once again an integral part of what makes it Jenkins. Same with deploying. Unless you have a single environment, deployment usually happens to multiple environments. Jenkins can keep track of which environment a specific build (with specific set of SVN changes) is deployed it, through the use of Promotions. You are foregoing all of this. It sounds like you are told "you have to use Jenkins" but you don't really want to, and you are doing it just to get your bosses off your back, just to put a checkmark "yes, I've used Jenkins"

The short answer is: the exit code of last command of the Jenkin's Execute Shell build step is what determines the success/failure of the Build Step. 0 - success, anything else - failure. Note, this is determining the success/failure of the build step, not the whole job run. The success/failure of the whole job run can further be affected by multiple build steps, and post-build actions and plugins.

You've mentioned Build step 'Execute shell' marked build as failure, so we will focus just on a single build step. If your Execute shell build step only has a single line that calls your shell script, then the exit code of your shell script will determine the success/failure of the build step. If you have more lines, after your shell script execution, then carefully review them, as they are the ones that could be causing failure.

Finally, have a read here Jenkins Build Script exits after Google Test execution. It is not directly related to your question, but note that part about Jenkins launching the Execute Shell build step, as a shell script with /bin/sh -xe

The -e means that the shell script will exit with failure, even if just 1 command fails, even if you do error checking for that command (because the script exits before it gets to your error checking). This is contrary to normal execution of shell scripts, which usually print the error message for the failed command (or redirect it to null and handle it by other means), and continue.

To circumvent this, add set +e to the top of your shell script.

Since you say your script does all it is supposed to do, chances are the failing command is somewhere at the end of the script. Maybe a final echo? Or copy of artifacts somewhere? Without seeing the full console output, we are just guessing.

Please post the job run's console output, and preferably the shell script itself too, and then we could tell you exactly which line is failing.

Excel CSV - Number cell format

Load csv into oleDB and force all inferred datatypes to string

i asked the same question and then answerd it with code.

basically when the csv file is loaded the oledb driver makes assumptions, you can tell it what assumptions to make.

My code forces all datatypes to string though ... its very easy to change the schema. for my purposes i used an xslt to get ti the way i wanted - but i am parsing a wide variety of files.

Launch programs whose path contains spaces

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("firefox")
Set objShell = Nothing

Please try this

Android studio logcat nothing to show

Run this command in terminal. It will start working again.

adb kill-server && adb start-server

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

Get the IP address of the machine

Further to what Steve Baker has said, you can find a description of the SIOCGIFCONF ioctl in the netdevice(7) man page.

Once you have the list of all the IP addresses on the host, you will have to use application specific logic to filter out the addresses you do not want and hope you have one IP address left.

Error With Port 8080 already in use

if you are running from inside eclipse with wtp, you should be able to change the port from the "servers" view (window -> show view -> servers)

AngularJS - convert dates in controller

All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ item.date | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $scope.item.date = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.

Stretch Image to Fit 100% of Div Height and Width

You're mixing notations. It should be:

<img src="folder/file.jpg" width="200" height="200">

(note, no px). Or:

<img src="folder/file.jpg" style="width: 200px; height: 200px;">

(using the style attribute) The style attribute could be replaced with the following CSS:

#mydiv img {
    width: 200px;
    height: 200px;
}

or

#mydiv img {
    width: 100%;
    height: 100%;
}

How to get a MemoryStream from a Stream in .NET?

You can simply do:

var ms = new MemoryStream(File.ReadAllBytes(filePath));

Stream position is 0 and ready to use.

Python: list of lists

Time traveller here

List_of_list =[([z for z in range(x-2,x+1) if z >= 0],y) for y in range(10) for x in range(10)]

This should do the trick. And the output is this:

[([0], 0), ([0, 1], 0), ([0, 1, 2], 0), ([1, 2, 3], 0), ([2, 3, 4], 0),  ([3, 4, 5], 0), ([4, 5, 6], 0), ([5, 6, 7], 0), ([6, 7, 8], 0), ([7, 8, 9], 0), ([0], 1), ([0, 1], 1), ([0, 1, 2], 1), ([1, 2, 3], 1), ([2, 3, 4], 1), ([3, 4, 5], 1), ([4, 5, 6], 1), ([5, 6, 7], 1), ([6, 7, 8], 1), ([7, 8, 9], 1), ([0], 2), ([0, 1], 2), ([0, 1, 2], 2), ([1, 2, 3], 2), ([2, 3, 4], 2), ([3, 4, 5], 2), ([4, 5, 6], 2), ([5, 6, 7], 2), ([6, 7, 8], 2), ([7, 8, 9], 2), ([0], 3), ([0, 1], 3), ([0, 1, 2], 3), ([1, 2, 3], 3), ([2, 3, 4], 3), ([3, 4, 5], 3), ([4, 5, 6], 3), ([5, 6, 7], 3), ([6, 7, 8], 3), ([7, 8, 9], 3), ([0], 4), ([0, 1], 4), ([0, 1, 2], 4), ([1, 2, 3], 4), ([2, 3, 4], 4), ([3, 4, 5], 4), ([4, 5, 6], 4), ([5, 6, 7], 4), ([6, 7, 8], 4), ([7, 8, 9], 4), ([0], 5), ([0, 1], 5), ([0, 1, 2], 5), ([1, 2, 3], 5), ([2, 3, 4], 5), ([3, 4, 5], 5), ([4, 5, 6], 5), ([5, 6, 7], 5), ([6, 7, 8], 5), ([7, 8, 9], 5), ([0], 6), ([0, 1], 6), ([0, 1, 2], 6), ([1, 2, 3], 6), ([2, 3, 4], 6), ([3, 4, 5], 6), ([4, 5, 6], 6), ([5, 6, 7], 6), ([6, 7, 8], 6), ([7, 8, 9], 6), ([0], 7), ([0, 1], 7), ([0, 1, 2], 7), ([1, 2, 3], 7), ([2, 3, 4], 7), ([3, 4, 5], 7), ([4, 5, 6], 7), ([5, 6, 7], 7), ([6, 7, 8], 7), ([7, 8, 9], 7), ([0], 8), ([0, 1], 8), ([0, 1, 2], 8), ([1, 2, 3], 8), ([2, 3, 4], 8), ([3, 4, 5], 8), ([4, 5, 6], 8), ([5, 6, 7], 8), ([6, 7, 8], 8), ([7, 8, 9], 8), ([0], 9), ([0, 1], 9), ([0, 1, 2], 9), ([1, 2, 3], 9), ([2, 3, 4], 9), ([3, 4, 5], 9), ([4, 5, 6], 9), ([5, 6, 7], 9), ([6, 7, 8], 9), ([7, 8, 9], 9)]    

This is done by list comprehension(which makes looping elements in a list via one line code possible). The logic behind this one-line code is the following:

(1) for x in range(10) and for y in range(10) are employed for two independent loops inside a list

(2) (a list, y) is the general term of the loop, which is why it is placed before two for's in (1)

(3) the length of the list in (2) cannot exceed 3, and the list depends on x, so

[z for z in range(x-2,x+1)] 

is used

(4) because z starts from zero but range(x-2,x+1) starts from -2 which isn't what we want, so a conditional statement if z >= 0 is placed at the end of the list in (2)

[z for z in range(x-2,x+1) if z >= 0] 

Is there a way to 'uniq' by column?

or if u want to use uniq:

<mycvs.cvs tr -s ',' ' ' | awk '{print $3" "$2" "$1}' | uniq -c -f2

gives:

1 01:05:47.893000000 2009-11-27 [email protected]
2 00:58:29.793000000 2009-11-27 [email protected]
1

Communication between multiple docker-compose projects

The previous posts information is correct, but it does not have details on how to link containers, which should be connected as "external_links".

Hope this example make more clear to you:

  • Suppose you have app1/docker-compose.yml, with two services (svc11 and svc12), and app2/docker-compose.yml with two more services (svc21 and svc22) and suppose you need to connect in a crossed fashion:

  • svc11 needs to connect to svc22's container

  • svc21 needs to connect to svc11's container.

So the configuration should be like this:

this is app1/docker-compose.yml:


version: '2'
services:
    svc11:
        container_name: container11
        [..]
        networks:
            - default # this network
            - app2_default # external network
        external_links:
            - container22:container22
        [..]
    svc12:
       container_name: container12
       [..]

networks:
    default: # this network (app1)
        driver: bridge
    app2_default: # external network (app2)
        external: true

this is app2/docker-compose.yml:


version: '2'
services:
    svc21:
        container_name: container21
        [..]
        networks:
            - default # this network (app2)
            - app1_default # external network (app1)
        external_links:
            - container11:container11
        [..]
    svc22:
       container_name: container22
       [..]

networks:
    default: # this network (app2)
        driver: bridge
    app1_default: # external network (app1)
        external: true

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

PHP sessions that have already been started

Only if you want to destroy previous session :

<?php
    if(!isset($_SESSION)) 
    { 
        session_start(); 
    }
    else
    {
        session_destroy();
        session_start(); 
    }
?>

or you can use

unset($_SESSION['variable_session _data'])

to destroy a particular session variable.

How can I count the occurrences of a list item?

Although it is very old question, but as i didn't find a one liner, i made one.

# original numbers in list
l = [1, 2, 2, 3, 3, 3, 4]

# empty dictionary to hold pair of number and its count
d = {}

# loop through all elements and store count
[ d.update( {i:d.get(i, 0)+1} ) for i in l ]

print(d)

How can I get the executing assembly version?

I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.

Sourced from a combination of places:

https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx

Elasticsearch query to return all records

Simple! You can use size and from parameter!

http://localhost:9200/[your index name]/_search?size=1000&from=0

then you change the from gradually until you get all of the data.

Have border wrap around text

Try this and see if you get what you are aiming for:

_x000D_
_x000D_
<div id='page' style='width: 600px'>_x000D_
  <h1 style='border:2px black solid; font-size:42px; width:fit-content; width:-webkit-fit-content; width:-moz-fit-content;'>Title</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Jquery Ajax Loading image

Its a bit late but if you don't want to use a div specifically, I usually do it like this...

var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);

ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.

Pythonic way to find maximum value and its index in a list?

With Python's built-in library, it's pretty easy:

a = [2, 9, -10, 5, 18, 9] 
max(xrange(len(a)), key = lambda x: a[x])

This tells max to find the largest number in the list [0, 1, 2, ..., len(a)], using the custom function lambda x: a[x], which says that 0 is actually 2, 1 is actually 9, etc.

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

Is quitting an application frowned upon?

I'd just like to add a correction here for the future readers of this thread. This particular nuance has escaped my understanding for a long time so I want to make sure none of you make the same mistakes:

System.exit() does not kill your app if you have more than one activity on the stack. What actually happens is that the process is killed and immediately restarted with one fewer activity on the stack. This is also what happens when your app is killed by the Force Close dialog, or even when you try to kill the process from DDMS. This is a fact that is entirely undocumented, to my knowledge.

The short answer is, if you want to exit your application, you've got to keep track of all activities in your stack and finish() ALL of them when the user wants to exit (and no, there is no way to iterate through the Activity stack, so you have to manage all of this yourself). Even this does not actually kill the process or any dangling references you may have. It simply finishes the activities. Also, I'm not sure whether Process.killProcess(Process.myPid()) works any better; I haven't tested it.

If, on the other hand, it is okay for you to have activities remaining in your stack, there is another method which makes things super easy for you: Activity.moveTaskToBack(true) will simply background your process and show the home screen.

The long answer involves explanation of the philosophy behind this behavior. The philosophy is born out of a number of assumptions:

  1. First of all, this only happens when your app is in the foreground. If it is in the background the process will terminate just fine. However, if it is in the foreground, the OS assumes that the user wants to keep doing whatever he/she was doing. (If you are trying to kill the process from DDMS, you should hit the home button first, and then kill it)
  2. It also assumes that each activity is independent of all the other activities. This is often true, for example in the case that your app launches the Browser Activity, which is entirely separate and was not written by you. The Browser Activity may or may not be created on the same Task, depending on its manifest attributes.
  3. It assumes that each of your activities is completely self-reliant and can be killed/restored in a moment's notice. (I rather dislike this particular assumption, since my app has many activities which rely on a large amount of cached data, too large to be efficiently serialized during onSaveInstanceState, but whaddya gonna do?) For most well-written Android apps this should be true, since you never know when your app is going to be killed off in the background.
  4. The final factor is not so much an assumption, but rather a limitation of the OS: killing the app explicitly is the same as the app crashing, and also the same as Android killing the app to reclaim memory. This culminates in our coup de grace: since Android can't tell if the app exited or crashed or was killed in the background, it assumes the user wants to return where they left off, and so the ActivityManager restarts the process.

When you think about it, this is appropriate for the platform. First, this is exactly what happens when the process is killed in the background and the user comes back to it, so it needs to be restarted where it left off. Second, this is what happens when the app crashes and presents the dreaded Force Close dialog.

Say I want my users to be able to take a picture and upload it. I launch the Camera Activity from my activity, and ask it to return an image. The Camera is pushed onto the top of my current Task (rather than being created in its own Task). If the Camera has an error and it crashes, should that result in the whole app crashing? From the standpoint of the user, only the Camera failed, and they should be returned to their previous activity. So it just restarts the process with all the same Activities in the stack, minus the Camera. Since your Activities should be designed so that they can be killed and restored at the drop of a hat, this shouldn't be a problem. Unfortunately, not all apps can be designed that way, so it is a problem for many of us, no matter what Romain Guy or anyone else tells you. So, we need to use workarounds.

So, my closing advice:

  • Don't try to kill the process. Either call finish() on all activities or call moveTaskToBack(true).
  • If your process crashes or gets killed, and if, like me, you need the data that was in memory which is now lost, you'll need to return to the root activity. To do this, you should call startActivity() with an Intent that contains the Intent.FLAG_ACTIVITY_CLEAR_TOP flag.
  • If you want to kill your app from the Eclipse DDMS perspective, it had better not be in the foreground, or it will restart itself. You should press the Home button first, and then kill the process.

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

I know this is a really old question however no answers provide the proper reasoning for why this can never be done. While you can "do" what you are looking for you cannot do it in a valid way. In order to have a valid img tag it must have the src and alt attributes.

So any of the answers giving a way to do this with an img tag that does not use the src attribute are promoting use of invalid code.

In short: what you are looking for cannot be done legally within the structure of the syntax.

Source: W3 Validator

How to represent empty char in Java Character class

You can't. "" is the literal for a string, which contains no characters. It does not contain the "empty character" (whatever you mean by that).

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. you are selecting

t1.ID, t2.ReceivedDate from Table t1

union

t2.ID from Table t2

which is incorrect.

so you have to write

t1.ID, t1.ReceivedDate from Table t1 union t2.ID, t2.ReceivedDate from Table t1

you can use sub query here

 SELECT tbl1.ID, tbl1.ReceivedDate FROM
      (select top 2 t1.ID, t1.ReceivedDate
      from tbl1 t1
      where t1.ItemType = 'TYPE_1'
      order by ReceivedDate desc
      ) tbl1 
 union
    SELECT tbl2.ID, tbl2.ReceivedDate FROM
     (select top 2 t2.ID, t2.ReceivedDate
      from tbl2 t2
      where t2.ItemType = 'TYPE_2'
      order by t2.ReceivedDate desc
     ) tbl2 

so it will return only distinct values by default from both table.

Convert array to JSON

One other way could be this:

        var json_arr = {};
        json_arr["name1"] = "value1";
        json_arr["name2"] = "value2";
        json_arr["name3"] = "value3";

        var json_string = JSON.stringify(json_arr);

Check if an array contains duplicate values

The code given in the question can be better written as follows

function checkIfArrayIsUnique(myArray) 
    {
        for (var i = 0; i < myArray.length; i++) 
        {
            for (var j = i+1; j < myArray.length; j++) 
            {                  
                    if (myArray[i] == myArray[j]) 
                    {
                        return true; // means there are duplicate values
                    }

            }
        }
        return false; // means there are no duplicate values.
    }

Instant run in Android Studio 2.0 (how to turn off)

the design in android 2.3 (stable version) is slightly changed.

File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.

enter image description here

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

Just finished a 2 hour wild goose chase trying to solve this. None of the posted answers worked for me. Im on a Mac (Mojave Version 10.14.6, Xcode Version 11.3).

It turns out the ruby file headers were missing so i had to run open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

That didnt work for me at first because the version of CommandLineTools i had installed did not have the "Packages" folder. So i uninstalled and reinstalled like this:

rm -rf /Library/Developer/CommandLineTools

xcode-select --install

Then i ran the previous command again:

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

After install the error was fixed!

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

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

Since Ruby 2.5.0, Array ships with the prepend method (which is just an alias for the unshift method).

How do I "Add Existing Item" an entire directory structure in Visual Studio?

In Solution Explorer:

  1. Click Show All Files (second icon from the left at the top of Solution Explorer).
  2. Locate the folder you want to add.
  3. Right-click and select "Include in Project"

I use this to install add-ons like HTML editors and third-party file browsers.

SQL Update Multiple Fields FROM via a SELECT Statement

you can use update from...

something like:

update shipment set.... from shipment inner join ProfilerTest.dbo.BookingDetails on ...

Java ArrayList copy

Just for completion: All the answers above are going for a shallow copy - keeping the reference of the original objects. I you want a deep copy, your (reference-) class in the list have to implement a clone / copy method, which provides a deep copy of a single object. Then you can use:

newList.addAll(oldList.stream().map(s->s.clone()).collect(Collectors.toList()));

Javascript loop through object array?

In your script, data is your whole object.

key is "messages", which is an array you need to iterate through like this:

    for (var key in data) {
       var arr = data[key];
       for( var i = 0; i < arr.length; i++ ) {
           var obj = arr[ i ];
           for (var prop in obj) {
               if(obj.hasOwnProperty(prop)){
                   console.log(prop + " = " + obj[prop]);
               }
           }
       }
    }

Generate sha256 with OpenSSL and C++

Here's the function I personally use - I simply derived it from the function I used for sha-1 hashing:

char *str2sha256( const char *str, int length ) {
  int n;
  SHA256_CTX c;
  unsigned char digest[ SHA256_DIGEST_LENGTH ];
  char *out = (char*) malloc( 33 );

  SHA256_Init( &c );

  while ( length > 0 ) {
    if ( length > 512 ) SHA256_Update( &c, str, 512 );
    else SHA256_Update( &c, str, length );

    length -= 512;
    str += 512;
  }

  SHA256_Final ( digest, &c );

  for ( n = 0; n < SHA256_DIGEST_LENGTH; ++n )
    snprintf( &( out[ n*2 ] ), 16*2, "%02x", (unsigned int) digest[ n ] );

  return out;
}

Full screen background image in an activity

Another option is to add a single image (not necessarily big) in the drawables (let's name it backgroung.jpg), create an ImageView iv_background at the root of your xml without a "src" attribute. Then in the onCreate method of the corresponding activity:

    /* create a full screen window */
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.your_activity);

    /* adapt the image to the size of the display */
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    Bitmap bmp = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(
      getResources(),R.drawable.background),size.x,size.y,true);

    /* fill the background ImageView with the resized image */
    ImageView iv_background = (ImageView) findViewById(R.id.iv_background);
    iv_background.setImageBitmap(bmp);

No cropping, no many different sized images. Hope it helps!

Call An Asynchronous Javascript Function Synchronously

Async functions, a feature in ES2017, make async code look sync by using promises (a particular form of async code) and the await keyword. Also notice in the code examples below the keyword async in front of the function keyword that signifies an async/await function. The await keyword won't work without being in a function pre-fixed with the async keyword. Since currently there is no exception to this that means no top level awaits will work (top level awaits meaning an await outside of any function). Though there is a proposal for top-level await.

ES2017 was ratified (i.e. finalized) as the standard for JavaScript on June 27th, 2017. Async await may already work in your browser, but if not you can still use the functionality using a javascript transpiler like babel or traceur. Chrome 55 has full support of async functions. So if you have a newer browser you may be able to try out the code below.

See kangax's es2017 compatibility table for browser compatibility.

Here's an example async await function called doAsync which takes three one second pauses and prints the time difference after each pause from the start time:

_x000D_
_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
async function doAsync () {_x000D_
  var start = Date.now(), time;_x000D_
  console.log(0);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
}_x000D_
_x000D_
doAsync();
_x000D_
_x000D_
_x000D_

When the await keyword is placed before a promise value (in this case the promise value is the value returned by the function doSomethingAsync) the await keyword will pause execution of the function call, but it won't pause any other functions and it will continue executing other code until the promise resolves. After the promise resolves it will unwrap the value of the promise and you can think of the await and promise expression as now being replaced by that unwrapped value.

So, since await just pauses waits for then unwraps a value before executing the rest of the line you can use it in for loops and inside function calls like in the below example which collects time differences awaited in an array and prints out the array.

_x000D_
_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
// this calls each promise returning function one after the other_x000D_
async function doAsync () {_x000D_
  var response = [];_x000D_
  var start = Date.now();_x000D_
  // each index is a promise returning function_x000D_
  var promiseFuncs= [doSomethingAsync, doSomethingAsync, doSomethingAsync];_x000D_
  for(var i = 0; i < promiseFuncs.length; ++i) {_x000D_
    var promiseFunc = promiseFuncs[i];_x000D_
    response.push(await promiseFunc() - start);_x000D_
    console.log(response);_x000D_
  }_x000D_
  // do something with response which is an array of values that were from resolved promises._x000D_
  return response_x000D_
}_x000D_
_x000D_
doAsync().then(function (response) {_x000D_
  console.log(response)_x000D_
})
_x000D_
_x000D_
_x000D_

The async function itself returns a promise so you can use that as a promise with chaining like I do above or within another async await function.

The function above would wait for each response before sending another request if you would like to send the requests concurrently you can use Promise.all.

_x000D_
_x000D_
// no change_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
// no change_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
// this function calls the async promise returning functions all at around the same time_x000D_
async function doAsync () {_x000D_
  var start = Date.now();_x000D_
  // we are now using promise all to await all promises to settle_x000D_
  var responses = await Promise.all([doSomethingAsync(), doSomethingAsync(), doSomethingAsync()]);_x000D_
  return responses.map(x=>x-start);_x000D_
}_x000D_
_x000D_
// no change_x000D_
doAsync().then(function (response) {_x000D_
  console.log(response)_x000D_
})
_x000D_
_x000D_
_x000D_

If the promise possibly rejects you can wrap it in a try catch or skip the try catch and let the error propagate to the async/await functions catch call. You should be careful not to leave promise errors unhandled especially in Node.js. Below are some examples that show off how errors work.

_x000D_
_x000D_
function timeoutReject (time) {_x000D_
  return new Promise(function (resolve, reject) {_x000D_
    setTimeout(function () {_x000D_
      reject(new Error("OOPS well you got an error at TIMESTAMP: " + Date.now()));_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doErrorAsync () {_x000D_
  return timeoutReject(1000);_x000D_
}_x000D_
_x000D_
var log = (...args)=>console.log(...args);_x000D_
var logErr = (...args)=>console.error(...args);_x000D_
_x000D_
async function unpropogatedError () {_x000D_
  // promise is not awaited or returned so it does not propogate the error_x000D_
  doErrorAsync();_x000D_
  return "finished unpropogatedError successfully";_x000D_
}_x000D_
_x000D_
unpropogatedError().then(log).catch(logErr)_x000D_
_x000D_
async function handledError () {_x000D_
  var start = Date.now();_x000D_
  try {_x000D_
    console.log((await doErrorAsync()) - start);_x000D_
    console.log("past error");_x000D_
  } catch (e) {_x000D_
    console.log("in catch we handled the error");_x000D_
  }_x000D_
  _x000D_
  return "finished handledError successfully";_x000D_
}_x000D_
_x000D_
handledError().then(log).catch(logErr)_x000D_
_x000D_
// example of how error propogates to chained catch method_x000D_
async function propogatedError () {_x000D_
  var start = Date.now();_x000D_
  var time = await doErrorAsync() - start;_x000D_
  console.log(time - start);_x000D_
  return "finished propogatedError successfully";_x000D_
}_x000D_
_x000D_
// this is what prints propogatedError's error._x000D_
propogatedError().then(log).catch(logErr)
_x000D_
_x000D_
_x000D_

If you go here you can see the finished proposals for upcoming ECMAScript versions.

An alternative to this that can be used with just ES2015 (ES6) is to use a special function which wraps a generator function. Generator functions have a yield keyword which may be used to replicate the await keyword with a surrounding function. The yield keyword and generator function are a lot more general purpose and can do many more things then just what the async await function does. If you want a generator function wrapper that can be used to replicate async await I would check out co.js. By the way co's function much like async await functions return a promise. Honestly though at this point browser compatibility is about the same for both generator functions and async functions so if you just want the async await functionality you should use Async functions without co.js.

Browser support is actually pretty good now for Async functions (as of 2017) in all major current browsers (Chrome, Safari, and Edge) except IE.

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

CSS flexbox not working in IE10

Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes

This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/

edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/

The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/

Refresh Part of Page (div)

You need to do that on the client side for instance with jQuery.

Let's say you want to retrieve HTML into div with ID mydiv:

<h1>My page</h1>
<div id="mydiv">
    <h2>This div is updated</h2>
</div>

You can update this part of the page with jQuery as follows:

$.get('/api/mydiv', function(data) {
  $('#mydiv').html(data);
});

In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.

See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/

How do I install jmeter on a Mac?

jmeter is now just installed with

brew install jmeter

This version includes the plugin manager that you can use to download the additional plugins.

OUTDATED:

If you want to include the plugins (JMeterPlugins Standard, Extras, ExtrasLibs, WebDriver and Hadoop) use:

brew install jmeter --with-plugins

What is a Data Transfer Object (DTO)?

  1. To me the best answer to the question what is a DTO is that DTO's are simple objects that should not contain any business logic or methods implementation that would require testing.
  2. Normally your model (using the MVC pattern) are intelligent models, and they can contain a lot of/some methods that do some different operations for that model specifically (not business logic, this should be at the controllers). However, when you transfer data (eg. calling a REST (GET/POST/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.

mongoError: Topology was destroyed

I got this error, while I was creating a new database on my MongoDb Compass Community. The issue was with my Mongod, it was not running. So as a fix, I had to run the Mongod command as preceding.

C:\Program Files\MongoDB\Server\3.6\bin>mongod

I was able to create a database after running that command.

Hope it helps.

Selecting text in an element (akin to highlighting with your mouse)

Have a look at the Selection object (Gecko engine) and the TextRange object (Trident engine.) I don't know about any JavaScript frameworks that have cross-browser support for this implemented, but I've never looked for it either, so it's possible that even jQuery has it.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Faced the same problem and solved it by editing my build.gradle file on the dependencies section, removing:

compile 'com.google.android.gms:play-services:7.8.0'

And replacing it with:

compile 'com.google.android.gms:play-services-location:7.8.0'
compile 'com.google.android.gms:play-services-analytics:7.8.0' 

vertical-align image in div

you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-

inline-elements :- <img style="vertical-align:middle" ...>
                   <span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>  

block-elements :- <td style="vertical-align:middle"> ... </td>
                  <div style="display:table-cell; vertical-align:middle"> ... </div>

see the demo:- http://jsfiddle.net/Ewfkk/2/

What are the ways to sum matrix elements in MATLAB?

1)

total = 0;
for i=1:size(A,1)
  for j=1:size(A,2)
    total = total + A(i,j);
  end
end

2)

total = sum(A(:));

How can you profile a Python script?

gprof2dot_magic

Magic function for gprof2dot to profile any Python statement as a DOT graph in JupyterLab or Jupyter Notebook.

enter image description here

GitHub repo: https://github.com/mattijn/gprof2dot_magic

installation

Make sure you've the Python package gprof2dot_magic.

pip install gprof2dot_magic

Its dependencies gprof2dot and graphviz will be installed as well

usage

To enable the magic function, first load the gprof2dot_magic module

%load_ext gprof2dot_magic

and then profile any line statement as a DOT graph as such:

%gprof2dot print('hello world')

enter image description here

How to use the 'main' parameter in package.json?

Just think of it as the "starting point".

In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.

For example

public class IamMain  // when export and require this guy
{
    public IamMain()  // this is "main"
    {...}

    ...   // many others such as function, properties, etc.
}

SET NOCOUNT ON usage

It took me a lot of digging to find real benchmark figures around NOCOUNT, so I figured I'd share a quick summary.

  • If your stored procedure uses a cursor to perform a lot of very quick operations with no returned results, having NOCOUNT OFF can take roughly 10 times as long as having it ON. 1 This is the worst-case scenario.
  • If your stored procedure only performs a single quick operation with no returned results, setting NOCOUNT ON might yield around a 3% performance boost. 2 This would be consistent with a typical insert or update procedure. (See the comments on this answer for some discussion about why this may not always be faster.)
  • If your stored procedure returns results (i.e. you SELECT something), the performance difference will diminish proportionately with the size of the result set.

Return string without trailing slash

This snippet is more accurate:

str.replace(/^(.+?)\/*?$/, "$1");
  1. It not strips / strings, as it's a valid url.
  2. It strips strings with multiple trailing slashes.

Vagrant ssh authentication failure

I tried this on my VM machine

change the permissions /home/vagrant (did a chmod 700 on it)

now i can ssh directly into my boxes

Angular 2 / 4 / 5 not working in IE11

For me with iexplorer 11 and Angular 2 I fixed all those above issues by doing 2 things:

in index.html add:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

in src\polyfills.ts uncomment:

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';

How do I encode and decode a base64 string?

Encode

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

Decode

public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

How to show SVG file on React Native?

you can do this using a simple way

first, you should take installation,

  1. npm install -s react-native-svg
  2. react-native link react-native-svg
  3. npm install -s react-native-svg-transformer

then, you should add the following code in your metro.config.js file

_x000D_
_x000D_
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts }
  } = await getDefaultConfig();
  return {
    transformer: {
      babelTransformerPath: require.resolve("react-native-svg-transformer")
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== "svg"),
      sourceExts: [...sourceExts, "svg"]
    }
  };
})();
_x000D_
_x000D_
_x000D_

after that, you should create a new file in your root directory with the name of declarations.d.js with the following code

_x000D_
_x000D_
declare module "*.svg" {
  import { SvgProps } from "react-native-svg";
  const content: React.FC<SvgProps>;
  export default content;
}
_x000D_
_x000D_
_x000D_

Finally, This is a import mathod

_x000D_
_x000D_
import USER from "../../assets/icons/user.svg"
_x000D_
_x000D_
_x000D_

and, this is for jsx

_x000D_
_x000D_
<USER width="100%" height="100%"/>
_x000D_
_x000D_
_x000D_

Refreshing page on click of a button

Works for every browser.

<button type="button" onClick="Refresh()">Close</button>

<script>
    function Refresh() {
        window.parent.location = window.parent.location.href;
    }
</script>

Send FormData and String Data Together Through JQuery AJAX?

var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
    fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
    fd.append(input.name,input.value);
});
$.ajax({
    url: 'test.php',
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        console.log(data);
    }
});

Added a for loop and changed .serialize() to .serializeArray() for object reference in a .each() to append to the FormData.

Visual C++ executable and missing MSVCR100d.dll

For me the problem appeared in this situation:

I installed VS2012 and did not need VS2010 anymore. I wanted to get my computer clean and also removed the VS2010 runtime executables, thinking that no other program would use it. Then I wanted to test my DLL by attaching it to a program (let's call it program X). I got the same error message. I thought that I did something wrong when compiling the DLL. However, the real problem was that I attached the DLL to program X, and program X was compiled in VS2010 with debug info. That is why the error was thrown. I recompiled program X in VS2012, and the error was gone.

replace special characters in a string python

One way is to use re.sub, that's my preferred way.

import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string

Output:

hey there

Another way is to use re.escape:

import string
import re

my_str = "hey th~!ere"

chars = re.escape(string.punctuation)
print re.sub(r'['+chars+']', '',my_str)

Output:

hey there

Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars

Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]

Clicking submit button of an HTML form by a Javascript code

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:

document.getElementById('loginSubmit').click();

How to trap the backspace key using jQuery?

try this one :

 $('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})  

How do I set headers using python's urllib?

For multiple headers do as follow:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Which Java library provides base64 encoding/decoding?

If you're an Android developer you can use android.util.Base64 class for this purpose.

Connecting to SQL Server using windows authentication

Just replace the first line with the below;

SqlConnection con = new SqlConnection("Server=localhost;Database=employeedetails;Trusted_Connection=True");

Regards.

Convert NSDate to NSString

there are a number of NSDate helpers on the web, I tend to use:

https://github.com/billymeltdown/nsdate-helper/

Readme extract below:

  NSString *displayString = [NSDate stringForDisplayFromDate:date];

This produces the following kinds of output:

‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

As far as I am aware, the MSVCRxxx.dlls are in %SystemRoot%\System32 (usually C:\Windows\System32).

The xxx refers to the version of the MS Visual C Runtime (hence MSVCR...)

However, the complication seems to be that the xxx version is not the same as the two digits of the year "version".

For example, Visual C Runtime 2013 yields MSVCR120.dll and "...Runtime 2012" yields MSVCR110.dll. And then Microsoft packages these as vcredist_x86.exe or vcredist_x64.exe, seemingly irrespective of the xxx version or the Visual Studio version number (2012, 2013 etc) - confused? You have every right to be!

So, firstly, you need to determine whether you need 32 bit, 64 bit or even both (some PHP distributions apparently do need both), then download the relevant vcredist... for the bits AND for the Visual Studio version. As far as I can tell, the only way to tell which vcredist... you have is to start to install it. Recent versions give an intro screen that quotes the Visual Studio version and the xxx version. I have renamed by vcredists to something like vcredist_x64_2012_V11.exe.

[EDIT] Forgot to add earlier that if you are simply looking to "install" the missing DLL (as opposed to resolve some bigger set of issues), then you probably won't do any harm by simply installing the relevant vcredist for your architecture (32 bit, 64 bit) and "missing" version.

How do I start an activity from within a Fragment?

You should do it with getActivity().startActivity(myIntent)

git: How to ignore all present untracked files?

If you want to permanently ignore these files, a simple way to add them to .gitignore is:

  1. Change to the root of the git tree.
  2. git ls-files --others --exclude-standard >> .gitignore

This will enumerate all files inside untracked directories, which may or may not be what you want.

How can I do DNS lookups in Python, including referring to /etc/hosts?

I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

#!/usr/bin/python

def expand_dnsname(dnsname):
    from socket import getaddrinfo
    from dns import reversename, resolver
    namelist = [ ]
    # expand hostname into dict of ip addresses
    iplist = dict()
    for answer in getaddrinfo(dnsname, 80):
        ipa = str(answer[4][0])
        iplist[ipa] = 0
    # run through the list of IP addresses to get hostnames
    for ipaddr in sorted(iplist):
        rev_name = reversename.from_address(ipaddr)
        # run through all the hostnames returned, ignoring the dnsname
        for answer in resolver.query(rev_name, "PTR"):
            name = str(answer)
            if name != dnsname:
                # add it to the list of answers
                namelist.append(name)
                break
    # if no other choice, return the dnsname
    if len(namelist) == 0:
        namelist.append(dnsname)
    # return the sorted namelist
    namelist = sorted(namelist)
    return namelist

namelist = expand_dnsname('google.com.')
for name in namelist:
    print name

Which, when I run it, lists a few 1e100.net hostnames:

C error: undefined reference to function, but it IS defined

I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create, not having point.c will cause the compilation to fail.

I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:

gcc point.c testpoint.c

As others have pointed out, you also need to remove one of your main functions, since you can only have one.

Typescript : Property does not exist on type 'object'

You probably have allProviders typed as object[] as well. And property country does not exist on object. If you don't care about typing, you can declare both allProviders and countryProviders as Array<any>:

let countryProviders: Array<any>;
let allProviders: Array<any>;

If you do want static type checking. You can create an interface for the structure and use it:

interface Provider {
    region: string,
    country: string,
    locale: string,
    company: string
}

let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;

Disable sorting on last column when using jQuery DataTables

Do this in jQuery. The below code works well even if you columns generated automatically or not sure about the column number.

var table = $('#tbl').DataTable({
        "columnDefs": [{ targets: 'no-sort', orderable: false }]});

and add a class 'no-sort' to whatever headers you want to disable sort like this..

<th class="no-sort">Header n</th>

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Get the current fragment object

Try this,

Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);

this will give u the current fragment, then you may compare it to the fragment class and do your stuffs.

    if (currentFragment instanceof NameOfYourFragmentClass) {
     Log.v(TAG, "find the current fragment");
  }

How do I print the type or class of a variable in Swift?

Xcode 7.3.1, Swift 2.2:

String(instanceToPrint.self).componentsSeparatedByString(".").last

android studio 0.4.2: Gradle project sync failed error

Load Project:>Build, execution, Deployment:>(Check on)compiler Independent modules in parllel.

How to manually send HTTP POST requests from Firefox or Chrome browser?

Just to give my 2 cents to this answer, there have been some other clients born since the raise of Postman that worth mentioning here:

How to JSON serialize sets?

I adapted Raymond Hettinger's solution to python 3.

Here is what has changed:

  • unicode disappeared
  • updated the call to the parents' default with super()
  • using base64 to serialize the bytes type into str (because it seems that bytes in python 3 can't be converted to JSON)
from decimal import Decimal
from base64 import b64encode, b64decode
from json import dumps, loads, JSONEncoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, int, float, bool, type(None))):
            return super().default(obj)
        return {'_python_object': b64encode(pickle.dumps(obj)).decode('utf-8')}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(b64decode(dct['_python_object'].encode('utf-8')))
    return dct

data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]
j = dumps(data, cls=PythonObjectEncoder)
print(loads(j, object_hook=as_python_object))
# prints: [1, 2, 3, {'knights', 'who', 'say', 'ni'}, {'key': 'value'}, Decimal('3.14')]

How to copy commits from one branch to another?

Use

git cherry-pick <commit>

to apply <commit> to your current branch.

I myself would probably cross-check the commits I pick in gitk and cherry-pick them with right-clicks on the commit entry there instead.


If you want to go more automatic (with all its dangers) and assuming all commits since yesterday happened on wss you could generate the list of commits using git log (with --pretty suggested by Jefromi)

git log --reverse --since=yesterday --pretty=%H

so everything together assuming you use bash

for commit in $(git log --reverse --since=yesterday --pretty=%H);
do
    git cherry-pick $commit
done

If something goes wrong here (there is a lot of potential) you are in trouble since this works on the live checkout, so either do manual cherry-picks or use rebase like suggested by Jefromi.

How to add parameters to an external data query in Excel which can't be displayed graphically?

If you have Excel 2007 you can write VBA to alter the connections (i.e. the external data queries) in a workbook and update the CommandText property. If you simply add ? where you want a parameter, then next time you refresh the data it'll prompt for the values for the connections! magic. When you look at the properties of the Connection the Parameters button will now be active and useable as normal.

E.g. I'd write a macro, step through it in the debugger, and make it set the CommandText appropriately. Once you've done this you can remove the macro - it's just a means to update the query.

Sub UpdateQuery
    Dim cn As WorkbookConnection
    Dim odbcCn As ODBCConnection, oledbCn As OLEDBConnection
    For Each cn In ThisWorkbook.Connections
        If cn.Type = xlConnectionTypeODBC Then
            Set odbcCn = cn.ODBCConnection

            ' If you do have multiple connections you would want to modify  
            ' the line below each time you run through the loop.
            odbcCn.CommandText = "select blah from someTable where blah like ?"

        ElseIf cn.Type = xlConnectionTypeOLEDB Then
            Set oledbCn = cn.OLEDBConnection
            oledbCn.CommandText = "select blah from someTable where blah like ?" 
        End If
    Next
End Sub