Programs & Examples On #Direct3d10

0

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I uninstall a Windows service if the files do not exist anymore?

The easiest way is to use Sys Internals Autoruns

enter image description here

Start it in admin mode and then you can remove obsolete services by delete key

What does Ruby have that Python doesn't, and vice versa?

Ruby has embedded documentation:

 =begin

 You could use rdoc to generate man pages from this documentation

 =end

How to prevent a browser from storing passwords

I tested the many solutions and finally I came with this solution.

HTML Code

<input type="text" name="UserName" id="UserName" placeholder="UserName" autocomplete="off" />
<input type="text" name="Password" id="Password" placeholder="Password" autocomplete="off"/>

CSS Code

#Password {
    text-security: disc;
    -webkit-text-security: disc;
    -moz-text-security: disc;
}

JavaScript Code

window.onload = function () {
    init();
}

function init() {
    var x = document.getElementsByTagName("input")["Password"];
    var style = window.getComputedStyle(x);
    console.log(style);

    if (style.webkitTextSecurity) {
        // Do nothing
    } else {
        x.setAttribute("type", "password");
    }
}

How to disable spring security for particular url

This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
                .anyRequest().permitAll()
                .and()
                .formLogin().loginPage("/web/login").permitAll()
                .and()
                .csrf().ignoringAntMatchers("/contact-email")
                .and()
                .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles(ADMIN.toString())
                .and()
                .withUser("guest").password("guest").roles(GUEST.toString());
    }

}

I have included full configuration but the key line is:

.csrf().ignoringAntMatchers("/contact-email")

Set Focus After Last Character in Text Box

One can use these simple javascript within the input tag.

<input type="text" name="your_name" value="your_value"
     onfocus="this.setSelectionRange(this.value.length, this.value.length);" 
autofocus />

Execute external program

This is not right. Here's how you should use Runtime.exec(). You might also try its more modern cousin, ProcessBuilder:

Java Runtime.getRuntime().exec() alternatives

IIS: Where can I find the IIS logs?

I'm adding this answer because after researching the web, I ended up at this answer but still didn't know which subfolder of the IIS logs folder to look in.

If your server has multiple websites, you will need to know the IIS ID for the site. An easy way to get this in IIS is to simply click on the Sites folder in the left panel. The ID for each site is shown in the right panel.

Once you know the ID, let's call it n, the corresponding logs are in the W3SVCn subfolder of the IIS logs folder. So, if your website ID is 4, say, and the IIS logs are in the default location, then the logs are in this folder:

%SystemDrive%\inetpub\logs\LogFiles\W3SVC4

Acknowlegements:

  • Answer by @jishi tells where the logs are by default.
  • Answer by @Rafid explains how to find actual location (maybe not default).
  • Answer by @Bergius gives a programmatic way to find the log folder location for a specific website, taking ID into account, without using IIS.

Auto-indent in Notepad++

A little update: You can skip the TextFX Plugin and just use Tidy2. Here you can configure your own formating-rules for different types of codes. Easy to install and remove within

Notepad++ > Plugins > Plugin Manager > Show Plugin Manager

and just search for Tidy2 and install it. Done.

WSDL vs REST Pros and Cons

This probably really belongs as comments in several of the above posts, but I don't yet have the rep to do that, so here goes.

I think it is interesting that a lot of the pros and cons often cited for SOAP and REST have (IMO) very little to do with the actual values or limits of the two technologies. Probably the most cited pro for REST is that it is "light-weight" or tends to be more "human readable". At one level this is certainly true, REST does have a lower barrier to entry - there is less required structure than SOAP (though I agree with those who have said that good tooling is largely the answer here - too bad much of the SOAP tooling is pretty dreadful).

Beyond that initial entry cost however, I think the REST impression comes from a combination of the form of the request URLs and the complexity of the data exchanged by most REST services. REST tends to encourage simpler, more human readable request URLs and the data tends to be more digestable as well. To what extent however are these inherent to REST and to what extent are they merely accidental. The simpler URL structure is a direct result of the architecture - but it could be equally well applied to SOAP based services. The more digestable data is more likely to be a result of the lack of any defined structure. This means you'd better keep your data formats simple or you are going to be in for a lot of work. So here SOAP's additional structure, which should be a benefit is actually enabling sloppy design and that sloppy design then gets used as a dig against the technology.

So for use in the exchange of structured data between computer systems I'm not sure that REST is inherently better than SOAP (or visa-versa), they are just different. I think the comparison above of REST vs SOAP to dynamic vs. static typing is a good one. Where dyanmic languages tend to run in to trouble is in long term maintenance and upkeep of a system (and by long term I'm not talking a year or 2, I'm talking 5 or 10). It will be interesting to see if REST runs into the same challenges over time. I tend to think it will so if I were building a distributed, information processing system I would gravitate to SOAP as the communication mechanism (also because of the tranmission and application protocol layering and flexibility that it affords as has been mentioned above).

In other places though REST seems more appropriate. AJAX between the client and its server (regardless of payload) is one major example. I don't have much care for the longevity of this type of connection and ease of use and flexibility are at a premimum. Similarly if I needed quick access to some external service and I didn't think I was going to care about the maintainability of the interaction over time (again I'm assuming this is where REST is going to end up costing me more, one way or another), then I might choose REST just so I could get in and out quickly.

Anyway, they are both viable technologies and depending on what tradeoffs you want to make for a given application they can serve you well (or poorly).

Select method of Range class failed via VBA

This is how you get around that in an easy non-complicated way.
Instead of using sheet(x).range use Activesheet.range("range").select

Network tools that simulate slow network connection

try Traffic Shaper XP you can easily limit speed of IE or other browser with this App and its also freeware

New og:image size for Facebook share?

Facebook.com og:image is 325x325 (1:1 aspect ratio, square)

https://www.facebook.com/images/fb_icon_325x325.png

Simplest way to serve static data from outside the application server in a Java web application

if anyone not able to resolve his problem with accepted answer, then note these below considerations:

  1. no need to mention localhost:<port> with <img> src attribute.
  2. make sure you are running this project outside eclipse, because eclipse creates context docBase entry on its own inside its local server.xml file.

What is "406-Not Acceptable Response" in HTTP?

In my case, I added:

Content-Type: application/x-www-form-urlencoded

solved my problem completely.

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

onCreate is called for the first time when creation of tables are needed. We need to override this method where we write the script for table creation which is executed by SQLiteDatabase. execSQL method. After executing in first time deployment, this method will not be called onwards.

onUpgrade This method is called when database version is upgraded. Suppose for the first time deployment , database version was 1 and in second deployment there was change in database structure like adding extra column in table. Suppose database version is 2 now.

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

Extract substring from a string

You can use subSequence , it's same as substr in C

 Str.subSequence(int Start , int End)

Can I assume (bool)true == (int)1 for any C++ compiler?

Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...

Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as ints that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h> only require zero or non-zero, not necessarily zero or one.

If you cast that to bool, zero will convert to false, and non-zero to true (as you'd expect).

Add directives from directive in AngularJS

You can actually handle all of this with just a simple template tag. See http://jsfiddle.net/m4ve9/ for an example. Note that I actually didn't need a compile or link property on the super-directive definition.

During the compilation process, Angular pulls in the template values before compiling, so you can attach any further directives there and Angular will take care of it for you.

If this is a super directive that needs to preserve the original internal content, you can use transclude : true and replace the inside with <ng-transclude></ng-transclude>

Hope that helps, let me know if anything is unclear

Alex

Set background colour of cell to RGB value of data in cell

You can use VBA - something like

Range("A1:A6").Interior.Color = RGB(127,187,199)

Just pass in the cell value.

Text Editor which shows \r\n?

The best for replace \n \t and more: Programmer's File Editor http://www.lancs.ac.uk/staff/steveb/cpaap/pfe/pfefiles.htm

Passing vector by reference

You can pass the container by reference in order to modify it in the function. What other answers haven’t addressed is that std::vector does not have a push_front member function. You can use the insert() member function on vector for O(n) insertion:

void do_something(int el, std::vector<int> &arr){
    arr.insert(arr.begin(), el);
}

Or use std::deque instead for amortised O(1) insertion:

void do_something(int el, std::deque<int> &arr){
    arr.push_front(el);
}

How to multiply individual elements of a list with a number?

You can use built-in map function:

result = map(lambda x: x * P, S)

or list comprehensions that is a bit more pythonic:

result = [x * P for x in S]

How to match all occurrences of a regex

To find all the matching strings, use String's scan method.

str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
str.scan(/\d+/)
#=> ["54", "3", "1", "7", "3", "36", "0"]

If you want, MatchData, which is the type of the object returned by the Regexp match method, use:

str.to_enum(:scan, /\d+/).map { Regexp.last_match }
#=> [#<MatchData "54">, #<MatchData "3">, #<MatchData "1">, #<MatchData "7">, #<MatchData "3">, #<MatchData "36">, #<MatchData "0">]

The benefit of using MatchData is that you can use methods like offset:

match_datas = str.to_enum(:scan, /\d+/).map { Regexp.last_match }
match_datas[0].offset(0)
#=> [2, 4]
match_datas[1].offset(0)
#=> [7, 8]

See these questions if you'd like to know more:

Reading about special variables $&, $', $1, $2 in Ruby will be helpful too.

Why are elementwise additions much faster in separate loops than in a combined loop?

I cannot replicate the results discussed here.

I don't know if poor benchmark code is to blame, or what, but the two methods are within 10% of each other on my machine using the following code, and one loop is usually just slightly faster than two - as you'd expect.

Array sizes ranged from 2^16 to 2^24, using eight loops. I was careful to initialize the source arrays so the += assignment wasn't asking the FPU to add memory garbage interpreted as a double.

I played around with various schemes, such as putting the assignment of b[j], d[j] to InitToZero[j] inside the loops, and also with using += b[j] = 1 and += d[j] = 1, and I got fairly consistent results.

As you might expect, initializing b and d inside the loop using InitToZero[j] gave the combined approach an advantage, as they were done back-to-back before the assignments to a and c, but still within 10%. Go figure.

Hardware is Dell XPS 8500 with generation 3 Core i7 @ 3.4 GHz and 8 GB memory. For 2^16 to 2^24, using eight loops, the cumulative time was 44.987 and 40.965 respectively. Visual C++ 2010, fully optimized.

PS: I changed the loops to count down to zero, and the combined method was marginally faster. Scratching my head. Note the new array sizing and loop counts.

// MemBufferMystery.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <time.h>

#define  dbl    double
#define  MAX_ARRAY_SZ    262145    //16777216    // AKA (2^24)
#define  STEP_SZ           1024    //   65536    // AKA (2^16)

int _tmain(int argc, _TCHAR* argv[]) {
    long i, j, ArraySz = 0,  LoopKnt = 1024;
    time_t start, Cumulative_Combined = 0, Cumulative_Separate = 0;
    dbl *a = NULL, *b = NULL, *c = NULL, *d = NULL, *InitToOnes = NULL;

    a = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    b = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    c = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    d = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    InitToOnes = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    // Initialize array to 1.0 second.
    for(j = 0; j< MAX_ARRAY_SZ; j++) {
        InitToOnes[j] = 1.0;
    }

    // Increase size of arrays and time
    for(ArraySz = STEP_SZ; ArraySz<MAX_ARRAY_SZ; ArraySz += STEP_SZ) {
        a = (dbl *)realloc(a, ArraySz * sizeof(dbl));
        b = (dbl *)realloc(b, ArraySz * sizeof(dbl));
        c = (dbl *)realloc(c, ArraySz * sizeof(dbl));
        d = (dbl *)realloc(d, ArraySz * sizeof(dbl));
        // Outside the timing loop, initialize
        // b and d arrays to 1.0 sec for consistent += performance.
        memcpy((void *)b, (void *)InitToOnes, ArraySz * sizeof(dbl));
        memcpy((void *)d, (void *)InitToOnes, ArraySz * sizeof(dbl));

        start = clock();
        for(i = LoopKnt; i; i--) {
            for(j = ArraySz; j; j--) {
                a[j] += b[j];
                c[j] += d[j];
            }
        }
        Cumulative_Combined += (clock()-start);
        printf("\n %6i miliseconds for combined array sizes %i and %i loops",
                (int)(clock()-start), ArraySz, LoopKnt);
        start = clock();
        for(i = LoopKnt; i; i--) {
            for(j = ArraySz; j; j--) {
                a[j] += b[j];
            }
            for(j = ArraySz; j; j--) {
                c[j] += d[j];
            }
        }
        Cumulative_Separate += (clock()-start);
        printf("\n %6i miliseconds for separate array sizes %i and %i loops \n",
                (int)(clock()-start), ArraySz, LoopKnt);
    }
    printf("\n Cumulative combined array processing took %10.3f seconds",
            (dbl)(Cumulative_Combined/(dbl)CLOCKS_PER_SEC));
    printf("\n Cumulative seperate array processing took %10.3f seconds",
        (dbl)(Cumulative_Separate/(dbl)CLOCKS_PER_SEC));
    getchar();

    free(a); free(b); free(c); free(d); free(InitToOnes);
    return 0;
}

I'm not sure why it was decided that MFLOPS was a relevant metric. I though the idea was to focus on memory accesses, so I tried to minimize the amount of floating point computation time. I left in the +=, but I am not sure why.

A straight assignment with no computation would be a cleaner test of memory access time and would create a test that is uniform irrespective of the loop count. Maybe I missed something in the conversation, but it is worth thinking twice about. If the plus is left out of the assignment, the cumulative time is almost identical at 31 seconds each.

How to run JUnit tests with Gradle?

If you set up your project with the default gradle package structure, i.e.:

src/main/java
src/main/resources
src/test/java
src/test/resources

then you won't need to modify sourceSets to run your tests. Gradle will figure out that your test classes and resources are in src/test. You can then run as Oliver says above. One thing to note: Be careful when setting property files and running your test classes with both gradle and you IDE. I use Eclipse, and when running JUnit from it, Eclipse chooses one classpath (the bin directory) whereas gradle chooses another (the build directory). This can lead to confusion if you edit a resource file, and don't see your change reflected at test runtime.

Single statement across multiple lines in VB.NET without the underscore character

No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can't figure out where the end should be.

How do I install a NuGet package .nupkg file locally?

  1. Add the files to a folder called LocalPackages next to you solution (it doesn't have to be called that, but adjust the xml in the following step accordingly)
  2. Create a file called NuGet.config next to your solution file with the following contents

    <?xml version="1.0" encoding="utf-8"?>
      <configuration>
        <packageSources>
          <add key="LocalPackages" value="./LocalPackages" />
        </packageSources>
        <activePackageSource>
          <!-- this tells that all of them are active -->
          <add key="All" value="(Aggregate source)" />
        </activePackageSource>
     </configuration>
    
  3. If the solution is open in Visual Studio, close it, then re-open it.

Now your packages should appear in the browser, or be installable using Install-Package

Git remote branch deleted, but still it appears in 'branch -a'

Don't forget the awesome

git fetch -p

which fetches and prunes all origins.

How to set column header text for specific column in Datagridview C#

there is HeaderText property in Column object, you can find the column and set its HeaderText after initializing grid or do it in windows form designer via designer for DataGrid.

    public Form1()
    {
        InitializeComponent();

        grid.Columns[0].HeaderText = "First Column"; 
        //..............
    }

More details are here at MSDN. More details about DataGrid are here.

How to fully clean bin and obj folders within Visual Studio?

In windows just open the explorer navigate to your SLN folder click into search field and type kind:=folder;obj --> for obj folders use CTRL+A and delete 'em - same for bin Done

No need for any tool or extra software ;)

How to check if a process is running via a batch script

I don't know how to do so with built in CMD but if you have grep you can try the following:

tasklist /FI "IMAGENAME eq myApp.exe" | grep myApp.exe
if ERRORLEVEL 1 echo "myApp is not running"

How to set an button align-right with Bootstrap?

function Continue({show, onContinue}) {
  return(<div className="row continue">
  { show ? <div className="col-11">
    <button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
    </div>
    : null }
  </div>);
}

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

Find and Replace Inside a Text File from a Bash Command

You can use rpl command. For example you want to change domain name in whole php project.

rpl -ivRpd -x'.php' 'old.domain.name' 'new.domain.name' ./path_to_your_project_folder/  

This is not clear bash of cause, but it's a very quick and usefull. :)

What does the "yield" keyword do?

Here is an example in plain language. I will provide a correspondence between high-level human concepts to low-level Python concepts.

I want to operate on a sequence of numbers, but I don't want to bother my self with the creation of that sequence, I want only to focus on the operation I want to do. So, I do the following:

  • I call you and tell you that I want a sequence of numbers which is produced in a specific way, and I let you know what the algorithm is.
    This step corresponds to defining the generator function, i.e. the function containing a yield.
  • Sometime later, I tell you, "OK, get ready to tell me the sequence of numbers".
    This step corresponds to calling the generator function which returns a generator object. Note that you don't tell me any numbers yet; you just grab your paper and pencil.
  • I ask you, "tell me the next number", and you tell me the first number; after that, you wait for me to ask you for the next number. It's your job to remember where you were, what numbers you have already said, and what is the next number. I don't care about the details.
    This step corresponds to calling .next() on the generator object.
  • … repeat previous step, until…
  • eventually, you might come to an end. You don't tell me a number; you just shout, "hold your horses! I'm done! No more numbers!"
    This step corresponds to the generator object ending its job, and raising a StopIteration exception The generator function does not need to raise the exception. It's raised automatically when the function ends or issues a return.

This is what a generator does (a function that contains a yield); it starts executing, pauses whenever it does a yield, and when asked for a .next() value it continues from the point it was last. It fits perfectly by design with the iterator protocol of Python, which describes how to sequentially request values.

The most famous user of the iterator protocol is the for command in Python. So, whenever you do a:

for item in sequence:

it doesn't matter if sequence is a list, a string, a dictionary or a generator object like described above; the result is the same: you read items off a sequence one by one.

Note that defining a function which contains a yield keyword is not the only way to create a generator; it's just the easiest way to create one.

For more accurate information, read about iterator types, the yield statement and generators in the Python documentation.

Convert LocalDate to LocalDateTime or java.sql.Timestamp

Depending on your timezone, you may lose a few minutes (1650-01-01 00:00:00 becomes 1649-12-31 23:52:58)

Use the following code to avoid that

new Timestamp(localDateTime.getYear() - 1900, localDateTime.getMonthOfYear() - 1, localDateTime.getDayOfMonth(), localDateTime.getHourOfDay(), localDateTime.getMinuteOfHour(), localDateTime.getSecondOfMinute(), fractional);

exception in thread 'main' java.lang.NoClassDefFoundError:

Here is what finally worked.

`@echo off
set path=%path%;C:\Program Files\Java\jdk1.7.0_71\bin;
set classpath=C:\Program Files\Java\jdk1.7.0_71\lib;
cd <packageDirectoryName>
javac .\trainingPackage\HelloWorld.java
cd ..
java trainingPackage.HelloWorld 
REM (Make sure you are on the parent directory of the PackageName and not inside the    Packagedirectory when executing java).`

How to understand nil vs. empty vs. blank in Ruby

Quick tip: !obj.blank? == obj.present?

Can be handy/easier on the eyes in some expressions

How to change environment's font size?

Just copy "editor.fontSize": 18 into your setting.json of the editor.

Pressing Control+Shift+P and then typing "settings" will allow you to easily find the user or workspace settings file.

enter image description here

VBA collection: list of keys

You can easily iterate you collection. The example below is for the special Access TempVars collection, but works with any regular collection.

Dim tv As Long
For tv = 0 To TempVars.Count - 1
    Debug.Print TempVars(tv).Name, TempVars(tv).Value
Next tv

How to verify Facebook access token?

The officially supported method for this is:

GET graph.facebook.com/debug_token?
     input_token={token-to-inspect}
     &access_token={app-token-or-admin-token}

See the check token docs for more information.

An example response is:

{
    "data": {
        "app_id": 138483919580948, 
        "application": "Social Cafe", 
        "expires_at": 1352419328, 
        "is_valid": true, 
        "issued_at": 1347235328, 
        "metadata": {
            "sso": "iphone-safari"
        }, 
        "scopes": [
            "email", 
            "publish_actions"
        ], 
        "user_id": 1207059
    }
}

Calling one Activity from another in Android

check the following code to open new activit.

Intent f = new Intent(MainActivity.this, SecondActivity.class);

startActivity(f);

Android Studio - Failed to notify project evaluation listener error

you need check your gradle version. gradle -v

then you should know your gradle version and your gradle plugin version compatible.

Example:

gradle 4.6 is not compatible with gradle plugin 2.2.

so need update com.android.tools.build:gradle version to 2.3.3.

then you need check gradle/wrapper/gradle-wrapper.properties distributionUrl gradle version

google Android Plugin for Gradle Release Notes

enter image description here

on the other hand

using newer plugin version might require to update Android Studio

thanks @antek

jQuery get text as number

number = parseInt(number);

That should do the trick.

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

In my case I had to enable another extension, namely php_mbstring.dll in the php.ini file before it could work. It's listed under extension=php_mbstring.dll. Find it in the php.ini file and remove the semi-colon (;) in front of it and save the file.

After this run install composer again in the root directory of your Laravel applcication and is should work.

How do you enable mod_rewrite on any OS?

Module rewrite_module is built-in in to the server most cases

Use .htaccess

Use the Mod Rewrite Generator at http://www.generateit.net/mod-rewrite/

Delete specified file from document directory

I checked your code. It's working for me. Check any error you are getting using the modified code below

- (void)removeImage:(NSString *)filename
{
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

  NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
  NSError *error;
  BOOL success = [fileManager removeItemAtPath:filePath error:&error];
  if (success) {
      UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
      [removedSuccessFullyAlert show];
  }
  else
  {
      NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
  }
}

Search all tables, all columns for a specific value SQL Server

I published one here: FullParam SQL Blog

/* Reto Egeter, fullparam.wordpress.com */

DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))

WHILE @TableName IS NOT NULL
BEGIN
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
    )
    IF @TableName IS NOT NULL
    BEGIN
        DECLARE @sql VARCHAR(MAX)
        SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''' + @TableName + ''', 2)
                AND TABLE_NAME  = PARSENAME(''' + @TableName + ''', 1)
                AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
                AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END  + ',COLUMN_NAME)'
        INSERT INTO @ColumnNameTable
        EXEC (@sql)
        WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
        BEGIN
            PRINT @ColumnName
            SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
            SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),''' 
            WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
            ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + ''' 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
            INSERT INTO #Results
            EXEC(@sql)
            IF @@ROWCOUNT > 0 IF @FullRowResult = 1 
            BEGIN
                SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
                    ' FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
                EXEC(@sql)
            END
            DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
        END 
    END
END
SET NOCOUNT OFF

SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType

SMTP connect() failed PHPmailer - PHP

<?php

use PHPMailer\PHPMailer\PHPMailer;

require_once "PHPMailer/src/Exception.php";
require_once "PHPMailer/src/PHPMailer.php";
require_once "PHPMailer/src/SMTP.php";



$mail = new PHPMailer();

$mail ->isSMTP();
$mail ->Host ="smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail ->Username = '[email protected]';
$mail ->Password = 'password';
//$mail ->SMTPSecure=PHPMailer::ENCRYPTION_STARTTLS;
$mail ->Port = '587';
$mail ->SMTPSecure ='tls';
$mail ->isHTML(true);

$mail ->setFrom('[email protected]','email send name');

$mail ->addAddress('[email protected]');
$mail ->Subject = 'HelloWorld';
$mail ->Body = 'a test email';


$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);



if ($mail->send()){
    echo "Message has been sent successfully";
}else{
    echo "Mailer Error: " . $mail->ErrorInfo;
}

?>

make sure that you configure less secure app settings in gmail using this link https://www.google.com/settings/security/lesssecureapps and make sure you downloaded PHPMailer-master.zip from github

working fine with MAMP server locally :)

How to Update Date and Time of Raspberry Pi With out Internet

Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.

This is how it works:

  1. Type sudo raspi-config in the Raspberry Pi command line
  2. Internationalization options
  3. Change Time Zone
  4. Select geographical area
  5. Select city or region
  6. Reboot your pi

Next thing you can set time using this command

sudo date -s "Mon Aug  12 20:14:11 UTC 2014"

More about data and time

man date

When Pi is connected to computer should have to manually set data and time

TypeError: $(...).autocomplete is not a function

you missed jquery ui library. Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

How do I restart a service on a remote machine in Windows?

Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:

Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).

Right click on your computer name and choose "Connect to Remote Computer"

Put in the computer name and credentials and you have full access to many admin functions including the services control panel.

TSQL select into Temp table from dynamic sql

A working example.

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YourTableName'

EXECUTE ('SELECT * INTO #TEMP  FROM ' + @TableName +'; SELECT * FROM #TEMP;')

Second solution with accessible temp table

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YOUR_TABLE_NAME'

EXECUTE ('CREATE VIEW vTemp AS
        SELECT *
        FROM ' + @TableName)
SELECT * INTO #TEMP  FROM vTemp 

--DROP THE VIEW HERE      
DROP VIEW vTemp

/*START USING TEMP TABLE
************************/
--EX:
SELECT * FROM #TEMP


--DROP YOUR TEMP TABLE HERE
DROP TABLE #TEMP

VBA using ubound on a multidimensional array

[This is a late answer addressing the title of the question (since that is what people would encounter when searching) rather than the specifics of OP's question which has already been answered adequately]

Ubound is a bit fragile in that it provides no way to know how many dimensions an array has. You can use error trapping to determine the full layout of an array. The following returns a collection of arrays, one for each dimension. The count property can be used to determine the number of dimensions and their lower and upper bounds can be extracted as needed:

Function Bounds(A As Variant) As Collection
    Dim C As New Collection
    Dim v As Variant, i As Long

    On Error GoTo exit_function
    i = 1
    Do While True
        v = Array(LBound(A, i), UBound(A, i))
        C.Add v
        i = i + 1
    Loop
exit_function:
    Set Bounds = C
End Function

Used like this:

Sub test()
    Dim i As Long
    Dim A(1 To 10, 1 To 5, 4 To 10) As Integer
    Dim B(1 To 5) As Variant
    Dim C As Variant
    Dim sizes As Collection

    Set sizes = Bounds(A)
    Debug.Print "A has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(B)
    Debug.Print vbCrLf & "B has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(C)
    Debug.Print vbCrLf & "C has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i
End Sub

Output:

A has 3 dimensions:
1 to 10
1 to 5
4 to 10

B has 1 dimensions:
1 to 5

C has 0 dimensions:

HTTP Error 503, the service is unavailable

I had the same issue for the longest time and I thought there was an issue with my code. Turns out, in the IIS server, my application pool for that particular project was stopped. I turned it back on and that fixed the issue. Error 503 is most likely related to the Application Pool

Git: how to reverse-merge a commit?

To revert a merge commit, you need to use: git revert -m <parent number>. So for example, to revert the recent most merge commit using the parent with number 1 you would use:

git revert -m 1 HEAD

To revert a merge commit before the last commit, you would do:

git revert -m 1 HEAD^

Use git show <merge commit SHA1> to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2

git merge documentation: http://schacon.github.com/git/git-merge.html

git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt

How to add new DataRow into DataTable?

You can try with this code - based on Rows.Add method

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

Link : https://msdn.microsoft.com/en-us/library/9yfsd47w.aspx

How to connect to LocalDb

I think you hit the same issue as discussed in this post. You forgot to escape your \ character.

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

We can also try this solution

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml");

in this the spring automatically finds the class in the class path itself

What are the differences between JSON and JSONP?

Basically, you're not allowed to request JSON data from another domain via AJAX due to same-origin policy. AJAX allows you to fetch data after a page has already loaded, and then execute some code/call a function once it returns. We can't use AJAX but we are allowed to inject <script> tags into our own page and those are allowed to reference scripts hosted at other domains.

Usually you would use this to include libraries from a CDN such as jQuery. However, we can abuse this and use it to fetch data instead! JSON is already valid JavaScript (for the most part), but we can't just return JSON in our script file, because we have no way of knowing when the script/data has finished loading and we have no way of accessing it unless it's assigned to a variable or passed to a function. So what we do instead is tell the web service to call a function on our behalf when it's ready.

For example, we might request some data from a stock exchange API, and along with our usual API parameters, we give it a callback, like ?callback=callThisWhenReady. The web service then wraps the data with our function and returns it like this: callThisWhenReady({...data...}). Now as soon as the script loads, your browser will try to execute it (as normal), which in turns calls our arbitrary function and feeds us the data we wanted.

It works much like a normal AJAX request except instead of calling an anonymous function, we have to use named functions.

jQuery actually supports this seamlessly for you by creating a uniquely named function for you and passing that off, which will then in turn run the code you wanted.

html5 - canvas element - Multiple layers

You can create multiple canvas elements without appending them into document. These will be your layers:

Then do whatever you want with them and at the end just render their content in proper order at destination canvas using drawImage on context.

Example:

/* using canvas from DOM */
var domCanvas = document.getElementById('some-canvas');
var domContext = domCanvas.getContext('2d');
domContext.fillRect(50,50,150,50);

/* virtual canvase 1 - not appended to the DOM */
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50,50,150,150);

/* virtual canvase 2 - not appended to the DOM */    
var canvas2 = document.createElement('canvas')
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'yellow';
ctx2.fillRect(50,50,100,50)

/* render virtual canvases on DOM canvas */
domContext.drawImage(canvas, 0, 0, 200, 200);
domContext.drawImage(canvas2, 0, 0, 200, 200);

And here is some codepen: https://codepen.io/anon/pen/mQWMMW

How to replace url parameter with javascript/jquery?

If you are having very narrow and specific use-case like replacing a particular parameter of given name that have alpha-numeric values with certain special characters capped upto certain length limit, you could try this approach:

urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue);

Example:

let urlValue = 'www.example.com?a=b&src=test-value&p=q';
const newValue = 'sucess';
console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue));
// output - www.example.com?a=b&src=sucess&p=q

How do I find out what version of Sybase is running

Run this command:

select @@version

Writing new lines to a text file in PowerShell

It's also possible to assign newline and carriage return to variables and then append them to texts inside PowerShell scripts:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg

How do I declare and initialize an array in Java?

Array is a sequential list of items

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};

If it's an object, then it's the same concept

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};

In case of objects, you need to either assign it to null to initialize them using new Type(..), classes like String and Integer are special cases that will be handled as following

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };

In general you can create arrays that's M dimensional

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

It's worthy to note that creating an M dimensional array is expensive in terms of Space. Since when you create an M dimensional array with N on all the dimensions, The total size of the array is bigger than N^M, since each array has a reference, and at the M-dimension there is an (M-1)-dimensional array of references. The total size is as following

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data

Getting HTTP code in PHP using curl

Try PHP's "get_headers" function.

Something along the lines of:

<?php
    $url = 'http://www.example.com';
    print_r(get_headers($url));
    print_r(get_headers($url, 1));
?>

Biggest differences of Thrift vs Protocol Buffers?

As I've said as "Thrift vs Protocol buffers" topic :

Referring to Thrift vs Protobuf vs JSON comparison :

Additionally, there are plenty of interesting additional tools available for those solutions, which might decide. Here are examples for Protobuf: Protobuf-wireshark , protobufeditor.

VBScript to send email without running Outlook

Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line

Blat is here

How do I remove accents from characters in a PHP string?

The easiest way is to use iconv() PHP native function.

 echo iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', "Thîs îs à vêry wrong séntènce!");

 // output: This is a very wrong sentence!

How to add an element to a list?

I would do this:

data["list"].append({'b':'2'})

so simply you are adding an object to the list that is present in "data"

Getting a directory name from a filename

Just use this: ExtractFilePath(your_path_file_name)

Permission to write to the SD card

The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
  protected override void OnCreate(Bundle bindle)
  {
    base.OnCreate(bindle);
  }
}

Java 8: merge lists with stream API

I think flatMap() is what you're looking for.

For example:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());

How to get param from url in angular 4?

import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.paramMap
    .subscribe( params => {
    let id = +params.get('id');
    console.log('id' + id);
    console.log(params);


id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
        }
        )

      }

Return multiple values from a function, sub or type?

Ideas :

  1. Use pass by reference (ByRef)
  2. Build a User Defined Type to hold the stuff you want to return, and return that.
  3. Similar to 2 - build a class to represent the information returned, and return objects of that class...

Difference between break and continue statement

break completely exits the loop. continue skips the statements after the continue statement and keeps looping.

HTML CSS Invisible Button

HTML

<input type="button">

CSS

input[type=button]{
 background:transparent;
 border:0;
}

How to resize image automatically on browser width resize but keep same height?

I've used Perfect Full Page Background Image to accomplish this on a previous site.

You can use background-size: cover; if you only need to support modern browsers.

Running Python on Windows for Node.js dependencies

This helped: https://www.npmjs.com/package/node-gyp

I followed these steps:

npm install -g node-gyp

then:

npm install --global --production windows-build-tools

Regex expressions in Java, \\s vs. \\s+

The first regex will match one whitespace character. The second regex will reluctantly match one or more whitespace characters. For most purposes, these two regexes are very similar, except in the second case, the regex can match more of the string, if it prevents the regex match from failing.  from http://www.coderanch.com/t/570917/java/java/regex-difference

ERROR in ./node_modules/css-loader?

I tried both

npm rebuild node-sass

and

npm install --save node-sass

Later by seeing EACCESS, i checked the folder permission of /node_modules, which was not 777 permission

Then I gave

chmod -R 777 *

-R for recursively(setting the same permission not in the dir but also inside nested sub dir) * is for all files in current directory

What is file permission

To check for permission you can use

ls -l

If u don't know about it, first see here, then check the url

Every file and directory has permission of 'rwx'(read, write, execute). and if 'x' permission is not there, then you can not execture, if no 'w', you can not write into the file. if some thing is missiing it will show in place of r/w/x with '-'. So, if 'x' permission is not there, it will show like 'rw-'

And there will be 3 category of user Owner(who created the file/directory), Group(some people who shares same permission and user previlege), Others(general public)

So 1st letter is 'd'(if it is a directory) or '-'(if it is not a directory), followed by rwx for owner, followed by for group, followed by other

drwxrwxrwx

For example, for 'node_modules'directory I want to give permission to owner all permission and for rest only read, then it will be

drwxr--r--

And about the number assume for 'r/w/x' it is 1 and for '-' it is 0, 777, first 7 is for owner, followed by group, followed by other

Let's assume the permission is rwxr-xrw-

Now 'rwx' is like '111' and it's equivalent decimal is 1*2^2+1*2^1+1*2^0=7

Now 'r-x' is like '101' and it's equivalent decimal is 1*2^2+0*2^1+1*2^0=5

Now 'rw-' is like '110' and it's equivalent decimal is 1*2^2+1*2^1+0*2^0=6

So, it will be 756

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

I discovered an error in my first post, so I decided to sit down and do the the math. What I found is that the number system used to identify Excel columns is not a base 26 system, as another person posted. Consider the following in base 10. You can also do this with the letters of the alphabet.

Space:.........................S1, S2, S3 : S1, S2, S3
....................................0, 00, 000 :.. A, AA, AAA
....................................1, 01, 001 :.. B, AB, AAB
.................................... …, …, … :.. …, …, …
....................................9, 99, 999 :.. Z, ZZ, ZZZ
Total states in space: 10, 100, 1000 : 26, 676, 17576
Total States:...............1110................18278

Excel numbers columns in the individual alphabetical spaces using base 26. You can see that in general, the state space progression is a, a^2, a^3, … for some base a, and the total number of states is a + a^2 + a^3 + … .

Suppose you want to find the total number of states A in the first N spaces. The formula for doing so is A = (a)(a^N - 1 )/(a-1). This is important because we need to find the space N that corresponds to our index K. If I want to find out where K lies in the number system I need to replace A with K and solve for N. The solution is N = log{base a} (A (a-1)/a +1). If I use the example of a = 10 and K = 192, I know that N = 2.23804… . This tells me that K lies at the beginning of the third space since it is a little greater than two.

The next step is to find exactly how far in the current space we are. To find this, subtract from K the A generated using the floor of N. In this example, the floor of N is two. So, A = (10)(10^2 – 1)/(10-1) = 110, as is expected when you combine the states of the first two spaces. This needs to be subtracted from K because these first 110 states would have already been accounted for in the first two spaces. This leaves us with 82 states. So, in this number system, the representation of 192 in base 10 is 082.

The C# code using a base index of zero is

    private string ExcelColumnIndexToName(int Index)
    {
        string range = string.Empty;
        if (Index < 0 ) return range;
        int a = 26;
        int x = (int)Math.Floor(Math.Log((Index) * (a - 1) / a + 1, a));
        Index -= (int)(Math.Pow(a, x) - 1) * a / (a - 1);
        for (int i = x+1; Index + i > 0; i--)
        {
            range = ((char)(65 + Index % a)).ToString() + range;
            Index /= a;
        }
        return range;
    }

//Old Post

A zero-based solution in C#.

    private string ExcelColumnIndexToName(int Index)
    {
        string range = "";
        if (Index < 0 ) return range;
        for(int i=1;Index + i > 0;i=0)
        {
            range = ((char)(65 + Index % 26)).ToString() + range;
            Index /= 26;
        }
        if (range.Length > 1) range = ((char)((int)range[0] - 1)).ToString() + range.Substring(1);
        return range;
    }

Make <body> fill entire screen?

Try using viewport (vh, vm) units of measure at the body level

html, body { margin: 0; padding: 0; } body { min-height: 100vh; }

Use vh units for horizontal margins, paddings, and borders on the body and subtract them from the min-height value.

I've had bizarre results using vh,vm units on elements within the body, especially when re-sizing.

How to communicate between iframe and the parent site?

This library supports HTML5 postMessage and legacy browsers with resize+hash https://github.com/ternarylabs/porthole

Edit: Now in 2014, IE6/7 usage is quite low, IE8 and above all support postMessage so I now suggest to just use that.

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

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

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

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

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

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

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

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

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

R solve:system is exactly singular

I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.

Select data between a date/time range

You need to update the date format:

select * from hockey_stats 
where game_date between '2012-03-11 00:00:00' and '2012-05-11 23:59:00' 
order by game_date desc;

Connect to docker container as user other than root

Execute command as www-data user: docker exec -t --user www-data container bash -c "ls -la"

How to create an AVD for Android 4.0

This site Android Create AVD shows you how to install the latest version of the Android SDK and AVD version 4 in Eclipse with video and screenshots if you're still stuck?

How can a windows service programmatically restart itself?

Set the service to restart after failure (double click the service in the control panel and have a look around on those tabs - I forget the name of it). Then, anytime you want the service to restart, just call Environment.Exit(1) (or any non-zero return) and the OS will restart it for you.

Evaluate empty or null JSTL c tags

Here's the one liner.

Ternary operator inside EL

${empty value?'value is empty or null':'value is NOT empty or null'}

Angular2 multiple router-outlet in the same template

Yes you can as said by @tomer above. i want to add some point to @tomer answer.

  • firstly you need to provide name to the router-outlet where you want to load the second routing view in your view. (aux routing angular2.)
  • In angular2 routing few important points are here.

    • path or aux (requires exactly one of these to give the path you have to show as the url).
    • component, loader, redirectTo (requires exactly one of these, which component you want to load on routing)
    • name or as (optional) (requires exactly one of these, the name which specify at the time of routerLink)
    • data (optional, whatever you want to send with the routing that you have to get using routerParams at the receiver end.)

for more info read out here and here.

import {RouteConfig, AuxRoute} from 'angular2/router';
@RouteConfig([
  new AuxRoute({path: '/home', component: HomeCmp})
])
class MyApp {}

Multiple commands on a single line in a Windows batch file

Use:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.


That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal

Why doesn't JavaScript support multithreading?

Multi-threading with javascript is clearly possible using webworkers bring by HTML5.

Main difference between webworkers and a standard multi-threading environment is memory resources are not shared with the main thread, a reference to an object is not visible from one thread to another. Threads communicate by exchanging messages, it is therefore possible to implement a synchronzization and concurrent method call algorithm following an event-driven design pattern.

Many frameworks exists allowing to structure programmation between threads, among them OODK-JS, an OOP js framework supporting concurrent programming https://github.com/GOMServices/oodk-js-oop-for-js

Import Excel Spreadsheet Data to an EXISTING sql table?

Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.

I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.

How to specify a multi-line shell variable?

I would like to give one additional answer, while the other ones will suffice in most cases.

I wanted to write a string over multiple lines, but its contents needed to be single-line.

sql="                       \
SELECT c1, c2               \
from Table1, ${TABLE2}      \
where ...                   \
"

I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

SWIFT

Well I did this in the following order and didn't get any error like Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service after that, following code might help you too.

webView = WKWebView(frame: self.view.frame)
self.view.addSubview(self.view.webView)
webView.navigationDelegate = self
webView.loadHTMLString(htmlString, baseURL: nil)

Do as order.

Thanks

Changing the tmp folder of mysql

You should edit your my.cnf

tmpdir = /whatewer/you/want

and after that restart mysql

P.S. Don't forget give write permissions to /whatewer/you/want for mysql user

Deserializing JSON array into strongly typed .NET object

try

List<TheUser> friends = jsonSerializer.Deserialize<List<TheUser>>(response);

Generating random numbers with normal distribution in Excel

The numbers generated by

=NORMINV(RAND(),10,7)

are uniformally distributed. If you want the numbers to be normally distributed, you will have to write a function I guess.

Using cURL with a username and password?

You can use command like,

curl -u user-name -p http://www.example.com/path-to-file/file-name.ext > new-file-name.ext

Then HTTP password will be triggered.

Reference: http://www.asempt.com/article/how-use-curl-http-password-protected-site

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

git pull error "The requested URL returned error: 503 while accessing"

It was the service issue from the git. The site will be under maintenance. Please try once after the maintenance work is done.

How to get a certain element in a list, given the position?

std::list<Object> l; 
std::list<Object>::iterator ptr;
int i;

for( i = 0 , ptr = l.begin() ; i < N && ptr != l.end() ; i++ , ptr++ );

if( ptr == l.end() ) {
    // list too short  
} else {
    // 'ptr' points to N-th element of list
}

Scale an equation to fit exact page width

The graphicx package provides the command \resizebox{width}{height}{object}:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
 A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}

Ignore outliers in ggplot2 boxplot

Use geom_boxplot(outlier.shape = NA) to not display the outliers and scale_y_continuous(limits = c(lower, upper)) to change the axis limits.

An example.

n <- 1e4L
dfr <- data.frame(
  y = exp(rlnorm(n)),  #really right-skewed variable
  f = gl(2, n / 2)
)

p <- ggplot(dfr, aes(f, y)) + 
  geom_boxplot()
p   # big outlier causes quartiles to look too slim

p2 <- ggplot(dfr, aes(f, y)) + 
  geom_boxplot(outlier.shape = NA) +
  scale_y_continuous(limits = quantile(dfr$y, c(0.1, 0.9)))
p2  # no outliers plotted, range shifted

Actually, as Ramnath showed in his answer (and Andrie too in the comments), it makes more sense to crop the scales after you calculate the statistic, via coord_cartesian.

coord_cartesian(ylim = quantile(dfr$y, c(0.1, 0.9)))

(You'll probably still need to use scale_y_continuous to fix the axis breaks.)

How to pass variable from jade template file to a script file?

In my case, I was attempting to pass an object into a template via an express route (akin to OPs setup). Then I wanted to pass that object into a function I was calling via a script tag in a pug template. Though lagginreflex's answer got me close, I ended up with the following:

script.
    var data = JSON.parse('!{JSON.stringify(routeObj)}');
    funcName(data)

This ensured the object was passed in as expected, rather than needing to deserialise in the function. Also, the other answers seemed to work fine with primitives, but when arrays etc. were passed along with the object they were parsed as string values.

PHP foreach change original array values

function checkForm(& $fields){
    foreach($fields as $field){
        if($field['required'] && strlen($_POST[$field['name']]) <= 0){
            $fields[$field]['value'] = "Some error";
        }
    }
    return $fields;
}

This is what I would Suggest pass by reference

Set cookie and get cookie with JavaScript

These are much much better references than w3schools (the most awful web reference ever made):

Examples derived from these references:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use.

javac : command not found

This worked for me: sudo dnf install java-<version>-devel

Move view with keyboard using Swift

i've read answers and solved my problem by this lines of code:

class ViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var titleField: UITextField!
  @IBOutlet weak var priceField: UITextField!
  @IBOutlet weak var detailsField: UTtextField!

  override func viewDidLoad() {
   super.viewDidLoad()
// Do not to forget to set the delegate otherwise the textFieldShouldReturn(_:)
// won't work and the keyboard will never be hidden.
   priceField.delegate = self
   titleField.delegate = self
   detailsField.delegate = self

   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
 name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
 name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  }

   func textFieldShouldReturn(_ textField: UITextField) -> Bool {
      self.view.endEditing(true)
      return false
   }

 func keyboardWillShow(notification: NSNotification) {
   var translation:CGFloat = 0
   if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
     if detailsField.isEditing{
       translation = CGFloat(-keyboardSize.height)
     }else if priceField.isEditing{
       translation = CGFloat(-keyboardSize.height / 3.8)
     }
   }
    UIView.animate(withDuration: 0.2) {
   self.view.transform = CGAffineTransform(translationX: 0, y: translation)
    }
  }


 func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.2) {
     self.view.transform = CGAffineTransform(translationX: 0, y: 0)
    } 
  }
}

I have a few UITextFields and want the view to move up differently depending on which textField is tapped.

Foreign Key Django Model

I would advise, it is slightly better practise to use string model references for ForeignKey relationships if utilising an app based approach to seperation of logical concerns .

So, expanding on Martijn Pieters' answer:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        'app_label.Anniversary', on_delete=models.CASCADE)
    address = models.ForeignKey(
        'app_label.Address', on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Unit testing private methods in C#

Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...

In other words...

No, first things first.

Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.

Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.

In this case, the usual suspects are: OCP, SRP, and, as always, KIS.

But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.

What am I talking about?

private double TranslateMeasurementIntoLinear(double actualMeasurement);

It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.

To make this fairy tale short: We need a simple way to test private methods--without ado.

First: Happy new year everyone!

Second: Rehearse your architect lessons.

Third: The "public" modifier is religion, not a solution.

Maximum number of rows in an MS Access database engine table?

It's been some years since I last worked with Access but larger database files always used to have more problems and be more prone to corruption than smaller files.

Unless the database file is only being accessed by one person or stored on a robust network you may find this is a problem before the 2GB database size limit is reached.

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

I really like following clean solution.

class Router
  include Rails.application.routes.url_helpers

  def self.default_url_options
    ActionMailer::Base.default_url_options
  end
end

router = Router.new
router.posts_url  # http://localhost:3000/posts
router.posts_path # /posts

It's from http://hawkins.io/2012/03/generating_urls_whenever_and_wherever_you_want/

Replace non-numeric with empty string

I'm sure there's a more efficient way to do it, but I would probably do this:

string getTenDigitNumber(string input)
{    
    StringBuilder sb = new StringBuilder();
    for(int i - 0; i < input.Length; i++)
    {
        int junk;
        if(int.TryParse(input[i], ref junk))
            sb.Append(input[i]);
    }
    return sb.ToString();
}

Mockito matcher and array of primitives

Try this:

AdditionalMatchers.aryEq(array);

Sass calculate percent minus px

Just add the percentage value into a variable and use #{$variable} for example

$twentyFivePercent:25%;
.selector {
    height: calc(#{$twentyFivePercent} - 5px);
}

Making div content responsive

@media screen and (max-width : 760px) (for tablets and phones) and use with this: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views

How to exit an if clause

may be this?

if some_condition and condition_a:
       # do something
elif some_condition and condition_b:
           # do something
           # and then exit the outer if block
elif some_condition and not condition_b:
           # more code here
else:
     #blah
if

Table fixed header and scrollable body

I made some kinda working CSS only solution by using position: sticky. Should work on evergreen browsers. Try to resize browser. Still have some layout issue in FF, will fix it later, but at least table headers handle vertical and horizontal scrolling. Codepen Example

Arrays vs Vectors: Introductory Similarities and Differences

Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:

int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;

for vectors, you just declare it and add elements

vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...

at times you wont know the number of elements needed so a vector would be ideal for such a situation.

Get DateTime.Now with milliseconds precision

public long millis() {
  return (long.MaxValue + DateTime.Now.ToBinary()) / 10000;
}

If you want microseconds, just change 10000 to 10, and if you want the 10th of micro, delete / 10000.

C++ Calling a function from another class

class B is only declared but not defined at the beginning, which is what the compiler complains about. The root cause is that in class A's Call Function, you are referencing instance b of type B, which is incomplete and undefined. You can modify source like this without introducing new file(just for sake of simplicity, not recommended in practice):

using namespace std;

class A 
{
public:

    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    {
        //stuff done here
    }
};


 // postpone definition of CallFunction here

 void A::CallFunction ()
 {
     B b;
     b.bFunction();
 }

Property 'map' does not exist on type 'Observable<Response>'

Angular 9:

 forkJoin([
  this.http.get().pipe(
    catchError((error) => {
      return of([]);
    })
  ),
  this.http.get().pipe(
    catchError((error) => {
      return of([]);
    })
  ),

Export table data from one SQL Server to another

Just to show yet another option (for SQL Server 2008 and above):

  1. right-click on Database -> select 'Tasks' -> select 'Generate Scripts'
  2. Select specific database objects you want to copy. Let's say one or more tables. Click Next
  3. Click Advanced and scroll down to 'Types of Data to script' and choose 'Schema and Data'. Click OK
  4. Choose where to save generated script and proceed by clicking Next

Using external images for CSS custom cursors

It wasn't working because your image was too big - there are restrictions on the image dimensions. In Firefox, for example, the size limit is 128x128px. See this page for more details.

Additionally, you also have to add in auto.

jsFiddle demo here - note that's an actual image, and not a default cursor.

_x000D_
_x000D_
.test {_x000D_
  background:gray;_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
  cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif), auto;_x000D_
}
_x000D_
<div class="test">TEST</div>
_x000D_
_x000D_
_x000D_

How do I get rid of the b-prefix in a string in python?

I got it done by only encoding the output using utf-8. Here is the code example

new_tweets = api.GetUserTimeline(screen_name = user,count=200)
result = new_tweets[0]
try: text = result.text
except: text = ''

with open(file_name, 'a', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(text)

i.e: do not encode when collecting data from api, encode the output (print or write) only.

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

This error is also thrown if the update command is used on a project instrumented for code coverage with Clover.

To resolve in this scenario: Un-instrument the project folders you wish to update. Run the maven update then instrument for code coverage again.

Having issues with a MySQL Join that needs to meet multiple conditions

also this should work (not tested):

SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc

If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

to convert a TimestampTZ in oracle, you do

TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') 
  at time zone 'region'

see here: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#NLSPG264

and here for regions: http://docs.oracle.com/cd/E11882_01/server.112/e10729/applocaledata.htm#NLSPG0141

eg:

SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
09-APR-13 01.10.21.000000000 -05:00


SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-MAR-13 01.10.21.000000000 CST
09-MAR-13 07.10.21.000000000
09-MAR-13 02.10.21.000000000 -05:00

SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'AMERICA/LOS_ANGELES'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
08-APR-13 23.10.21.000000000 AMERICA/LOS_ANGELES

How to retrieve Jenkins build parameters using the Groovy API?

To get the parameterized build params from the current build from your GroovyScript (using Pipeline), all you need to do is: Say you had a variable called VARNAME.

def myVariable = env.VARNAME

SQL Update to the SUM of its joined values

This is a valid error. See this. Following (and others suggested below) are the ways to achieve this:-

UPDATE P 
SET extrasPrice = t.TotalPrice
FROM BookingPitches AS P INNER JOIN
 (
  SELECT
    PitchID,
    SUM(Price) TotalPrice
  FROM
     BookingPitchExtras
  GROUP BY PitchID
  ) t
ON t.PitchID = p.ID

Subclipse svn:ignore

I just figured out how to do this:

It appears that when you add a parent folder to version control, Eclipse adds all sub-folders. Once the sub-folders are added to version control, it is not possible to ignore them.

Here's how to do it:

Right click on the top level folder and add to version control Right click on the child folder you want to ignore, revert Right click on the child folder you want to ignore, svn:ignore (which will now be available)

How to get a div to resize its height to fit container?

Unfortunately, there is no fool-proof way of achieving this. A block will only expand to the height of its container if it is not floated. Floated blocks are considered outside of the document flow.

One way to do the following without using JavaScript is via a technique called Faux-Columns.

It basically involves applying a background-image to the parent elements of the floated elements which makes you believe that the two elements are the same height.

More information available at:

A List Apart: Articles: Faux Columns

How to prevent scientific notation in R?

To set the use of scientific notation in your entire R session, you can use the scipen option. From the documentation (?options):

‘scipen’: integer.  A penalty to be applied when deciding to print
          numeric values in fixed or exponential notation.  Positive
          values bias towards fixed and negative towards scientific
          notation: fixed notation will be preferred unless it is more
          than ‘scipen’ digits wider.

So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999:

options(scipen=999)

How to make blinking/flashing text with CSS 3

@-webkit-keyframes blinker {  
  0% { opacity: 1.0; }
  50% { opacity: 0.0; }
  100% { opacity: 1.0; }
}

_x000D_
_x000D_
@-webkit-keyframes blinker {  _x000D_
  0% { opacity: 1.0; }_x000D_
  50% { opacity: 0.0; }_x000D_
  100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
.blink {_x000D_
  width: 10px;_x000D_
  height: 10px;_x000D_
  border-radius: 10px;_x000D_
  animation: blinker 2s linear infinite;_x000D_
  background-color: red;_x000D_
  margin-right: 5px;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: center;_x000D_
}
_x000D_
<div class="content">_x000D_
  <i class="blink"></i>_x000D_
  LIVE_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to playback MKV video in web browser?

<video controls width=800 autoplay>
    <source src="file path here">
</video>

This will display the video (.mkv) using Google Chrome browser only.

Convert Date/Time for given Timezone - java

A quick way is :

String dateText ="Thu, 02 Jul 2015 21:51:46";
long hours = -5; // time difference between places

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(E, dd MMM yyyy HH:mm:ss, Locale.ENGLISH);     
LocalDateTime date = LocalDateTime.parse(dateText, formatter);        
date = date.with(date.plusHours(hours));

System.out.println("NEW DATE: "+date);

Output

NEW DATE: 2015-07-02T16:51:46

Simple and clean way to convert JSON string to Object in Swift

Here are some tips how to begin with simple example.

Consider you have following JSON Array String (similar to yours) like:

 var list:Array<Business> = []

  // left only 2 fields for demo
  struct Business {
    var id : Int = 0
    var name = ""               
 }

 var jsonStringAsArray = "[\n" +
        "{\n" +
        "\"id\":72,\n" +
        "\"name\":\"Batata Cremosa\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":183,\n" +
        "\"name\":\"Caldeirada de Peixes\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":76,\n" +
        "\"name\":\"Batata com Cebola e Ervas\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":56,\n" +
        "\"name\":\"Arroz de forma\",\n" +            
    "}]"


        // convert String to NSData
        var data: NSData = jsonStringAsArray.dataUsingEncoding(NSUTF8StringEncoding)!
        var error: NSError?

        // convert NSData to 'AnyObject'
        let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0),
            error: &error)
        println("Error: \(error)")

     // convert 'AnyObject' to Array<Business>
     list = self.parseJson(anyObj!)

     //===============

    func parseJson(anyObj:AnyObject) -> Array<Business>{

        var list:Array<Business> = []

         if  anyObj is Array<AnyObject> {

            var b:Business = Business()

            for json in anyObj as Array<AnyObject>{
             b.name = (json["name"] as AnyObject? as? String) ?? "" // to get rid of null
             b.id  =  (json["id"]  as AnyObject? as? Int) ?? 0                 

               list.append(b)
            }// for

        } // if

      return list

    }//func    

[EDIT]

To get rid of null changed to:

b.name = (json["name"] as AnyObject? as? String) ?? ""
b.id  =  (json["id"]  as AnyObject? as? Int) ?? 0 

See also Reference of Coalescing Operator (aka ??)

Hope it will help you to sort things out,

.NET - Get protocol, host, and port

A more structured way to get this is to use UriBuilder. This avoids direct string manipulation.

var builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);

Python Variable Declaration

Variables have scope, so yes it is appropriate to have variables that are specific to your function. You don't always have to be explicit about their definition; usually you can just use them. Only if you want to do something specific to the type of the variable, like append for a list, do you need to define them before you start using them. Typical example of this.

list = []
for i in stuff:
  list.append(i)

By the way, this is not really a good way to setup the list. It would be better to say:

list = [i for i in stuff] # list comprehension

...but I digress.

Your other question. The custom object should be a class itself.

class CustomObject(): # always capitalize the class name...this is not syntax, just style.
  pass
customObj = CustomObject()

How To Make Circle Custom Progress Bar in Android

I'd make a new view class and derive from the existing ProgressBar. Then override the onDraw function. You're going to need to make direct draw calls to the canvas for this, since its so custom- a combination of drawText, drawArc, and drawOval should do it- an oval for the outer ring and empty portions, and an arc for the colored in parts. You may end up needing to override onMeasure and onLayout as well. Then in your xml, reference this view by class name like this when you want to use it.

How can I dynamically set the position of view in Android?

For support to all API levels you can use it like this:

ViewPropertyAnimator.animate(view).translationYBy(-yourY).translationXBy(-yourX).setDuration(0);

How do I get TimeSpan in minutes given two Dates?

See TimeSpan.TotalMinutes:

Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

How to search all loaded scripts in Chrome Developer Tools?

In Widows it is working for me. Control Shift F and then it opens a search window at the bottom. Make sure you expand the bottom area to see the new search window.

enter image description here

How to deal with the URISyntaxException

A general solution requires parsing the URL into a RFC 2396 compliant URI (note that this is an old version of the URI standard, which java.net.URI uses).

I have written a Java URL parsing library that makes this possible: galimatias. With this library, you can achieve your desired behaviour with this code:

String urlString = //...
URLParsingSettings settings = URLParsingSettings.create()
  .withStandard(URLParsingSettings.Standard.RFC_2396);
URL url = URL.parse(settings, urlString);

Note that galimatias is in a very early stage and some features are experimental, but it is already quite solid for this use case.

path.join vs path.resolve with __dirname

const absolutePath = path.join(__dirname, some, dir);

vs.

const absolutePath = path.resolve(__dirname, some, dir);

path.join will concatenate __dirname which is the directory name of the current file concatenated with values of some and dir with platform-specific separator.

Whereas

path.resolve will process __dirname, some and dir i.e. from right to left prepending it by processing it.

If any of the values of some or dir corresponds to a root path then the previous path will be omitted and process rest by considering it as root

In order to better understand the concept let me explain both a little bit more detail as follows:-

The path.join and path.resolve are two different methods or functions of the path module provided by nodejs.

Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.

path.join concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

When no arguments supplied

The following example will help you to clearly understand both concepts:-

My filename is index.js and the current working directory is E:\MyFolder\Pjtz\node

const path = require('path');

console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname

Result

? node index.js
path.join() :  .
path.resolve() :  E:\MyFolder\Pjtz\node

path.resolve() method will output the absolute path whereas the path.join() returns . representing the current working directory if nothing is provided

When some root path is passed as arguments

const path=require('path');

console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));

Result i

? node index.js
path.join() :  abc\bcd
path.resolve() :  E:\bcd

path.join() only concatenates the input list with platform-specific separator while the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

how to create a Java Date object of midnight today and midnight tomorrow?

JDK8 - Java Time Module way:

LocalDateTime todayMidnight = LocalDate.now().atStartOfDay();

Also work:

LocalDateTime todayMidnight = LocalDateTime.now().with(LocalTime.MIDNIGHT);

Lua string to int

It should be noted that math.floor() always rounds down, and therefore does not yield a sensible result for negative floating point values.

For example, -10.4 represented as an integer would usually be either truncated or rounded to -10. Yet the result of math.floor() is not the same:

math.floor(-10.4) => -11

For truncation with type conversion, the following helper function will work:

function tointeger( x )
    num = tonumber( x )
    return num < 0 and math.ceil( num ) or math.floor( num )
end

Reference: http://lua.2524044.n2.nabble.com/5-3-Converting-a-floating-point-number-to-integer-td7664081.html

How to import existing *.sql files in PostgreSQL 8.4?

From the command line:

psql -f 1.sql
psql -f 2.sql

From the psql prompt:

\i 1.sql
\i 2.sql

Note that you may need to import the files in a specific order (for example: data definition before data manipulation). If you've got bash shell (GNU/Linux, Mac OS X, Cygwin) and the files may be imported in the alphabetical order, you may use this command:

for f in *.sql ; do psql -f $f ; done

Here's the documentation of the psql application (thanks, Frank): http://www.postgresql.org/docs/current/static/app-psql.html

How do I convert Int/Decimal to float in C#?

It is just:

float f = (float)6;

add maven repository to build.gradle

Android Studio Users:

If you want to use grade, go to http://search.maven.org/ and search for your maven repo. Then, click on the "latest version" and in the details page on the bottom left you will see "Gradle" where you can then copy/paste that link into your app's build.gradle.

enter image description here

How to insert text in a td with id, using JavaScript

If your <td> is not empty, one popular trick is to insert a non breaking space &nbsp; in it, such that:

 <td id="td1">&nbsp;</td>

Then you will be able to use:

 document.getElementById('td1').firstChild.data = 'New Value';

Otherwise, if you do not fancy adding the meaningless &nbsp you can use the solution that Jonathan Fingland described in the other answer.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.

cannot connect to pc-name\SQLEXPRESS

I had this problem. So I put like this: PC-NAME\SQLSERVER Since the SQLSERVER the instance name that was set at installation.

Authentication: Windows Authentication

Connects !!!

How to parse a month name (string) to an integer for comparison in C#?

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int> mapping the month's name to its value.

Check if a PHP cookie exists and if not set its value

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

How do I iterate through the files in a directory in Java?

If you are using Java 1.7, you can use java.nio.file.Files.walkFileTree(...).

For example:

public class WalkFileTreeExample {

  public static void main(String[] args) {
    Path p = Paths.get("/usr");
    FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
          throws IOException {
        System.out.println(file);
        return FileVisitResult.CONTINUE;
      }
    };

    try {
      Files.walkFileTree(p, fv);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

If you are using Java 8, you can use the stream interface with java.nio.file.Files.walk(...):

public class WalkFileTreeExample {

  public static void main(String[] args) {
    try (Stream<Path> paths = Files.walk(Paths.get("/usr"))) {
      paths.forEach(System.out::println);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

How do I enable/disable log levels in Android?

I took a simple route - creating a wrapper class that also makes use of variable parameter lists.

 public class Log{
        public static int LEVEL = android.util.Log.WARN;


    static public void d(String tag, String msgFormat, Object...args)
    {
        if (LEVEL<=android.util.Log.DEBUG)
        {
            android.util.Log.d(tag, String.format(msgFormat, args));
        }
    }

    static public void d(String tag, Throwable t, String msgFormat, Object...args)
    {
        if (LEVEL<=android.util.Log.DEBUG)
        {
            android.util.Log.d(tag, String.format(msgFormat, args), t);
        }
    }

    //...other level logging functions snipped

Python: Best way to add to sys.path relative to the current running script

You can run the script with python -m from the relevant root dir. And pass the "modules path" as argument.

Example: $ python -m module.sub_module.main # Notice there is no '.py' at the end.


Another example:

$ tree  # Given this file structure
.
+-- bar
¦   +-- __init__.py
¦   +-- mod.py
+-- foo
    +-- __init__.py
    +-- main.py

$ cat foo/main.py
from bar.mod import print1
print1()

$ cat bar/mod.py
def print1():
    print('In bar/mod.py')

$ python foo/main.py  # This gives an error
Traceback (most recent call last):
  File "foo/main.py", line 1, in <module>
    from bar.mod import print1
ImportError: No module named bar.mod

$ python -m foo.main  # But this succeeds
In bar/mod.py

How can I open multiple files using "with open" in Python?

Since Python 3.3, you can use the class ExitStack from the contextlib module to safely
open an arbitrary number of files.

It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.

In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

If you are interested in the details, here is a generic example in order to explain how ExitStack operates:

from contextlib import ExitStack

class X:
    num = 1

    def __init__(self):
        self.num = X.num
        X.num += 1

    def __repr__(self):
        cls = type(self)
        return '{cls.__name__}{self.num}'.format(cls=cls, self=self)

    def __enter__(self):
        print('enter {!r}'.format(self))
        return self.num

    def __exit__(self, exc_type, exc_value, traceback):
        print('exit {!r}'.format(self))
        return True

xs = [X() for _ in range(3)]

with ExitStack() as stack:
    print(len(stack._exit_callbacks)) # number of callbacks called on exit
    nums = [stack.enter_context(x) for x in xs]
    print(len(stack._exit_callbacks))

print(len(stack._exit_callbacks))
print(nums)

Output:

0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]

When do you use Java's @Override annotation and why?

I always use the tag. It is a simple compile-time flag to catch little mistakes that I might make.

It will catch things like tostring() instead of toString()

The little things help in large projects.

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Quote: I would like to know how to display the div in the middle of the screen, whether user has scrolled up/down.

Change

position: absolute;

To

position: fixed;

W3C specifications for position: absolute and for position: fixed.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I don't think that x[[1,3]][:,[1,3]] is hardly readable. If you want to be more clear on your intent, you can do:

a[[1,3],:][:,[1,3]]

I am not an expert in slicing but typically, if you try to slice into an array and the values are continuous, you get back a view where the stride value is changed.

e.g. In your inputs 33 and 34, although you get a 2x2 array, the stride is 4. Thus, when you index the next row, the pointer moves to the correct position in memory.

Clearly, this mechanism doesn't carry well into the case of an array of indices. Hence, numpy will have to make the copy. After all, many other matrix math function relies on size, stride and continuous memory allocation.

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)

Finding Variable Type in JavaScript

Use typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

So you can do:

if(typeof bar === 'number') {
   //whatever
}

Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"

The type of an array is still object. Here you really need the instanceof operator.

Update:

Another interesting way is to examine the output of Object.prototype.toString:

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"

With that you would not have to distinguish between primitive values and objects.

How to have a default option in Angular.js select box

I needed the default “Please Select” to be unselectable. I also needed to be able to conditionally set a default selected option.

I achieved this the following simplistic way: JS code: // Flip these 2 to test selected default or no default with default “Please Select” text //$scope.defaultOption = 0; $scope.defaultOption = { key: '3', value: 'Option 3' };

$scope.options = [
   { key: '1', value: 'Option 1' },
   { key: '2', value: 'Option 2' },
   { key: '3', value: 'Option 3' },
   { key: '4', value: 'Option 4' }
];

getOptions();

function getOptions(){
    if ($scope.defaultOption != 0)
    { $scope.options.selectedOption = $scope.defaultOption; }
}

HTML:

<select name="OptionSelect" id="OptionSelect" ng-model="options.selectedOption" ng-options="item.value for item in options track by item.key">
<option value="" disabled selected style="display: none;"> -- Please Select -- </option>
</select>
<h1>You selected: {{options.selectedOption.key}}</h1>         

I hope this helps someone else that has similar requirements.

The "Please Select" was accomplished through Joffrey Outtier's answer here.

Convert date to YYYYMM format

You can convert your date in many formats, for example :

CONVERT(NVARCHAR(10), DATE_OF_DAY, 103) => 15/09/2016
CONVERT(NVARCHAR(10), DATE_OF_DAY, 3) => 15/09/16

Syntaxe :

CONVERT('TheTypeYouWant', 'TheDateToConvert', 'TheCodeForFormating' * )
  • The code is an integer, here 3 is the third formating without century, if you want the century just change the code to 103.

In your case, i've just converted and restrict size by nvarchar(6) like this :

CONVERT(NVARCHAR(6), DATE_OF_DAY, 112) => 201609

See more at : http://www.w3schools.com/sql/func_convert.asp

How to get previous page url using jquery

simple & sweet

window.location = document.referrer;

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

Simply install Microsot.ReportViewer.2012.Runtime nuget package as shown in this answer https://stackoverflow.com/a/33014040/2198830

Remove substring from the string

If you are using rails or at less activesupport you got String#remove and String#remove! method

def remove!(*patterns)
  patterns.each do |pattern|
    gsub! pattern, ""
  end

  self
end

source: http://api.rubyonrails.org/classes/String.html#method-i-remove

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

How to update primary key

You shouldn't really do this but insert in a new record instead and update it that way.
But, if you really need to, you can do the following:

  • Disable enforcing FK constraints temporarily (e.g. ALTER TABLE foo WITH NOCHECK CONSTRAINT ALL)
  • Then update your PK
  • Then update your FKs to match the PK change
  • Finally enable back enforcing FK constraints

Bootstrap datepicker disabling past dates without current date

To disable past dates & highlight today's date:

$(function () {
    $('.input-daterange').datepicker({
        startDate : new Date(),
        todayHighlight : true
    });
});

To disable future dates & highlight today's date:

$(function () {
    $('.input-daterange').datepicker({
        endDate : new Date(),
        todayHighlight : true
    });
});

For more details check this out https://bootstrap-datepicker.readthedocs.io/en/latest/options.html?highlight=startdate#quick-reference

Command to change the default home directory of a user

From Linux Change Default User Home Directory While Adding A New User:

Simply open this file using a text editor, type:

vi /etc/default/useradd

The default home directory defined by HOME variable, find line that read as follows:

HOME=/home

Replace with:

HOME=/iscsi/user

Save and close the file. Now you can add user using regular useradd command:

# useradd vivek
# passwd vivek

Verify user information:

# finger vivek

Rails has_many with alias name

You could also use alias_attribute if you still want to be able to refer to them as tasks as well:

class User < ActiveRecord::Base
  alias_attribute :jobs, :tasks

  has_many :tasks
end

Share Text on Facebook from Android App via ACTION_SEND

To make the Share work with the facebook app, you only need to have suply at least one link:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Wonderful search engine http://www.google.fr/");
startActivity(Intent.createChooser(intent, "Share with"));

This will show the correct sharing window but when you click on share, nothing happends (I also tried with the official Twitter App, it does not work).

The only way I found to make the Facebook app sharing work is to share only a link with no text:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "http://www.google.fr/");
startActivity(Intent.createChooser(intent, "Share with"));

It will show the following window and the Share button will work:

facebook share

Apparently it automatically takes an image and text from the link to populate the share.

If you want to share only text, you will have to use the facebook api: https://github.com/facebook/facebook-android-sdk

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

Sending arrays with Intent.putExtra

This code sends array of integer values

Initialize array List

List<Integer> test = new ArrayList<Integer>();

Add values to array List

test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);

Send the array list values to target activity

intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);

here you get values on targetActivty

Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");

Getting indices of True values in a boolean list

Use enumerate, list.index returns the index of first match found.

>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> [i for i, x in enumerate(t) if x]
[4, 5, 7]

For huge lists, it'd be better to use itertools.compress:

>>> from itertools import compress
>>> list(compress(xrange(len(t)), t))
[4, 5, 7]
>>> t = t*1000
>>> %timeit [i for i, x in enumerate(t) if x]
100 loops, best of 3: 2.55 ms per loop
>>> %timeit list(compress(xrange(len(t)), t))
1000 loops, best of 3: 696 µs per loop

What is the best way to convert an array to a hash in Ruby

The best way is to use Array#to_h:

[ [:apple,1],[:banana,2] ].to_h  #=> {apple: 1, banana: 2}

Note that to_h also accepts a block:

[:apple, :banana].to_h { |fruit| [fruit, "I like #{fruit}s"] } 
  # => {apple: "I like apples", banana: "I like bananas"}

Note: to_h accepts a block in Ruby 2.6.0+; for early rubies you can use my backports gem and require 'backports/2.6.0/enumerable/to_h'

to_h without a block was introduced in Ruby 2.1.0.

Before Ruby 2.1, one could use the less legible Hash[]:

array = [ [:apple,1],[:banana,2] ]
Hash[ array ]  #= > {:apple => 1, :banana => 2}

Finally, be wary of any solutions using flatten, this could create problems with values that are arrays themselves.

How to get a variable type in Typescript?

Type guards in typescript

To determine the type of a variable after a conditional statement you can use type guards. A type guard in typescript is the following:

An expression which allows you to narrow down the type of something within a conditional block.

In other words it is an expression within a conditional block from where the typescript compiler has enough information to narrow down the type. The type will be more specific within the block of the type guard because the compiler has inferred more information about the type.

Example

declare let abc: number | string;

// typeof abc === 'string' is a type guard
if (typeof abc === 'string') {
    // abc: string
    console.log('abc is a string here')
} else {
    // abc: number, only option because the previous type guard removed the option of string
    console.log('abc is a number here')
}

Besides the typeof operator there are built in type guards like instanceof, in and even your own type guards.

Using the RUN instruction in a Dockerfile with 'source' does not work

I ended up putting my env stuff in .profile and mutated SHELL something like

SHELL ["/bin/bash", "-c", "-l"]

# Install ruby version specified in .ruby-version
RUN rvm install $(<.ruby-version)

# Install deps
RUN rvm use $(<.ruby-version) && gem install bundler && bundle install

CMD rvm use $(<.ruby-version) && ./myscript.rb

SQL ORDER BY multiple columns

The results are ordered by the first column, then the second, and so on for as many columns as the ORDER BY clause includes. If you want any results sorted in descending order, your ORDER BY clause must use the DESC keyword directly after the name or the number of the relevant column.

Check out this Example

SELECT first_name, last_name, hire_date, salary 
FROM employee 
ORDER BY hire_date DESC,last_name ASC;

It will order in succession. Order the Hire_Date first, then LAST_NAME it by Hire_Date .

How to stop process from .BAT file?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate

wmic offer even more flexibility than taskkill .With wmic Path win32_process get you can see the available fileds you can filter.

How do I analyze a .hprof file?

Just get the Eclipse Memory Analyzer. There's nothing better out there and it's free.

JHAT is only usable for "toy applications"

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

How to calculate age in T-SQL with years, months, and days

Simple way to get age as text is as below:

Select cast((DATEDIFF(m, date_of_birth, GETDATE())/12) as varchar) + ' Y & ' + 
       cast((DATEDIFF(m, date_of_birth, GETDATE())%12) as varchar) + ' M' as Age

Results Format will be:

**63 Y & 2 M**

HTTP GET in VBS

You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP (I recommend the more explicit MSXML2.XMLHTTP.3.0 progID) however you may need to do different things with the response, it may not be text.

The XMLHTTP also has a responseBody property which is a byte array version of the reponse and there is a responseStream which is an IStream wrapper for the response.

Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0 or WinHttp.WinHttpRequest.5.1 (which has a near identical interface).

Here is an example of using XmlHttp to fetch a PDF file and store it:-

Dim oXMLHTTP
Dim oStream

Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")

oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send

If oXMLHTTP.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write oXMLHTTP.responseBody
    oStream.SaveToFile "c:\somefolder\file.pdf"
    oStream.Close
End If