Programs & Examples On #Nonsequential

How to stop C# console applications from closing automatically?

If you do not want the program to close even if a user presses anykey;

 while (true) {
      System.Console.ReadKey();                
 };//This wont stop app

how to change text in Android TextView

:) Your using the thread in a wrong way. Just do the following:

private void runthread()
{

splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized(this){

                        //wait 5 sec
                        wait(_splashTime);
                    }

                } catch(InterruptedException e) {}
                finally {
                    //call the handler to set the text
                }
            }
        };

        splashTread.start(); 
}

That's it.

PHP Create and Save a txt file to root directory

If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.

<?php
  $fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
  $file = fopen($fileLocation,"w");
  $content = "Your text here";
  fwrite($file,$content);
  fclose($file);
?>

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

A primitive type cannot be null. So the solution is replace primitive type with primitive wrapper class in your tableName.java file. Such as:

@Column(nullable=true, name="client_os_id")
private Integer client_os_id;

public int getClient_os_id() {
    return client_os_id;
}

public void setClient_os_id(int clientOsId) {
    client_os_id = clientOsId;
}

reference http://en.wikipedia.org/wiki/Primitive_wrapper_class to find wrapper class of a primivite type.

How can I add a key/value pair to a JavaScript object?

Year 2017 answer: Object.assign()

Object.assign(dest, src1, src2, ...) merges objects.

It overwrites dest with properties and values of (however many) source objects, then returns dest.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Live example

_x000D_
_x000D_
var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});

document.body.innerHTML = JSON.stringify(obj);
_x000D_
_x000D_
_x000D_

Year 2018 answer: object spread operator {...}

obj = {...obj, ...pair};

From MDN:

It copies own enumerable properties from a provided object onto a new object.

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

Note that Object.assign() triggers setters whereas spread syntax doesn’t.

Live example

It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.

_x000D_
_x000D_
var obj = {key1: "value1", key2: "value2"};
var pair = {key3: "value3"};
obj = {...obj, ...pair};

document.body.innerHTML = JSON.stringify(obj);
_x000D_
_x000D_
_x000D_

Year 2019 answer

Object assignment operator +=:

obj += {key3: "value3"};

Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

Span inside anchor or anchor inside span or doesn't matter?

SPAN is a GENERIC inline container. It does not matter whether an a is inside span or span is inside a as both are inline elements. Feel free to do whatever seems logically correct to you.

Difference between innerText, innerHTML and value?

InnerText property html-encodes the content, turning <p> to &lt;p&gt;, etc. If you want to insert HTML tags you need to use InnerHTML.

Using the HTML5 "required" attribute for a group of checkboxes?

Its a simple trick. This is jQuery code that can exploit the html5 validation by changing the required properties if any one is checked. Following is your html code (make sure that you add required for all the elements in the group.)

<input type="checkbox" name="option[]" id="option-1" value="option1" required/> Option 1
<input type="checkbox" name="option[]" id="option-2" value="option2" required/> Option 2
<input type="checkbox" name="option[]" id="option-3" value="option3" required/> Option 3
<input type="checkbox" name="option[]" id="option-4" value="option4" required/> Option 4
<input type="checkbox" name="option[]" id="option-5" value="option5" required/> Option 5

Following is jQuery script, which disables further validation check if any one is selected. Select using name element.

$cbx_group = $("input:checkbox[name='option[]']");
$cbx_group = $("input:checkbox[id^='option-']"); // name is not always helpful ;)

$cbx_group.prop('required', true);
if($cbx_group.is(":checked")){
  $cbx_group.prop('required', false);
}

Small gotcha here: Since you are using html5 validation, make sure you execute this before the it gets validated i.e. before form submit.

// but this might not work as expected
$('form').submit(function(){
  // code goes here
});

// So, better USE THIS INSTEAD:
$('button[type="submit"]').on('click', function() {
  // skipping validation part mentioned above
});

How to find sitemap.xml path on websites?

There is no standard, so there is no guarantee. With that said, its common for the sitemap to be self labeled and on the root, like this:

example.com/sitemap.xml

Case is sensitive on some servers, so keep that in mind. If its not there, look in the robots file on the root:

example.com/robots.txt

If you don't see it listed in the robots file head to Google and search this:

site:example.com filetype:xml

This will limit the results to XML files on your target domain. At this point its trial-and-error and based on the specifics of the website you are working with. If you get several pages of results from the Google search phrase above then try to limit the results further:

filetype:xml site:example.com inurl:sitemap

or

filetype:xml site:example.com inurl:products

If you still can't find it you can right-click > "View Source" and do a search (aka: "control find" or Ctrl + F) for .xml to see if there is a reference to it in the code.

Foreign Key to non-primary key

Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship.

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

Get Path from another app (WhatsApp)

protected void onCreate(Bundle savedInstanceState) { /* * Your OnCreate */ Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType();

//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {viewhekper(intent);//Handle text being sent}

Flash CS4 refuses to let go

Do you have several swf-files? If your class is imported in one of the swf's, other swf's will also use the same version of the class. One old import with * in one swf will do it. Recompile everything and see if it works.

Clone private git repo with dockerfile

Above solutions did not work for bitbucket. I figured this does the trick:

RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts \
    && eval `ssh-agent` \
    && ssh-add ~/.ssh/[key] \
    && git clone [email protected]:[team]/[repo].git

How to bind list to dataGridView?

may be little late but useful for future. if you don't require to set custom properties of cell and only concern with header text and cell value then this code will help you

public class FileName
{        
     [DisplayName("File Name")] 
     public string FileName {get;set;}
     [DisplayName("Value")] 
     public string Value {get;set;}
}

and then you can bind List as datasource as

private void BindGrid()
{
    var filelist = GetFileListOnWebServer().ToList();    
    gvFilesOnServer.DataSource = filelist.ToArray();
}

for further information you can visit this page Bind List of Class objects as Datasource to DataGridView

hope this will help you.

Comparing Class Types in Java

If you don't want to or can't use instanceof, then compare with equals:

 if(obj.getClass().equals(MyObject.class)) System.out.println("true");

BTW - it's strange because the two Class instances in your statement really should be the same, at least in your example code. They may be different if:

  • the classes have the same short name but are defined in different packages
  • the classes have the same full name but are loaded by different classloaders.

SSL Proxy/Charles and Android trouble

for the Android7

refer to: How to get charles proxy work with Android 7 nougat?

for the Android version below Android7

From your computer, run Charles:

  1. Open Proxy Settings: Proxy -> Proxy Settings, Proxies Tab, check "Enable transparent HTTP proxying", and remember "Port" in heart. enter image description here

  2. SSL Proxy Settings:Proxy -> SSL Proxy Settings, SSL Proxying tab, Check “enable SSL Proxying”, and add . to Locations: enter image description here enter image description here

  3. Open Access Control Settings: Proxy -> Access Control Settings. Add your local subnet to authorize machines on you local network to use the proxy from another machine/mobile. enter image description here

In Android Phone:

  1. Configure your mobile: Go to Settings -> Wireless & networks -> WiFi -> Connect or modify your network, fill in the computer IP address and Port(8888): enter image description here

  2. Get Charles SSL Certificate. Visit this url from your mobile browser: http://charlesproxy.com/getssl enter image description here

  3. In “Name the certificate” enter whatever you want

  4. Accept the security warning and install the certificate. If you install it successful, then you probably see sth like that: In your phone, Settings -> Security -> Trusted credentials: enter image description here

Done.

then you can have some test on your mobile, the encrypted https request will be shown in Charles: enter image description here

Working Soap client example

String send = 
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
    "        <soap:Body>\n" +
    "        </soap:Body>\n" +
    "</soap:Envelope>";

private static String getResponse(String send) throws Exception {
    String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint
    String result = "";
    String username="user_name";
    String password="pass_word";
    String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url};
    ProcessBuilder process = new ProcessBuilder(command); 
    Process p;
    try {
        p = process.start();
        BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ( (line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
        }
        result = builder.toString();
    }
    catch (IOException e)
    {   System.out.print("error");
        e.printStackTrace();
    }

    return result;
}

INFO: No Spring WebApplicationInitializer types detected on classpath

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>          
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
 </plugin>

This is the important plugin that should be in pom.xml. I spent my two days debugging and researching. This was the solution. This is Apache plugin to tell maven to use the the given Compiler.

How to convert Moment.js date to users local timezone?

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

How can you debug a CORS request with cURL?

Updated answer that covers most cases

curl -H "Access-Control-Request-Method: GET" -H "Origin: http://localhost" --head http://www.example.com/
  1. Replace http://www.example.com/ with URL you want to test.
  2. If response includes Access-Control-Allow-* then your resource supports CORS.

Rationale for alternative answer

I google this question every now and then and the accepted answer is never what I need. First it prints response body which is a lot of text. Adding --head outputs only headers. Second when testing S3 URLs we need to provide additional header -H "Access-Control-Request-Method: GET".

Hope this will save time.

Error in model.frame.default: variable lengths differ

Its simple, just make sure the data type in your columns are the same. For e.g. I faced the same error, that and an another error:

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

So, I went back to my excel file or csv file, set a filter on the variable throwing me an error and checked if the distinct datatypes are the same. And... Oh! it had numbers and strings, so I converted numbers to string and it worked just fine for me.

Specifying Font and Size in HTML table

First, try omitting the quotes from 12 and 24. Worth a shot.

Second, it's better to do this in CSS. See also http://www.w3schools.com/css/css_font.asp . Here is an inline style for a table tag:

<table style='font-family:"Courier New", Courier, monospace; font-size:80%' ...>...</table>

Better still, use an external style sheet or a style tag near the top of your HTML document. See also http://www.w3schools.com/css/css_howto.asp .

__init__ and arguments in Python

In python you must always pass in at least one argument to class methods, the argument is self and it is not meaningless its a reference to the instance itself

Sending email with gmail smtp with codeigniter email library

You need to enable SSL in your PHP config. Load up php.ini and find a line with the following:

;extension=php_openssl.dll

Uncomment it. :D

(by removing the semicolon from the statement)

extension=php_openssl.dll

simple way to display data in a .txt file on a webpage?

How are you converting the submitted names to "a simple .txt list"? During that step, can you instead convert them into a simple HTML list or table? Then you could wrap that in a standard header which includes any styling you want.

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

You can't. Security stops you for knowing anything about the filing system of the client computer - it may not even have one! It could be a MAC, a PC, a Tablet or an internet enabled fridge - you don't know, can't know and won't know. And letting you have the full path could give you some information about the client - particularly if it is a network drive for example.

In fact you can get it under particular conditions, but it requires an ActiveX control, and will not work in 99.99% of circumstances.

You can't use it to restore the file to the original location anyway (as you have absolutely no control over where downloads are stored, or even if they are stored) so in practice it is not a lot of use to you anyway.

Parsing boolean values with argparse

In addition to what @mgilson said, it should be noted that there's also a ArgumentParser.add_mutually_exclusive_group(required=False) method that would make it trivial to enforce that --flag and --no-flag aren't used at the same time.

String format currency

Use this it works and so simple :

  var price=22.5m;
  Console.WriteLine(
     "the price: {0}",price.ToString("C", new System.Globalization.CultureInfo("en-US")));

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

For Linux there is even a bit better solution.

Navigate to https://developer.android.com/studio/index.html#downloads

and download the command line tools zip file (bottom of the page) for linux. Extract them to your ..../Android/Sdk/ folder so you overrwrite/extend your tools folder. Now everything works fine.

Best way to check for IE less than 9 in JavaScript without library

Below is an improvement over James Padolsey's solution:

1) It doesn't pollute memory (James' snippet creates 7 unremoved document fragments when detecting IE11, for example).
2) It's faster since it checks for a documentMode value before generating markup.
3) It's far more legible, especially to beginning JavaScript programmers.

Gist link: https://gist.github.com/julianshapiro/9098609

/*
 - Behavior: For IE8+, we detect the documentMode value provided by Microsoft.
 - Behavior: For <IE8, we inject conditional comments until we detect a match.
 - Results: In IE, the version is returned. In other browsers, false is returned.
 - Tip: To check for a range of IE versions, use if (!IE || IE < MAX_VERSION)...
*/

var IE = (function() { 
    if (document.documentMode) {
        return document.documentMode;
    } else {
        for (var i = 7; i > 0; i--) {
            var div = document.createElement("div");

            div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";

            if (div.getElementsByTagName("span").length) {
                return i;
            }
        }
    }

    return undefined;
})();

Counting number of words in a file

BufferedReader bf= new BufferedReader(new FileReader("G://Sample.txt"));
        String line=bf.readLine();
        while(line!=null)
        {
            String[] words=line.split(" ");
            System.out.println("this line contains " +words.length+ " words");
            line=bf.readLine();
        }

Getting Git to work with a proxy server - fails with "Request timed out"

As an alternative to using git config --global http.proxy address:port, you can set the proxy on the command line:

git -c "http.proxy=address:port" clone https://...

The advantage is the proxy is not persistently set. Under Bash you might set an alias:

alias git-proxy='git -c "http.proxy=address:port"'

jQuery checkbox checked state changed event

Try this "html-approach" which is acceptable for small JS projects

_x000D_
_x000D_
function msg(animal,is) {
  console.log(animal, is.checked);   // Do stuff
}
_x000D_
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
_x000D_
_x000D_
_x000D_

Modal width (increase)

For responsive answer.

@media (min-width: 992px) {
  .modal-dialog {
    max-width: 80%;
  }
}

How to change the cursor into a hand when a user hovers over a list item?

You can also use the following style:

li {
    cursor: grabbing;
}

YouTube Video Embedded via iframe Ignoring z-index?

Only this one worked for me:

<script type="text/javascript">
var frames = document.getElementsByTagName("iframe");
    for (var i = 0; i < frames.length; i++) {
        src = frames[i].src;
        if (src.indexOf('embed') != -1) {
        if (src.indexOf('?') != -1) {
            frames[i].src += "&wmode=transparent";
        } else {
            frames[i].src += "?wmode=transparent";
        }
    }
}
</script>

I load it in the footer.php Wordpress file. Code found in comment here (thanks Gerson)

Android Studio Run/Debug configuration error: Module not specified

None of the existing answers worked in my case (Android studio 3.5.0). I had to

  1. close all android studio projects
  2. remove the project from the recent projects in android studio wizard
  3. restart android studio
  4. use import option (Import project- Gradle, Eclipse ADT, etc) instead of open an existing project AS project
  5. File -> Sync project with gradle files

Error in strings.xml file in Android

Solution

Apostrophes in the strings.xml should be written as

\'


Example

In my case I had an error with this string in my strings.xml and I fixed it.

<item>Most arguments can be ended with three words, "I don\'t care".</item>

Here you see my app builds properly with that code.

enter image description here

Here is the actual string in my app.

enter image description here

How to define Gradle's home in IDEA?

If you installed gradle with homebrew, then the path is:

/usr/local/Cellar/gradle/X.X/libexec

Where X.X is the version of gradle (currently 2.1)

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

No function matches the given name and argument types

In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.

Move all files except one

I think the easiest way to do is with backticks

mv `ls -1 ~/Linux/Old/ | grep -v Tux.png` ~/Linux/New/

Edit:

Use backslash with ls instead to prevent using it with alias, i.e. mostly ls is aliased as ls --color.

mv `\ls -1 ~/Linux/Old/ | grep -v Tux.png` ~/Linux/New/

Thanks @Arnold Roa

Global npm install location on windows?

Just press windows button and type %APPDATA% and type enter.

Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.

Log4net rolling daily filename with date in the file name

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
  <file value="logs\" />
  <datePattern value="dd.MM.yyyy'.log'" />
  <staticLogFileName value="false" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="5MB" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>

Jquery $.ajax fails in IE on cross domain calls

Could you check if the problem with IE relies on not defining security zones to allow cross domain requests? See this microsoft page for an explanation.

OTOH, this page mentions that IE7 and eariler cannot do cross domain calls, but IE8 can, using a different object than XMLHttpRequest, the one JQuery uses. Could you check if XDomainRequest works?

EDIT (2013-08-22)

The second link is dead, so I'm writing here some of its information, taken from the wayback machine:

XDomainRequest Supported: IE8

Rather than implement the CORS version of XMLHttpRequest, the IE team have gone with there own propriety object, named XDomainRequest. The usage of XDomainRequest has been simplified from XMLHttpRequest, by having more events thrown (with onload perhaps being the most important).

This implementation has a few limitations attached to it. For example, cookies are not sent when using this object, which can be a headache for cookie based sessions on the server side. Also, ContentType can not be set, which poses a problem in ASP.NET and possibly other server side languages (see http://www.actionmonitor.co.uk/NewsItem.aspx?id=5).

var xdr = new XDomainRequest();
xdr.onload = function() { alert("READY"); };
xdr.open("GET", "script.html");
xdr.send();

How do I calculate the date in JavaScript three months prior to today?

In my case I needed to substract 1 month to current date. The important part was the month number, so it doesn't care in which day of the current month you are at, I needed last month. This is my code:

var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)

dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month

//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)

Substract 1 month to actual date it's not accurate, that's why in first place I set first day of the month (first day of any month always is first day) and in second place I substract 1 day, which always send you to last month. Hope to help you dude.

_x000D_
_x000D_
var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object_x000D_
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)_x000D_
_x000D_
dateObj.setDate(1); //Set first day of the month from current date_x000D_
dateObj.setDate(-1); // Substract 1 day to the first day of the month_x000D_
_x000D_
//Now, you are in the last month_x000D_
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)
_x000D_
_x000D_
_x000D_

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

From Now() to Current_timestamp in Postgresql

Here is what the MySQL docs say about NOW():

Returns the current date and time as a value in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.

mysql> SELECT NOW();
        -> '2007-12-15 23:50:26'
mysql> SELECT NOW() + 0;
        -> 20071215235026.000000

Now, you can certainly reduce your smart date to something less...

SELECT (
 date_part('year', NOW())::text
 || date_part('month', NOW())::text
 || date_part('day', NOW())::text
 || date_part('hour', NOW())::text
 || date_part('minute', NOW())::text
 || date_part('second', NOW())::text
)::float8 + foo;

But, that would be a really bad idea, what you need to understand is that times and dates are not stupid unformated numbers, they are their own type with their own set of functions and operators

So the MySQL time essentially lets you treat NOW() as a dumber type, or it overrides + to make a presumption that I can't find in the MySQL docs. Eitherway, you probably want to look at the date and interval types in pg.

Jenkins Git Plugin: How to build specific tag?

None of these answers were sufficient for me, using Jenkins CI v.1.555, Git Client plugin v.1.6.4, and Git plugin 2.0.4.

I wanted a job to build for one Git repository for one specific, fixed (i.e., non-parameterized) tag. I had to cobble together a solution from the various answers plus the "build a Git tag" blog post cited by Thilo.

  1. Make sure you push your tag to the remote repository with git push --tags
  2. In the "Git Repository" section of your job, under the "Source Code Management" heading, click "Advanced".
  3. In the field for Refspec, add the following text: +refs/tags/*:refs/remotes/origin/tags/*
  4. Under "Branches to build", "Branch specifier", put */tags/<TAG_TO_BUILD> (replacing <TAG_TO_BUILD> with your actual tag name).

Adding the Refspec for me turned out to be critical. Although it seemed the git repositories were fetching all the remote information by default when I left it blank, the Git plugin would nevertheless completely fail to find my tag. Only when I explicitly specified "get the remote tags" in the Refspec field was the Git plugin able to identify and build from my tag.

Update 2014-5-7: Unfortunately, this solution does come with an undesirable side-effect for Jenkins CI (v.1.555) and the Git repository push notification mechanism à la Stash Webhook to Jenkins: any time any branch on the repository is updated in a push, the tag build jobs will also fire again. This leads to a lot of unnecessary re-builds of the same tag jobs over and over again. I have tried configuring the jobs both with and without the "Force polling using workspace" option, and it seemed to have no effect. The only way I could prevent Jenkins from making the unnecessary builds for the tag jobs is to clear the Refspec field (i.e., delete the +refs/tags/*:refs/remotes/origin/tags/*).

If anyone finds a more elegant solution, please edit this answer with an update. I suspect, for example, that maybe this wouldn't happen if the refspec specifically was +refs/tags/<TAG TO BUILD>:refs/remotes/origin/tags/<TAG TO BUILD> rather than the asterisk catch-all. For now, however, this solution is working for us, we just remove the extra Refspec after the job succeeds.

Checking letter case (Upper/Lower) within a string in Java

package passwordValidator;

import java.util.Scanner;

public class Main {
    /**
     * @author felipe mello.
     */

    private static Scanner scanner = new Scanner(System.in);

     /*
     * Create a password validator(from an input string) via TDD
     * The validator should return true if
     *  The Password is at least 8 characters long
     *  The Password contains uppercase Letters(atLeastOne)
     *  The Password contains digits(at least one)
     *  The Password contains symbols(at least one)
     */


    public static void main(String[] args) {
        System.out.println("Please enter a password");
        String password = scanner.nextLine();   

        checkPassword(password);
    }
    /**
     * 
     * @param checkPassword the method check password is validating the input from the the user and check if it matches the password requirements
     * @return
     */
    public static boolean checkPassword(String password){
        boolean upperCase = !password.equals(password.toLowerCase()); //check if the input has a lower case letter
        boolean lowerCase = !password.equals(password.toUpperCase()); //check if the input has a CAPITAL case letter
        boolean isAtLeast8 = password.length()>=8;                    //check if the input is greater than 8 characters
        boolean hasSpecial = !password.matches("[A-Za-z0-9]*");       // check if the input has a special characters
        boolean hasNumber = !password.matches(".*\\d+.*");            //check if the input contains a digit
        if(!isAtLeast8){
            System.out.println("Your Password is not big enough\n please enter a password with minimun of 8 characters");
            return true;
        }else if(!upperCase){
            System.out.println("Password must contain at least one UPPERCASE letter");
            return true;
        }else if(!lowerCase){
            System.out.println("Password must contain at least one lower case letter");
            return true;
        }else if(!hasSpecial){
            System.out.println("Password must contain a special character");
            return true;
        }else if(hasNumber){
            System.out.println("Password must contain at least one number");
            return true;
        }else{
            System.out.println("Your password: "+password+", sucessfully match the requirements");
            return true;
        }

    }
}

What is useState() in React?

useState() is an example built-in React hook that lets you use states in your functional components. This was not possible before React 16.7.

The useState function is a built in hook that can be imported from the react package. It allows you to add state to your functional components. Using the useState hook inside a function component, you can create a piece of state without switching to class components.

C: What is the difference between ++i and i++?

The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.

In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.

However, you should consider two main problems with the preceding logic.

  1. Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.

  2. In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.

In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.

This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Linq code to select one item

Depends how much you like the linq query syntax, you can use the extension methods directly like:

var item = Items.First(i => i.Id == 123);

And if you don't want to throw an error if the list is empty, use FirstOrDefault which returns the default value for the element type (null for reference types):

var item = Items.FirstOrDefault(i => i.Id == 123);

if (item != null)
{
    // found it
}

Single() and SingleOrDefault() can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First() and FirstOrDefault() stop on the first match, so they are more efficient.

Of the First() and Single() family, here's where they throw:

  • First() - throws if empty/not found, does not throw if duplicate
  • FirstOrDefault() - returns default if empty/not found, does not throw if duplicate
  • Single() - throws if empty/not found, throws if duplicate exists
  • SingleOrDefault() - returns default if empty/not found, throws if duplicate exists

Composer Update Laravel

When you run composer update, composer generates a file called composer.lock which lists all your packages and the currently installed versions. This allows you to later run composer install, which will install the packages listed in that file, recreating the environment that you were last using.

It appears from your log that some of the versions of packages that are listed in your composer.lock file are no longer available. Thus, when you run composer install, it complains and fails. This is usually no big deal - just run composer update and it will attempt to build a set of packages that work together and write a new composer.lock file.

However, you're running into a different problem. It appears that, in your composer.json file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate command. This can be avoided by running the following: composer update --no-scripts

This will run the composer update but will skip over the scripts added to the file. You should be able to successfully run the update this way.

However, this does not solve the problem long-term. There are two problems:

  1. A migration is for database changes, not random stuff like compiling assets. Go through the migrations and remove that code from there.

  2. Assets should not be compiled each time you run composer update. Remove that step from the composer.json file.

From what I've read, best practice seems to be compiling assets on an as-needed basis during development (ie. when you're making changes to your LESS files - ideally using a tool like gulp.js) and before deployment.

Cordova - Error code 1 for command | Command failed for

I removed android platforms and installed again then worked. I wrote these lines in command window:

cordova platform remove android
then
cordova platform add android

How to add Python to Windows registry

I installed ArcGIS Pro 1.4 and it didn't register the Python 3.5.2 it installed which prevented me from installing any add-ons. I resolved this by using the "reg" command in an Administrator PowerShell session to manually create and populate the necessary registry keys/values (where Python is installed in C:\Python35):

reg add "HKLM\Software\Python\PythonCore\3.5\Help\Main Python Documentation" /reg:64 /ve /t REG_SZ /d "C:\Python35\Doc\Python352.chm"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath\InstallGroup" /reg:64 /ve /t REG_SZ /d "Python 3.5"
reg add "HKLM\Software\Python\PythonCore\3.5\PythonPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\Lib;C:\Python35\DLLs;C:\Python35\Lib\lib-tk"

I find this easier than using Registry Editor but that's solely a personal preference.

The same commands can be executed in CMD.EXE session if you prefer; just make sure you run it as Administrator.

What's the difference between Unicode and UTF-8?

UTF-16 and UTF-8 are both encodings of Unicode. They are both Unicode; one is not more Unicode than the other.

Don't let an unfortunate historical artifact from Microsoft confuse you.

Determine if two rectangles overlap each other?

Lets say the two rectangles are rectangle A and rectangle B. Let their centers be A1 and B1 (coordinates of A1 and B1 can be easily found out), let the heights be Ha and Hb, width be Wa and Wb, let dx be the width(x) distance between A1 and B1 and dy be the height(y) distance between A1 and B1.

Now we can say we can say A and B overlap: when

if(!(dx > Wa+Wb)||!(dy > Ha+Hb)) returns true

Identifier not found error on function call

Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:

void swapCase(char *name);

or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.

How to modify list entries during for loop?

No you wouldn't alter the "content" of the list, if you could mutate strings that way. But in Python they are not mutable. Any string operation returns a new string.

If you had a list of objects you knew were mutable, you could do this as long as you don't change the actual contents of the list.

Thus you will need to do a map of some sort. If you use a generator expression it [the operation] will be done as you iterate and you will save memory.

How to add some non-standard font to a website?

It looks like it only works in Internet Explorer, but a quick Google search for "html embed fonts" yields http://www.spoono.com/html/tutorials/tutorial.php?id=19

If you want to stay platform-agnostic (and you should!) you'll have to use images, or else just use a standard font.

Home does not contain an export named Home

This is a case where you mixed up default exports and named exports.

When dealing with the named exports, if you try to import them you should use curly braces as below,

import { Home } from './layouts/Home'; // if the Home is a named export

In your case the Home was exported as a default one. This is the one that will get imported from the module, when you don’t specify a certain name of a certain piece of code. When you import, and omit the curly braces, it will look for the default export in the module you’re importing from. So your import should be,

import Home from './layouts/Home'; // if the Home is a default export

Some references to look :

How do I find files that do not contain a given string pattern?

grep -irnw "filepath" -ve "pattern"

or

grep -ve "pattern" < file

above command will give us the result as -v finds the inverse of the pattern being searched

How to update a record using sequelize for node?

hi to update the record it very simple

  1. sequelize find the record by ID (or by what you want)
  2. then you pass the params with result.feild = updatedField
  3. if the record doesn'texist in database sequelize create a new record with the params
  4. watch the exemple for more understand Code #1 test that code for all version under V4
const sequelizeModel = require("../models/sequelizeModel");
    const id = req.params.id;
            sequelizeModel.findAll(id)
            .then((result)=>{
                result.name = updatedName;
                result.lastname = updatedLastname;
                result.price = updatedPrice;
                result.tele = updatedTele;
                return result.save()
            })
            .then((result)=>{
                    console.log("the data was Updated");
                })
            .catch((err)=>{
                console.log("Error : ",err)
            });

Code for V5

const id = req.params.id;
            const name = req.body.name;
            const lastname = req.body.lastname;
            const tele = req.body.tele;
            const price = req.body.price;
    StudentWork.update(
        {
            name        : name,
            lastname    : lastname,
            tele        : tele,
            price       : price
        },
        {returning: true, where: {id: id} }
      )
            .then((result)=>{
                console.log("data was Updated");
                res.redirect('/');
            })
    .catch((err)=>{
        console.log("Error : ",err)
    });

How to upgrade Python version to 3.7?

Try this if you are on ubuntu:

sudo apt-get update
sudo apt-get install build-essential libpq-dev libssl-dev openssl libffi-dev zlib1g-dev
sudo apt-get install python3-pip python3.7-dev
sudo apt-get install python3.7

In case you don't have the repository and so it fires a not-found package you first have to install this:

sudo apt-get install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update

more info here: http://devopspy.com/python/install-python-3-6-ubuntu-lts/

Generate MD5 hash string with T-SQL

For data up to 8000 characters use:

CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)

Demo

For binary data (without the limit of 8000 bytes) use:

CONVERT(VARCHAR(32), master.sys.fn_repl_hash_binary(@binary_data), 2)

Demo

How to write a JSON file in C#?

The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.

The following adds basic JSON indentation:

 string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);

React JS onClick event handler

You can make use of the React.createClone method. Create your element, than create a clone of it. During the clone's creation, you can inject props. Inject an onClick : method prop like this

{ onClick : () => this.changeColor(originalElement, index) }

the changeColor method will set the state with the duplicate, allowing you sto set the color in the process.

_x000D_
_x000D_
render()_x000D_
  {_x000D_
    return(_x000D_
      <ul>_x000D_
_x000D_
        {this.state.items.map((val, ind) => {_x000D_
          let item = <li key={ind}>{val}</li>;_x000D_
          let props = { _x000D_
            onClick: () => this.Click(item, ind),_x000D_
            key : ind,_x000D_
            ind_x000D_
          }_x000D_
          let clone = React.cloneElement(item, props, [val]);_x000D_
          return clone;_x000D_
        })}_x000D_
_x000D_
      </ul>_x000D_
    )_x000D_
  }
_x000D_
_x000D_
_x000D_

how to convert a string date into datetime format in python?

You should use datetime.datetime.strptime:

import datetime

dt = datetime.datetime.strptime(string_date, fmt)

fmt will need to be the appropriate format for your string. You'll find the reference on how to build your format here.

exclude @Component from @ComponentScan

I had an issue when using @Configuration, @EnableAutoConfiguration and @ComponentScan while trying to exclude specific configuration classes, the thing is it didn't work!

Eventually I solved the problem by using @SpringBootApplication, which according to Spring documentation does the same functionality as the three above in one annotation.

Another Tip is to try first without refining your package scan (without the basePackages filter).

@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}

Nested iframes, AKA Iframe Inception

I guess your problem is that jQuery is not loaded in your iframes.

The safest approach is to rely on pure DOM-based methods to parse your content.

Or else, start with jQuery, and then once inside your iframes, test once if typeof window.jQuery == 'undefined', if it's true, jQuery is not enabled inside it and fallback on DOM-based method.

Selenium Webdriver: Entering text into text field

I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.

import org.openqa.selenium.Keys;

String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);

element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field

I hope it helps..

How to reposition Chrome Developer Tools

After I have placed my dock to the right (see older answers), I still found the panels split vertically.

To split the panels horizontally - and even got more from your screen width - go to Settings (bottom right corner), and remove the check on 'Split panels vertically when docked to right'.

Now, you have all panels from left to right :p

Reading file input from a multipart/form-data POST

How about some Regex?

I wrote this for a text a file, but I believe this could work for you

(In case your text file contains line starting exactly with the "matched" ones below - simply adapt your Regex)

    private static List<string> fileUploadRequestParser(Stream stream)
    {
        //-----------------------------111111111111111
        //Content-Disposition: form-data; name="file"; filename="data.txt"
        //Content-Type: text/plain
        //...
        //...
        //-----------------------------111111111111111
        //Content-Disposition: form-data; name="submit"
        //Submit
        //-----------------------------111111111111111--

        List<String> lstLines = new List<string>();
        TextReader textReader = new StreamReader(stream);
        string sLine = textReader.ReadLine();
        Regex regex = new Regex("(^-+)|(^content-)|(^$)|(^submit)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);

        while (sLine != null)
        {
            if (!regex.Match(sLine).Success)
            {
                lstLines.Add(sLine);
            }
            sLine = textReader.ReadLine();
        }

        return lstLines;
    }

Auto-expanding layout with Qt-Designer

After creating your QVBoxLayout in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout should now stretch to fit the window and will resize automatically when the entire window is resized.

Get the value in an input text box

To get the textbox value, you can use the jQuery val() function.

For example,

$('input:textbox').val() – Get textbox value.

$('input:textbox').val("new text message") – Set the textbox value.

How to install trusted CA certificate on Android device?

There is a MUCH easier solution to this than posted here, or in related threads. If you are using a webview (as I am), you can achieve this by executing a JAVASCRIPT function within it. If you are not using a webview, you might want to create a hidden one for this purpose. Here's a function that works in just about any browser (or webview) to kickoff ca installation (generally through the shared os cert repository, including on a Droid). It uses a nice trick with iFrames. Just pass the url to a .crt file to this function:

function installTrustedRootCert( rootCertUrl ){
    id = "rootCertInstaller";
    iframe = document.getElementById( id );
    if( iframe != null ) document.body.removeChild( iframe );
    iframe = document.createElement( "iframe" );
    iframe.id = id;
    iframe.style.display = "none";
    document.body.appendChild( iframe );
    iframe.src = rootCertUrl;
}

UPDATE:

The iframe trick works on Droids with API 19 and up, but older versions of the webview won't work like this. The general idea still works though - just download/open the file with a webview and then let the os take over. This may be an easier and more universal solution (in the actual java now):

 public static void installTrustedRootCert( final String certAddress ){
     WebView certWebView = new WebView( instance_ );
     certWebView.loadUrl( certAddress );
 }

Note that instance_ is a reference to the Activity. This works perfectly if you know the url to the cert. In my case, however, I resolve that dynamically with the server side software. I had to add a fair amount of additional code to intercept a redirection url and call this in a manner which did not cause a crash based on a threading complication, but I won't add all that confusion here...

How to append multiple items in one line in Python

mylist = [1,2,3]

def multiple_appends(listname, *element):
    listname.extend(element)

multiple_appends(mylist, 4, 5, "string", False)
print(mylist)

OUTPUT:

[1, 2, 3, 4, 5, 'string', False]

Why does 2 mod 4 = 2?

mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.

Use custom build output folder when using create-react-app

Based on the answers by Ben Carp and Wallace Sidhrée:

This is what I use to copy my entire build folder to my wamp public folder.

package.json

{
  "name": "[your project name]",
  "homepage": "http://localhost/[your project name]/",
  "version": "0.0.1",
  [...]
  "scripts": {
    "build": "react-scripts build",
    "postbuild": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./post_build.ps1",
    [...]
  },
}

post_build.ps1

Copy-Item "./build/*" -Destination "C:/wamp64/www/[your project name]" -Recurse -force

The homepage line is only needed if you are deploying to a subfolder on your server (See This answer from another question).

Find where python is installed (if it isn't default dir)

For Windows Users:

If the python command is not in your $PATH environment var.

Open PowerShell and run these commands to find the folder

cd \
ls *ython* -Recurse -Directory

That should tell you where python is installed

mysql stored-procedure: out parameter

I just tried to call a function in terminal rather then MySQL Query Browser and it works. So, it looks like I'm doing something wrong in that program...

I don't know what since I called some procedures before successfully (but there where no out parameters)...

For this one I had entered

CALL my_sqrt(4,@out_value);
SELECT @out_value;

And it results with an error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @out_value' at line 2

Strangely, if I write just:

CALL my_sqrt(4,@out_value); 

The result message is: "Query canceled"

I guess, for now I will use only terminal...

How to set up file permissions for Laravel?

For Laravel developers, directory issues can be a little bit pain. In my application, I was creating directories on the fly and moving files to this directory in my local environment successfully. Then on server, I was getting errors while moving files to newly created directory.

Here are the things that I have done and got a successful result at the end.

  1. sudo find /path/to/your/laravel/root/directory -type f -exec chmod 664 {} \;
    sudo find /path/to/your/laravel/root/directory -type d -exec chmod 775 {} \;
  2. chcon -Rt httpd_sys_content_rw_t /path/to/my/file/upload/directory/in/laravel/project/
  3. While creating the new directory on the fly, I used the command mkdir($save_path, 0755, true);

After making those changes on production server, I successfully created new directories and move files to them.

Finally, if you use File facade in Laravel you can do something like this: File::makeDirectory($save_path, 0755, true);

Javascript add leading zeroes to date

 let date = new Date();
 let dd = date.getDate();//day of month

 let mm = date.getMonth();// month
 let yyyy = date.getFullYear();//day of week
 if (dd < 10) {//if less then 10 add a leading zero
     dd = "0" + dd;
   }
 if (mm < 10) {
    mm = "0" + mm;//if less then 10 add a leading zero
  }

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Convert tuple to list and back

Why don't you try converting its type from a tuple to a list and vice versa.

level1 = (
     (1,1,1,1,1,1)
     (1,0,0,0,0,1)
     (1,0,0,0,0,1)
     (1,0,0,0,0,1)
     (1,0,0,0,0,1)
     (1,1,1,1,1,1))

print(level1)

level1 = list(level1)

print(level1)

level1 = tuple(level1)

print(level1)

How to access a dictionary element in a Django template?

To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object:

class Choice(models.Model):
    text = models.CharField(max_length=200)

    def calculateVotes(self):
        return Vote.objects.filter(choice=self).count()

    votes = property(calculateVotes)

And then in your template, you can do:

{% for choice in choices %}
    {{choice.choice}} - {{choice.votes}} <br />
{% endfor %}

The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa.

I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.

Int or Number DataType for DataAnnotation validation attribute

ASP.NET Core 3.1

This is my implementation of the feature, it works on server side as well as with jquery validation unobtrusive with a custom error message just like any other attribute:

The attribute:

  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
    {
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
        }

        public override bool IsValid(object value)
        {
            return int.TryParse(value?.ToString() ?? "", out int newVal);
        }

        private bool MergeAttribute(
              IDictionary<string, string> attributes,
              string key,
              string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }

Client side logic:

$.validator.addMethod("mustbeinteger",
    function (value, element, parameters) {
        return !isNaN(parseInt(value)) && isFinite(value);
    });

$.validator.unobtrusive.adapters.add("mustbeinteger", [], function (options) {
    options.rules.mustbeinteger = {};
    options.messages["mustbeinteger"] = options.message;
});

And finally the Usage:

 [MustBeInteger(ErrorMessage = "You must provide a valid number")]
 public int SomeNumber { get; set; }

javascript window.location in new tab

This works for me on Chrome 53. Haven't tested anywhere else:

function navigate(href, newTab) {
   var a = document.createElement('a');
   a.href = href;
   if (newTab) {
      a.setAttribute('target', '_blank');
   }
   a.click();
}

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

How to make overlay control above all other controls?

If you are using a Canvas or Grid in your layout, give the control to be put on top a higher ZIndex.

From MSDN:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowTitle="ZIndex Sample">
  <Canvas>
    <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="100" Canvas.Left="100" Fill="blue"/>
    <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="150" Canvas.Left="150" Fill="yellow"/>
    <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="200" Canvas.Left="200" Fill="green"/>

    <!-- Reverse the order to illustrate z-index property -->

    <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="300" Canvas.Left="200" Fill="green"/>
    <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="350" Canvas.Left="150" Fill="yellow"/>
    <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="400" Canvas.Left="100" Fill="blue"/>
  </Canvas>
</Page>

If you don't specify ZIndex, the children of a panel are rendered in the order they are specified (i.e. last one on top).

If you are looking to do something more complicated, you can look at how ChildWindow is implemented in Silverlight. It overlays a semitransparent background and popup over your entire RootVisual.

Position of a string within a string using Linux shell script?

You can use grep to get the byte-offset of the matching part of a string:

echo $str | grep -b -o str

As per your example:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat

you can pipe that to awk if you just want the first part

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'

CSS Circular Cropping of Rectangle Image

The best way I've been able to do this is with using the new css object-fit (1) property and the padding-bottom (2) hack.

You need a wrapper element around the image. You can use whatever you want, but I like using the new HTML picture tag.

_x000D_
_x000D_
.rounded {
  display: block;
  width: 100%;
  height: 0;
  padding-bottom: 100%;
  border-radius: 50%;
  overflow: hidden;
}

.rounded img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


/* These classes just used for demo */
.w25 {
  width: 25%;
}

.w50 {
  width: 50%;
}
_x000D_
<div class="w25">
<picture class="rounded">
  <img src="https://i.imgur.com/A8eQsll.jpg">
</picture>
</div>

<!-- example using a div -->
<div class="w50">
<div class="rounded">
  <img src="https://i.imgur.com/A8eQsll.jpg">
</div>
</div>

<picture class="rounded">
  <img src="https://i.imgur.com/A8eQsll.jpg">
</picture>
_x000D_
_x000D_
_x000D_

References

  1. CSS Image size, how to fill, not stretch?

  2. Maintain the aspect ratio of a div with CSS

Internal Error 500 Apache, but nothing in the logs?

Please check if you are disable error reporting somewhere in your code.

There was a place in my code where I have disabled it, so I added the debug code after it:

require_once("inc/req.php");   <-- Error reporting is disabled here

// overwrite it
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

How to view user privileges using windows cmd?

I'd start with:

secedit /export /areas USER_RIGHTS /cfg OUTFILE.CFG

Then examine the line for the relevant privilege. However, the problem now is that the accounts are listed as SIDs, not usernames.

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

For anybody who is getting an error like : '2*' string cannot be converted to Length.

<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" /><!--This will make any control in this column of grid take 2/5 of total width-->
        <ColumnDefinition Width="3*" /><!--This will make any control in this column of grid take 3/5 of total width-->
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition MinHeight="30" />
    </Grid.RowDefinitions>

    <TextBlock Grid.Column="0" Grid.Row="0">Your text block a:</TextBlock>
    <TextBlock Grid.Column="1" Grid.Row="0">Your text block b:</TextBlock>
</Grid>

nodemon not working: -bash: nodemon: command not found

From you own project.

npx nodemon [your-app.js]

With a local installation, nodemon will not be available in your system path. Instead, the local installation of nodemon can be run by calling it from within an npm script (such as npm start) or using npx nodemon.

OR

Create a simple symbolik link

ln -s /Users/YourUsername/.npm-global/bin/nodemon /usr/local/bin

ln -s [from: where is you install 'nodemon'] [to: folder where are general module for node]

node : v12.1.0

npm : 6.9.0

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Select statement to find duplicates on certain fields

You mention "the first one", so I assume that you have some kind of ordering on your data. Let's assume that your data is ordered by some field ID.

This SQL should get you the duplicate entries except for the first one. It basically selects all rows for which another row with (a) the same fields and (b) a lower ID exists. Performance won't be great, but it might solve your problem.

SELECT A.ID, A.field1, A.field2, A.field3
  FROM myTable A
 WHERE EXISTS (SELECT B.ID
                 FROM myTable B
                WHERE B.field1 = A.field1
                  AND B.field2 = A.field2
                  AND B.field3 = A.field3
                  AND B.ID < A.ID)

AngularJs: How to check for changes in file input fields?

No binding support for File Upload control

https://github.com/angular/angular.js/issues/1375

<div ng-controller="form-cntlr">
        <form>
             <button ng-click="selectFile()">Upload Your File</button>
             <input type="file" style="display:none" 
                id="file" name='file' onchange="angular.element(this).scope().fileNameChanged(this)" />
        </form>  
    </div>

instead of

 <input type="file" style="display:none" 
    id="file" name='file' ng-Change="fileNameChanged()" />

can you try

<input type="file" style="display:none" 
    id="file" name='file' onchange="angular.element(this).scope().fileNameChanged()" />

Note: this requires the angular application to always be in debug mode. This will not work in production code if debug mode is disabled.

and in your function changes instead of

$scope.fileNameChanged = function() {
   alert("select file");
}

can you try

$scope.fileNameChanged = function() {
  console.log("select file");
}

Below is one working example of file upload with drag drop file upload may be helpful http://jsfiddle.net/danielzen/utp7j/

Angular File Upload Information

URL for AngularJS File Upload in ASP.Net

http://cgeers.com/2013/05/03/angularjs-file-upload/

AngularJs native multi-file upload with progress with NodeJS

http://jasonturim.wordpress.com/2013/09/12/angularjs-native-multi-file-upload-with-progress/

ngUpload - An AngularJS Service for uploading files using iframe

http://ngmodules.org/modules/ngUpload

Is it valid to replace http:// with // in a <script src="http://...">?

Here I duplicate the answer in Hidden features of HTML:

Using a protocol-independent absolute path:

<img src="//domain.com/img/logo.png"/>

If the browser is viewing an page in SSL through HTTPS, then it'll request that asset with the https protocol, otherwise it'll request it with HTTP.

This prevents that awful "This Page Contains Both Secure and Non-Secure Items" error message in IE, keeping all your asset requests within the same protocol.

Caveat: When used on a <link> or @import for a stylesheet, IE7 and IE8 download the file twice. All other uses, however, are just fine.

Can I scroll a ScrollView programmatically in Android?

I got this to work to scroll to the bottom of a ScrollView (with a TextView inside):

(I put this on a method that updates the TextView)

final ScrollView myScrollView = (ScrollView) findViewById(R.id.myScroller);
    myScrollView.post(new Runnable() {
    public void run() {
        myScrollView.fullScroll(View.FOCUS_DOWN);
    }
});

How do you upload a file to a document library in sharepoint?

if you get this error "Value does not fall within the expected range" in this line:

SPFolder myLibrary = oWeb.Folders[documentLibraryName];

use instead this to fix the error:

SPFolder myLibrary = oWeb.GetList(URL OR NAME).RootFolder;

Use always URl to get Lists or others because they are unique, names are not the best way ;)

Using Custom Domains With IIS Express

David's solution is good. But I found the <script>alert(document.domain);</script> in the page still alerts "localhost" because the Project Url is still localhost even if it has been override with http://dev.example.com. Another issue I run into is that it alerts me the port 80 has already been in use even if I have disabled the Skype using the 80 port number as recommended by David Murdoch. So I have figured out another solution that is much easier:

  1. Run Notepad as administrator, and open the C:\Windows\System32\drivers\etc\hosts, add 127.0.0.1 mydomain, and save the file;
  2. Open the web project with Visual Studio 2013 (Note: must also run as administrator), right-click the project -> Properties -> Web, (lets suppose the Project Url under the "IIS Express" option is http://localhost:33333/), then change it from http://localhost:33333/ to http://mydomain:333333/ Note: After this change, you should neither click the "Create Virtual Directory" button on the right of the Project Url box nor click the Save button of the Visual Studio as they won't be succeeded. You can save your settings after next step 3.
  3. Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config, search for "33333:localhost", then update it to "33333:mydomain" and save the file.
  4. Save your setting as mentioned in step 2.
  5. Right click a web page in your visual studio, and click "View in Browser". Now the page will be opened under http://mydomain:333333/, and <script>alert(document.domain);</script> in the page will alert "mydomain".

Note: The port number listed above is assumed to be 33333. You need to change it to the port number set by your visual studio.

Post edited: Today I tried with another domain name and got the following error: Unable to launch the IIS Express Web server. Failed to register URL... Access is denied. (0x80070005). I exit the IIS Express by right clicking the IIS Express icon at the right corner in the Windows task bar, and then re-start my visual studio as administrator, and the issue is gone.

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

Node.js - get raw request body using Express

Use body-parser Parse the body with what it will be:

app.use(bodyParser.text());

app.use(bodyParser.urlencoded());

app.use(bodyParser.raw());

app.use(bodyParser.json());

ie. If you are supposed to get raw text file, run .text().

Thats what body-parser currently supports

How to count the frequency of the elements in an unordered list?

Simple solution using a dictionary.

def frequency(l):
     d = {}
     for i in l:
        if i in d.keys():
           d[i] += 1
        else:
           d[i] = 1

     for k, v in d.iteritems():
        if v ==max (d.values()):
           return k,d.keys()

print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))

Android EditText view Floating Hint in Material Design

Use the TextInputLayout provided by the Material Components Library:

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Label">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </com.google.android.material.textfield.TextInputLayout>

enter image description here

Pretty-print an entire Pandas Series / DataFrame

Try using display() function. This would automatically use Horizontal and vertical scroll bars and with this you can display different datasets easily instead of using print().

display(dataframe)

display() supports proper alignment also.

However if you want to make the dataset more beautiful you can check pd.option_context(). It has lot of options to clearly show the dataframe.

Note - I am using Jupyter Notebooks.

JavaScript private methods

Private functions cannot access the public variables using module pattern

SELECT with a Replace()

This will work:

SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'

Laravel Eloquent "WHERE NOT IN"

$created_po = array();
     $challan = modelname::where('fieldname','!=', 0)->get();
     // dd($challan);
     foreach ($challan as $rec){
         $created_po[] = array_push($created_po,$rec->fieldname);
     }
     $data = modelname::whereNotIn('fieldname',$created_po)->orderBy('fieldname','desc')->with('modelfunction')->get();

How to resize an Image C#

You can use the Accord.NET framework for this. It provides a few different methods of resizing:

Regular expression for letters, numbers and - _

To actually cover your pattern, i.e, valid file names according to your rules, I think that you need a little more. Note this doesn't match legal file names from a system perspective. That would be system dependent and more liberal in what it accepts. This is intended to match your acceptable patterns.

^([a-zA-Z0-9]+[_-])*[a-zA-Z0-9]+\.[a-zA-Z0-9]+$

Explanation:

  • ^ Match the start of a string. This (plus the end match) forces the string to conform to the exact expression, not merely contain a substring matching the expression.
  • ([a-zA-Z0-9]+[_-])* Zero or more occurrences of one or more letters or numbers followed by an underscore or dash. This causes all names that contain a dash or underscore to have letters or numbers between them.
  • [a-zA-Z0-9]+ One or more letters or numbers. This covers all names that do not contain an underscore or a dash.
  • \. A literal period (dot). Forces the file name to have an extension and, by exclusion from the rest of the pattern, only allow the period to be used between the name and the extension. If you want more than one extension that could be handled as well using the same technique as for the dash/underscore, just at the end.
  • [a-zA-Z0-9]+ One or more letters or numbers. The extension must be at least one character long and must contain only letters and numbers. This is typical, but if you wanted allow underscores, that could be addressed as well. You could also supply a length range {2,3} instead of the one or more + matcher, if that were more appropriate.
  • $ Match the end of the string. See the starting character.

Convert string to integer type in Go?

Converting Simple strings

The easiest way is to use the strconv.Atoi() function.

Note that there are many other ways. For example fmt.Sscan() and strconv.ParseInt() which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi():

Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

Here's an example using the mentioned functions (try it on the Go Playground):

flag.Parse()
s := flag.Arg(0)

if i, err := strconv.Atoi(s); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

if i, err := strconv.ParseInt(s, 10, 64); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

var i int
if _, err := fmt.Sscan(s, &i); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

Output (if called with argument "123"):

i=123, type: int
i=123, type: int64
i=123, type: int

Parsing Custom strings

There is also a handy fmt.Sscanf() which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the input string.

This is great for parsing custom strings holding a number. For example if your input is provided in a form of "id:00123" where you have a prefix "id:" and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:

s := "id:00123"

var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
    fmt.Println(i) // Outputs 123
}

How to get calendar Quarter from a date in TSQL

You have to convert the integer to a char(8) then a datetime. then wrap that in SELECT DATEPART(QUARTER, [date])

You will then have to convert the above to character and add on the '-' + year (also converted to char)

The arithmetic overflow above is caused by omitting the initial convert to a character type.

I would be inclined to abstract the conversion to date-time using views where possible and then use the quarter function and character conversion as and when required.

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Python's most efficient way to choose longest string in list?

What should happen if there are more than 1 longest string (think '12', and '01')?

Try that to get the longest element

max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])

And then regular foreach

for st in mylist:
    if len(st)==max_length:...

How to convert an object to a byte array in C#

Well a cast from myObject to byte[] is never going to work unless you've got an explicit conversion or if myObject is a byte[]. You need a serialization framework of some kind. There are plenty out there, including Protocol Buffers which is near and dear to me. It's pretty "lean and mean" in terms of both space and time.

You'll find that almost all serialization frameworks have significant restrictions on what you can serialize, however - Protocol Buffers more than some, due to being cross-platform.

If you can give more requirements, we can help you out more - but it's never going to be as simple as casting...

EDIT: Just to respond to this:

I need my binary file to contain the object's bytes. Only the bytes, no metadata whatsoever. Packed object-to-object. So I'll be implementing custom serialization.

Please bear in mind that the bytes in your objects are quite often references... so you'll need to work out what to do with them.

I suspect you'll find that designing and implementing your own custom serialization framework is harder than you imagine.

I would personally recommend that if you only need to do this for a few specific types, you don't bother trying to come up with a general serialization framework. Just implement an instance method and a static method in all the types you need:

public void WriteTo(Stream stream)
public static WhateverType ReadFrom(Stream stream)

One thing to bear in mind: everything becomes more tricky if you've got inheritance involved. Without inheritance, if you know what type you're starting with, you don't need to include any type information. Of course, there's also the matter of versioning - do you need to worry about backward and forward compatibility with different versions of your types?

Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me

For me XCode had expired my login...XCode-Preferences - saw it had logged me out, loged back in. Only came up with this solution by chance thanks to a related post here that took me to preferences in XCode !

How can I use Python to get the system hostname?

What about :

import platform

h = platform.uname()[1]

Actually you may want to have a look to all the result in platform.uname()

How to split a comma-separated string?

In Kotlin,

val stringArray = commasString.replace(", ", ",").split(",")

where stringArray is List<String> and commasString is String with commas and spaces

Define an alias in fish shell

  1. if there is not config.fish in ~/.config/fish/, make it.
  2. there you can write your function .function name; command; end

sqlite database default time value 'now'

It's just a syntax error, you need parenthesis: (DATETIME('now'))

If you look at the documentation, you'll note the parenthesis that is added around the 'expr' option in the syntax.

View's getWidth() and getHeight() returns 0

If you need to get width of some widget before it is displayed on screen, you can use getMeasuredWidth() or getMeasuredHeight().

myImage.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int width = myImage.getMeasuredWidth();
int height = myImage.getMeasuredHeight();

Xampp localhost/dashboard

Here's what's actually happening localhost means that you want to open htdocs. First it will search for any file named index.php or index.html. If one of those exist it will open the file. If neither of those exist then it will open all folder/file inside htdocs directory which is what you want.

So, the simplest solution is to rename index.php or index.html to index2.php etc.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

Open the file gradle/wrapper/gradle-wrapper.properties in your project. Change the version in the distributionUrl to use the version you want to use, e.g.,

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

How to remove trailing whitespaces with sed?

I have a script in my .bashrc that works under OSX and Linux (bash only !)

function trim_trailing_space() {
  if [[ $# -eq 0 ]]; then
    echo "$FUNCNAME will trim (in place) trailing spaces in the given file (remove unwanted spaces at end of lines)"
    echo "Usage :"
    echo "$FUNCNAME file"
    return
  fi
  local file=$1
  unamestr=$(uname)
  if [[ $unamestr == 'Darwin' ]]; then
    #specific case for Mac OSX
    sed -E -i ''  's/[[:space:]]*$//' $file
  else
    sed -i  's/[[:space:]]*$//' $file
  fi
}

to which I add:

SRC_FILES_EXTENSIONS="js|ts|cpp|c|h|hpp|php|py|sh|cs|sql|json|ini|xml|conf"

function find_source_files() {
  if [[ $# -eq 0 ]]; then
    echo "$FUNCNAME will list sources files (having extensions $SRC_FILES_EXTENSIONS)"
    echo "Usage :"
    echo "$FUNCNAME folder"
    return
  fi
  local folder=$1

  unamestr=$(uname)
  if [[ $unamestr == 'Darwin' ]]; then
    #specific case for Mac OSX
    find -E $folder -iregex '.*\.('$SRC_FILES_EXTENSIONS')'
  else
    #Rhahhh, lovely
    local extensions_escaped=$(echo $SRC_FILES_EXTENSIONS | sed s/\|/\\\\\|/g)
    #echo "extensions_escaped:$extensions_escaped"
    find $folder -iregex '.*\.\('$extensions_escaped'\)$'
  fi
}

function trim_trailing_space_all_source_files() {
  for f in $(find_source_files .); do trim_trailing_space $f;done
}

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ). Let's replace it in its context:

  • x is an array equal to [x0 * n], so its length is 1
  • you're iterating from 0 to n-2 (n doesn't matter here), and i is the index. In the beginning, everything is ok (here there's no beginning apparently... :( ), but as soon as i + 1 >= len(x) <=> i >= 0, the element x[i+1] doesn't exist. Here, this element doesn't exist since the beginning of the for loop.

To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ) by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )).

Changing case in Vim

See the following methods:

 ~    : Changes the case of current character

 guu  : Change current line from upper to lower.

 gUU  : Change current LINE from lower to upper.

 guw  : Change to end of current WORD from upper to lower.

 guaw : Change all of current WORD to lower.

 gUw  : Change to end of current WORD from lower to upper.

 gUaw : Change all of current WORD to upper.

 g~~  : Invert case to entire line

 g~w  : Invert case to current WORD

 guG : Change to lowercase until the end of document.

How to use onResume()?

KOTLIN

Any Activity that restarts has its onResume() method executed first.

To use this method, do this:

override fun onResume() {
        super.onResume()
        // your code here
    }

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

How to convert a boolean array to an int array

Numpy arrays have an astype method. Just do y.astype(int).

Note that it might not even be necessary to do this, depending on what you're using the array for. Bool will be autopromoted to int in many cases, so you can add it to int arrays without having to explicitly convert it:

>>> x
array([ True, False,  True], dtype=bool)
>>> x + [1, 2, 3]
array([2, 2, 4])

How to reset / remove chrome's input highlighting / focus border?

The simpliest way is to use something like this but note that it may not be that good.

input {
  outline: none;
}

I hope you find this useful.

Check for column name in a SqlDataReader object

Here the solution from Jasmine in one line... (one more, tho simple!):

reader.GetSchemaTable().Select("ColumnName='MyCol'").Length > 0;

Execute multiple command lines with the same process using .NET

Couldn't you just write all the commands into a .cmd file in the temp folder and then execute that file?

Ruby get object keys as array

Like taro said, keys returns the array of keys of your Hash:

http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys

You'll find all the different methods available for each class.

If you don't know what you're dealing with:

 puts my_unknown_variable.class.to_s

This will output the class name.

How to bind 'touchstart' and 'click' events but not respond to both?

In my case this worked perfectly:

jQuery(document).on('mouseup keydown touchend', function (event) {
var eventType = event.type;
if (eventType == 'touchend') {
    jQuery(this).off('mouseup');
}
});

The main problem was when instead mouseup I tried with click, on touch devices triggered click and touchend at the same time, if i use the click off, some functionality didn't worked at all on mobile devices. The problem with click is that is a global event that fire the rest of the event including touchend.

How to set root password to null

I am using nodejs and windows 10. A combination of two answers worked for me.

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY ''; 
mysql> flush privileges;

followed by:

restart;

Hope this helps for others who still have an issue with this.

Disable Pinch Zoom on Mobile Web

Found here you can use user-scalable=no:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

How to get the number of days of difference between two dates on mysql?

What about the DATEDIFF function ?

Quoting the manual's page :

DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation


In your case, you'd use :

mysql> select datediff('2010-04-15', '2010-04-12');
+--------------------------------------+
| datediff('2010-04-15', '2010-04-12') |
+--------------------------------------+
|                                    3 | 
+--------------------------------------+
1 row in set (0,00 sec)

But note the dates should be written as YYYY-MM-DD, and not DD-MM-YYYY like you posted.

How to fix date format in ASP .NET BoundField (DataFormatString)?

The following links will help you:

In Client side design page you can try this: {0:G}

OR

You can convert that datetime format inside the query itself from the database:

How to read file from res/raw by name

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

Switch statement equivalent in Windows batch file

I guess all other options would be more cryptic. For those who like readable and non-cryptic code:

IF        "%ID%"=="0" (
    REM do something

) ELSE IF "%ID%"=="1" (
    REM do something else

) ELSE IF "%ID%"=="2" (
    REM do another thing

) ELSE (
    REM default case...
)

It's like an anecdote:

Magician: Put the egg under the hat, do the magic passes ... Remove the hat and ... get the same egg but in the side view ...

The IF ELSE solution isn't that bad. It's almost as good as python's if elif else. More cryptic 'eggs' can be found here.

How to pass arguments to entrypoint in docker-compose.yml

The command clause does work as @Karthik says above.

As a simple example, the following service will have a -inMemory added to its ENTRYPOINT when docker-compose up is run.

version: '2'
services:
  local-dynamo:
    build: local-dynamo
    image: spud/dynamo
    command: -inMemory

Visual Studio Code always asking for git credentials

In general, you can use the built-in credential storage facilities:

git config --global credential.helper store

Or, if you're on Windows, you can use their credential system:

git config --global credential.helper wincred

Or, if you're on MacOS, you can use their credential system:

git config --global credential.helper osxkeychain

The first solution is optimal in most situations.

What are the best practices for SQLite on Android?

Having had some issues, I think I have understood why I have been going wrong.

I had written a database wrapper class which included a close() which called the helper close as a mirror of open() which called getWriteableDatabase and then have migrated to a ContentProvider. The model for ContentProvider does not use SQLiteDatabase.close() which I think is a big clue as the code does use getWriteableDatabase In some instances I was still doing direct access (screen validation queries in the main so I migrated to a getWriteableDatabase/rawQuery model.

I use a singleton and there is the slightly ominous comment in the close documentation

Close any open database object

(my bolding).

So I have had intermittent crashes where I use background threads to access the database and they run at the same time as foreground.

So I think close() forces the database to close regardless of any other threads holding references - so close() itself is not simply undoing the matching getWriteableDatabase but force closing any open requests. Most of the time this is not a problem as the code is single threading, but in multi-threaded cases there is always the chance of opening and closing out of sync.

Having read comments elsewhere that explains that the SqLiteDatabaseHelper code instance counts, then the only time you want a close is where you want the situation where you want to do a backup copy, and you want to force all connections to be closed and force SqLite to write away any cached stuff that might be loitering about - in other words stop all application database activity, close just in case the Helper has lost track, do any file level activity (backup/restore) then start all over again.

Although it sounds like a good idea to try and close in a controlled fashion, the reality is that Android reserves the right to trash your VM so any closing is reducing the risk of cached updates not being written, but it cannot be guaranteed if the device is stressed, and if you have correctly freed your cursors and references to databases (which should not be static members) then the helper will have closed the database anyway.

So my take is that the approach is:

Use getWriteableDatabase to open from a singleton wrapper. (I used a derived application class to provide the application context from a static to resolve the need for a context).

Never directly call close.

Never store the resultant database in any object that does not have an obvious scope and rely on reference counting to trigger an implicit close().

If doing file level handling, bring all database activity to a halt and then call close just in case there is a runaway thread on the assumption that you write proper transactions so the runaway thread will fail and the closed database will at least have proper transactions rather than potentially a file level copy of a partial transaction.

How to remove item from array by value?

Another variation:

if (!Array.prototype.removeArr) {
    Array.prototype.removeArr = function(arr) {
        if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
        var that = this;
        if(arr.length){
            var i=0;
            while(i<that.length){
                if(arr.indexOf(that[i])>-1){
                    that.splice(i,1);
                }else i++;
            }
        }
        return that;
    }
}

It's indexOf() inside a loop again, but on the assumption that the array to remove is small relative to the array to be cleaned; every removal shortens the while loop.

How do you update Xcode on OSX to the latest version?

Another best way to update and upgrade OSX development tools using command line is as follows:

Open terminal on OSX and type below commands. Try 'sudo' as prefix if you don't have admin privileges.

brew update

and for upgrading outdated tools and libraries use below command

brew upgrade

These will update all packages like node, rethinkDB and much more.

Also, softwareupdate --install --all this command also work best.

Important: Remove all outdated packages and free some space using the simple command.

brew cleanup

Should we @Override an interface's method implementation?

For me, often times this is the only reason some code requires Java 6 to compile. Not sure if it's worth it.

How to select a single child element using jQuery?

<html>
<title>

    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>




<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
 <!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->

<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
    <!-- repeater1 starts -->
        <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
            <ul  >
                <li ><h6><strong>lorem</strong></h6></li>
                <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                <li ><h6><strong>Full Service Contracts</strong></h6></li>
                <li ><h6><strong>Maintenance Contracts</strong></h6></li>
            </ul>
    <!-- repeater1 ends -->
</div>
</div>




</asp:Repeater>


</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>

<script>

 $(function () {
        $('a').click(function() {
            $(this).parent().children('.dataContentSectionMessages').slideToggle();
        });
    });

    </script>


</html>

How to right align widget in horizontal linear layout Android?

this is my xml, dynamic component to align right, in my case i use 3 button

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/checkinInputCodeMember">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="7"
                android:orientation="vertical" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_extends"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="3"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_checkout"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="2"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/checkinButtonScanQrCodeMember"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="1"/>


        </LinearLayout>

and the result

you can hide the right first button with change visibility GONE, and this my code

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/checkinInputCodeMember">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="7"
                android:orientation="vertical" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_extends"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="3"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/bttn_checkout"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="@color/colorAccent"
                android:text="2"/>

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/checkinButtonScanQrCodeMember"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:text="1"
                android:textColor="@color/colorAccent"
                **android:visibility="gone"**/>


        </LinearLayout>

still align right, after visibility gone first right component

result code 1

result code 2

Preferred way of getting the selected item of a JComboBox

Note this isn't at heart a question about JComboBox, but about any collection that can include multiple types of objects. The same could be said for "How do I get a String out of a List?" or "How do I get a String out of an Object[]?"

SQL Call Stored Procedure for each Row without using a cursor

If you can turn the stored procedure into a function that returns a table, then you can use cross-apply.

For example, say you have a table of customers, and you want to compute the sum of their orders, you would create a function that took a CustomerID and returned the sum.

And you could do this:

SELECT CustomerID, CustomerSum.Total

FROM Customers
CROSS APPLY ufn_ComputeCustomerTotal(Customers.CustomerID) AS CustomerSum

Where the function would look like:

CREATE FUNCTION ComputeCustomerTotal
(
    @CustomerID INT
)
RETURNS TABLE
AS
RETURN
(
    SELECT SUM(CustomerOrder.Amount) AS Total FROM CustomerOrder WHERE CustomerID = @CustomerID
)

Obviously, the example above could be done without a user defined function in a single query.

The drawback is that functions are very limited - many of the features of a stored procedure are not available in a user-defined function, and converting a stored procedure to a function does not always work.

How to include (source) R script in other scripts

There is no such thing built-in, since R does not track calls to source and is not able to figure out what was loaded from where (this is not the case when using packages). Yet, you may use same idea as in C .h files, i.e. wrap the whole in:

if(!exists('util_R')){
 util_R<-T

 #Code

}

check if file exists in php

if (!file_exists('http://example.com/images/thumbnail_1286954822.jpg')) {   
$filefound = '0';
}

Difference between string object and string literal

In addition to the answers already posted, also see this excellent article on javaranch.

Simulate low network connectivity for Android

Easy way to test your application with low/bad connection in emulator:

Go Run > Run configurations, select your Android Application, and there go to Target tab. Look Emulator launch parameters. Here, you can easy modify Network Speed and Network Latency.

How to change plot background color?

simpler answer:

ax = plt.axes()
ax.set_facecolor('silver')

Error message: "'chromedriver' executable needs to be available in the path"

Check the path of your chrome driver, it might not get it from there. Simply Copy paste the driver location into the code.

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

You can view this dump from the UNIX console.

The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.

E.g.:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"

You can view the dump from the console on the mentioned path.

Getting rid of all the rounded corners in Twitter Bootstrap

Download the source .less files and make the .border-radius() mixin blank.

Python 3.1.1 string to hex

You've already got some good answers, but I thought you might be interested in a bit of the background too.

Firstly you're missing the quotes. It should be:

"hello".encode("hex")

Secondly this codec hasn't been ported to Python 3.1. See here. It seems that they haven't yet decided whether or not these codecs should be included in Python 3 or implemented in a different way.

If you look at the diff file attached to that bug you can see the proposed method of implementing it:

import binascii
output = binascii.b2a_hex(input)

javascript get x and y coordinates on mouse click

It sounds like your printMousePos function should:

  1. Get the X and Y coordinates of the mouse
  2. Add those values to the HTML

Currently, it does this:

  1. Creates (undefined) variables for the X and Y coordinates of the mouse
  2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
  3. Adds the current values of your variables to the HTML

See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

It seems like you probably don't need that mousemove event at all; I would try something like this:

function printMousePos(e) {
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I'm playing right now with Git 1.6.5, and I can't replicate your setup:

Administrator@WS2008 /k/git
$ ll ~/.ssh
total 8
drwxr-xr-x    2 Administ Administ     4096 Oct 13 22:04 ./
drwxr-xr-x    6 Administ Administ     4096 Oct  6 21:36 ../
-rw-r--r--    1 Administ Administ        0 Oct 13 22:04 c.txt
-rw-r--r--    1 Administ Administ      403 Sep 30 22:36 config_disabled
-rw-r--r--    1 Administ Administ      887 Aug 30 16:33 id_rsa
-rw-r--r--    1 Administ Administ      226 Aug 30 16:34 id_rsa.pub
-rw-r--r--    1 Administ Administ      843 Aug 30 16:32 id_rsa_putty.ppk
-rw-r--r--    1 Administ Administ      294 Aug 30 16:33 id_rsa_putty.pub
-rw-r--r--    1 Administ Administ     1626 Sep 30 22:49 known_hosts

Administrator@WS2008 /k/git
$ git clone [email protected]:alexandrul/gitbook.git
Initialized empty Git repository in k:/git/gitbook/.git/
remote: Counting objects: 1152, done.
remote: Compressing objects: 100% (625/625), done.
remote: Total 1152 (delta 438), reused 1056 (delta 383)s
Receiving objects: 100% (1152/1152), 1.31 MiB | 78 KiB/s, done.
Resolving deltas: 100% (438/438), done.

Administrator@WS2008 /k/git
$ ssh [email protected]
ERROR: Hi alexandrul! You've successfully authenticated, but GitHub does not pro
vide shell access
Connection to github.com closed.

$ ssh -v
OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007

chmod doesn't modify file permissions for my keys either.

Environment:

  • Windows Server 2008 SP2 on NTFS
  • user: administrator
  • environment vars:
    • PLINK_PROTOCOL=ssh
    • HOME=/c/profiles/home

Update: Git 1.6.5.1 works as well.

C#: calling a button event handler method without actually clicking the button

btnTest_Click(null, null);

Provided that the method isn't using either of these parameters (it's very common not to.)

To be honest though this is icky. If you have code that needs to be called you should follow the following convention:

protected void btnTest_Click(object sender, EventArgs e)
{
   SomeSub();
}

protected void SomeOtherFunctionThatNeedsToCallTheCode()
{
   SomeSub();
}

protected void SomeSub()
{
   // ...
}

How do I post form data with fetch api?

With fetch api it turned out that you do NOT have to include headers "Content-type": "multipart/form-data".

So the following works:

let formData = new FormData()
formData.append("nameField", fileToSend)

fetch(yourUrlToPost, {
   method: "POST",
   body: formData
})

Note that with axios I had to use the content-type.

Keep CMD open after BAT file executes

In Windows add '& Pause' to the end of your command in the file.

How to split a string and assign it to variables

Golang does not support implicit unpacking of an slice (unlike python) and that is the reason this would not work. Like the examples given above, we would need to workaround it.

One side note:

The implicit unpacking happens for variadic functions in go:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)

Use string value from a cell to access worksheet of same name

You need INDIRECT function:

=INDIRECT("'"&A5&"'!G7")

Limit the length of a string with AngularJS

You can limit the length of a string or an array by using a filter. Check this one written by the AngularJS team.

Insert some string into given string at given index in Python

Answer for Insert characters of string in other string al located positions

str1 = "ibuprofen"
str2 = "MEDICAL"
final_string=""
Value = 2
list2=[]
result=[str1[i:i+Value] for i in range(0, len(str1), Value)]
count = 0

for letter in result:
    if count < len(result)-1:
        final_string = letter + str2[count]
        list2.append(final_string)
    elif ((len(result)-1)==count):
        list2.append(letter + str2[count:len(str2)])
        break
    count += 1

print(''.join(list2))

Differences between git pull origin master & git pull origin/master

git pull = git fetch + git merge origin/branch

git pull and git pull origin branch only differ in that the latter will only "update" origin/branch and not all origin/* as git pull does.

git pull origin/branch will just not work because it's trying to do a git fetch origin/branch which is invalid.

Question related: git fetch + git merge origin/master vs git pull origin/master

What characters are forbidden in Windows and Linux directory names?

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

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

\ / : * ? " < > |

Remove all git files from a directory?

You can use git-archive, for example:

git archive master | bzip2 > project.tar.bz2

Where master is the desired branch.

Countdown timer in React

The one downside with setInterval is that it can slow down the main thread. You can do a countdown timer using requestAnimationFrame instead to prevent this. For example, this is my generic countdown timer component:

class Timer extends Component {
  constructor(props) {
    super(props)
    // here, getTimeRemaining is a helper function that returns an 
    // object with { total, seconds, minutes, hours, days }
    this.state = { timeLeft: getTimeRemaining(props.expiresAt) }
  }

  // Wait until the component has mounted to start the animation frame
  componentDidMount() {
    this.start()
  }

  // Clean up by cancelling any animation frame previously scheduled
  componentWillUnmount() {
    this.stop()
  }

  start = () => {
    this.frameId = requestAnimationFrame(this.tick)
  }

  tick = () => {
    const timeLeft = getTimeRemaining(this.props.expiresAt)
    if (timeLeft.total <= 0) {
      this.stop()
      // ...any other actions to do on expiration
    } else {
      this.setState(
        { timeLeft },
        () => this.frameId = requestAnimationFrame(this.tick)
      )
    }
  }

  stop = () => {
    cancelAnimationFrame(this.frameId)
  }

  render() {...}
}

Git Server Like GitHub?

Gitorious is an open source web interface to git that you can run on your own server, much like github:

http://getgitorious.com/

Update:

http://gitlab.org/ is another alternative now as well.

Update 2:

Gitorious has now joined with GitLab

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

How to get item count from DynamoDB?

In Scala:

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder
import com.amazonaws.services.dynamodbv2.document.DynamoDB
val client = AmazonDynamoDBClientBuilder.standard().build()

val dynamoDB = new DynamoDB(client)
val tableDescription = dynamoDB.getTable("table name").describe().getItemCount()

Copying a HashMap in Java

If we want to copy an object in Java, there are two possibilities that we need to consider: a shallow copy and a deep copy.

The shallow copy is the approach when we only copy field values. Therefore, the copy might be dependent on the original object. In the deep copy approach, we make sure that all the objects in the tree are deeply copied, so the copy is not dependent on any earlier existing object that might ever change.

This question is the perfect definition for the application of the deep copy approach.

First, if you have a simple HashMap<Integer, List<T>> map then we just create a workaround like this. Creating a new instance of the List<T>.

public static <T> HashMap<Integer, List<T>> deepCopyWorkAround(HashMap<Integer, List<T>> original)
{
    HashMap<Integer, List<T>> copy = new HashMap<>();
    for (Map.Entry<Integer, List<T>> entry : original.entrySet()) {
        copy.put(entry.getKey(), new ArrayList<>(entry.getValue()));
    }
    return copy;
}

This one uses Stream.collect() method to create the clone map, but uses the same idea as the previous method.

public static <T> Map<Integer, List<T>> deepCopyStreamWorkAround(Map<Integer, List<T>> original)
{
    return original
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey, valueMapper -> new ArrayList<>(valueMapper.getValue())));
}   

But, if the instances inside T are also mutable objects we have a big problem. In this case a real deep copy is an alternative that solves this problem. Its advantage is that at least each mutable object in the object graph is recursively copied. Since the copy is not dependent on any mutable object that was created earlier, it won’t get modified by accident like we saw with the shallow copy.

To solve that this deep copy implementations will do the work.

public class DeepClone
{
    public static void main(String[] args)
    {
        Map<Long, Item> itemMap = Stream.of(
                entry(0L, new Item(2558584)),
                entry(1L, new Item(254243232)),
                entry(2L, new Item(986786)),
                entry(3L, new Item(672542)),
                entry(4L, new Item(4846)),
                entry(5L, new Item(76867467)),
                entry(6L, new Item(986786)),
                entry(7L, new Item(7969768)),
                entry(8L, new Item(68868486)),
                entry(9L, new Item(923)),
                entry(10L, new Item(986786)),
                entry(11L, new Item(549768)),
                entry(12L, new Item(796168)),
                entry(13L, new Item(868421)),
                entry(14L, new Item(923)),
                entry(15L, new Item(986786)),
                entry(16L, new Item(549768)),
                entry(17L, new Item(4846)),
                entry(18L, new Item(4846)),
                entry(19L, new Item(76867467)),
                entry(20L, new Item(986786)),
                entry(21L, new Item(7969768)),
                entry(22L, new Item(923)),
                entry(23L, new Item(4846)),
                entry(24L, new Item(986786)),
                entry(25L, new Item(549768))
        ).collect(entriesToMap());


        Map<Long, Item> clone = DeepClone.deepClone(itemMap);
        clone.remove(1L);
        clone.remove(2L);

        System.out.println(itemMap);
        System.out.println(clone);
    }

    private DeepClone() {}

    public static <T> T deepClone(final T input)
    {
        if (input == null) return null;

        if (input instanceof Map<?, ?>) {
            return (T) deepCloneMap((Map<?, ?>) input);
        } else if (input instanceof Collection<?>) {
            return (T) deepCloneCollection((Collection<?>) input);
        } else if (input instanceof Object[]) {
            return (T) deepCloneObjectArray((Object[]) input);
        } else if (input.getClass().isArray()) {
            return (T) clonePrimitiveArray((Object) input);
        }

        return input;
    }

    private static Object clonePrimitiveArray(final Object input)
    {
        final int length = Array.getLength(input);
        final Object output = Array.newInstance(input.getClass().getComponentType(), length);
        System.arraycopy(input, 0, output, 0, length);
        return output;
    }

    private static <E> E[] deepCloneObjectArray(final E[] input)
    {
        final E[] clone = (E[]) Array.newInstance(input.getClass().getComponentType(), input.length);
        for (int i = 0; i < input.length; i++) {
            clone[i] = deepClone(input[i]);
        }

        return clone;
    }

    private static <E> Collection<E> deepCloneCollection(final Collection<E> input)
    {
        Collection<E> clone;
        if (input instanceof LinkedList<?>) {
            clone = new LinkedList<>();
        } else if (input instanceof SortedSet<?>) {
            clone = new TreeSet<>();
        } else if (input instanceof Set) {
            clone = new HashSet<>();
        } else {
            clone = new ArrayList<>();
        }

        for (E item : input) {
            clone.add(deepClone(item));
        }

        return clone;
    }

    private static <K, V> Map<K, V> deepCloneMap(final Map<K, V> map)
    {
        Map<K, V> clone;
        if (map instanceof LinkedHashMap<?, ?>) {
            clone = new LinkedHashMap<>();
        } else if (map instanceof TreeMap<?, ?>) {
            clone = new TreeMap<>();
        } else {
            clone = new HashMap<>();
        }

        for (Map.Entry<K, V> entry : map.entrySet()) {
            clone.put(deepClone(entry.getKey()), deepClone(entry.getValue()));
        }

        return clone;
    }
}

Can I get div's background-image url?

I usually prefer .replace() to regular expressions when possible, since it's often easier to read: http://jsfiddle.net/mblase75/z2jKA/2

    $("div").click(function() {
        var bg = $(this).css('background-image');
        bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
        alert(bg);
    });

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

htaccess redirect to https://www

Similar to Amir Forsati's solution htaccess redirect to https://www but for variable domain name, I suggest:

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%2%{REQUEST_URI} [R=301,L]

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

Git command to checkout any branch and overwrite local changes

You could follow a solution similar to "How do I force “git pull” to overwrite local files?":

git fetch --all
git reset --hard origin/abranch
git checkout $branch 

That would involve only one fetch.

With Git 2.23+, git checkout is replaced here with git switch (presented here) (still experimental).

git switch -f $branch

(with -f being an alias for --discard-changes, as noted in Jan's answer)

Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.

Bootstrap Carousel : Remove auto slide

You just need to add one more attribute to your DIV tag which is

data-interval="false"

no need to touch JS!

How to use ESLint with Jest

The docs show you are now able to add:

"env": {
    "jest/globals": true
}

To your .eslintrc which will add all the jest related things to your environment, eliminating the linter errors/warnings.

Best way to check for null values in Java?

If you control the API being called, consider using Guava's Optional class

More info here. Change your method to return an Optional<Boolean> instead of a Boolean.

This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

As an alternative answer, there's a command line to invoke directly the Control Panel, which is javaws -viewer, should work for both openJDK and Oracle's JDK (thanks @Nasser for checking the availability in Oracle's JDK)

Same caution to run as the user you need to access permissions with applies.

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

"pip install unroll": "python setup.py egg_info" failed with error code 1

I got stuck exactly with the same error with psycopg2. It looks like I skipped a few steps while installing Python and related packages.

  1. sudo apt-get install python-dev libpq-dev
  2. Go to your virtual env
  3. pip install psycopg2

(In your case you need to replace psycopg2 with the package you have an issue with.)

It worked seamlessly.