Programs & Examples On #Uisplitviewcontroller

The UISplitViewController class is a container view controller that presents a master-detail interface. In a master-detail interface, changes in the primary view controller (the master) drive changes in a secondary view controller (the detail). The two view controllers can be arranged so that they are side-by-side, so that only one at a time is visible, or so that one only partially hides the other.

ApiNotActivatedMapError for simple html page using google-places-api

as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)

you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key

also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.

What is phtml, and when should I use a .phtml extension rather than .php?

You can choose any extension in the world if you setup Apache correctly. You could use .html to do PHP if you set up in your Apache config.

In conclusion, extension has nothing to do with the app or website itself. You can use the one you want, but normaly, use .php (to not reinvent the wheel)

But in 2019, you should use routing and forgot about extension at the end.

I recommend you using Laravel.

In answer to @KingCrunch: True, Apache not use it by default but you can easily use it if you change config. But this it not recommended since everybody know that it not really an option.

I already saw .html files that executed PHP using the html extension.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

In Android O and later this error happens when you set

 android:screenOrientation="portrait"

in Manifest.

Remove that line and use

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

in your activity.

This will fix your issue.

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

This should help : http://www.w3.org/International/articles/language-tags/

The golden rule when creating language tags is to keep the tag as short as possible. Avoid region, script or other subtags except where they add useful distinguishing information. For instance, use ja for Japanese and not ja-JP, unless there is a particular reason that you need to say that this is Japanese as spoken in Japan, rather than elsewhere.

The list below shows the various types of subtag that are available. We will work our way through these and how they are used in the sections that follow.

language-extlang-script-region-variant-extension-privateuse

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

Example to get the last input element:

document.querySelector(".groups-container >div:last-child input")

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

JavaScript - Get minutes between two dates

You can do as follows:

  1. Get difference of dates(Difference will be in milliseconds)
  2. Convert milliseconds into minutes i-e ms/1000/60

The Code:

let dateOne = new Date("2020-07-10");
let dateTwo = new Date("2020-07-11");

let msDifference =  dateTwo - dateOne;
let minutes = Math.floor(msDifference/1000/60);
console.log("Minutes between two dates =",minutes);

apache redirect from non www to www

This is similar to many of the other suggestions with a couple enhancements:

  • No need to hardcode the domain (works with vhosts that accept multiple domains or between environments)
  • Preserves the scheme (http/https) and ignores the effects of previous %{REQUEST_URI} rules.
  • The path portion not affected by previous RewriteRules like %{REQUEST_URI} is.

    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ %{REQUEST_SCHEME}://www.%{HTTP_HOST}/$1 [R=301,L]
    

How to ignore SSL certificate errors in Apache HttpClient 4.0

Just had to do this with the newer HttpClient 4.5 and it seems like they've deprecated a few things since 4.4 so here's the snippet that works for me and uses the most recent API:

final SSLContext sslContext = new SSLContextBuilder()
        .loadTrustMaterial(null, (x509CertChain, authType) -> true)
        .build();

return HttpClientBuilder.create()
        .setSSLContext(sslContext)
        .setConnectionManager(
                new PoolingHttpClientConnectionManager(
                        RegistryBuilder.<ConnectionSocketFactory>create()
                                .register("http", PlainConnectionSocketFactory.INSTANCE)
                                .register("https", new SSLConnectionSocketFactory(sslContext,
                                        NoopHostnameVerifier.INSTANCE))
                                .build()
                ))
        .build();

Get selected element's outer HTML

node.cloneNode() hardly seems like a hack. You can clone the node and append it to any desired parent element, and also manipulate it by manipulating individual properties, rather than having to e.g. run regular expressions on it, or add it in to the DOM, then manipulate it afterwords.

That said, you could also iterate over the attributes of the element to construct an HTML string representation of it. It seems likely this is how any outerHTML function would be implemented were jQuery to add one.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I had the same problem with Celery. My setting.py before:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

after:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', <YOUR developing key>)

If the environment variables are not defined then: SECRET_KEY = YOUR developing key

Mocking methods of local scope objects with Mockito

You can do this by creating a factory method in MyObject:

class MyObject {
    public static MyObject create() {
      return new MyObject();
    }
}

then mock that with PowerMock.

However, by mocking the methods of a local scope object, you are depending on that part of the implementation of the method staying the same. So you lose the ability to refactor that part of the method without breaking the test. In addition, if you are stubbing return values in the mock, then your unit test may pass, but the method may behave unexpectedly when using the real object.

In sum, you should probably not try to do this. Rather, letting the test drive your code (aka TDD), you would arrive at a solution like:

void method1(MyObject obj1) {
   obj1.method1();
}

passing in the dependency, which you can easily mock for the unit test.

How do I convert a decimal to an int in C#?

A neat trick for fast rounding is to add .5 before you cast your decimal to an int.

decimal d = 10.1m;
d += .5m;
int i = (int)d;

Still leaves i=10, but

decimal d = 10.5m;
d += .5m;
int i = (int)d;

Would round up so that i=11.

filename.whl is not supported wheel on this platform

First of all, cp33 means that it is to be used when you have Python 3.3 running on your system. So if you have Python 2.7 on your system, try installing the cp27 version.

Installing scipy-0.18.1-cp27-cp27m-win_amd64.whl, needs a Python 2.7 running and a 64-bit system.

If you are still getting an error saying "scipy-0.18.1-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform", then go for the win32 version. By this I mean install scipy-0.18.1-cp27-cp27m-win32.whl instead of the first one. This is because you might be running a 32-bit python on a 64-bit system. The last step successfully installed scipy for me.

Gunicorn worker timeout error

We had the same problem using Django+nginx+gunicorn. From Gunicorn documentation we have configured the graceful-timeout that made almost no difference.

After some testings, we found the solution, the parameter to configure is: timeout (And not graceful timeout). It works like a clock..

So, Do:

1) open the gunicorn configuration file

2) set the TIMEOUT to what ever you need - the value is in seconds

NUM_WORKERS=3
TIMEOUT=120

exec gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--timeout $TIMEOUT \
--log-level=debug \
--bind=127.0.0.1:9000 \
--pid=$PIDFILE

Text in HTML Field to disappear when clicked?

Use the placeholder attribute. The text disappears when the user starts typing. This is an example of a project I am working on:

<div class="" id="search-form">
    <input type="text" name="" value="" class="form-control" placeholder="Search..." >
</div>

What is the difference between mocking and spying when using Mockito?

The answer is in the documentation:

Real partial mocks (Since 1.8.0)

Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.

Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.

callRealMethod() was introduced after spy(), but spy() was left there of course, to ensure backward compatibility.

Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod() is called. In general, I would prefer using callRealMethod(), because it doesn't force me to use the doXxx().when() idiom instead of the traditional when().thenXxx()

Differences between hard real-time, soft real-time, and firm real-time?

The definition has expanded over the years to the detriment of the term. What is now called "Hard" real-time is what used to be simply called real-time. So systems in which missing timing windows (rather than single-sided time deadlines) would result incorrect data or incorrect behavior should be consider real-time. Systems without that characteristic would be considered non-real-time.

That's not to say that time isn't of interest in non-real-time systems, it just means that timing requirements in such systems don't result in fundamentally incorrect results.

Java parsing XML document gives "Content not allowed in prolog." error

I assume you have proper xml encoding and matching with Schema.

If you still get this error, check code that unmarshalls the xml and input type you have used. Because XML documents declare their own encoding, it is preferable to create a StreamSource object from an InputStream instead of from a Reader, so that XML processor can correctly handle the declared encoding [Ref Book: Java in A Nutshell ]

Hope this helps!

How to convert timestamps to dates in Bash?

In this answer I copy Dennis Williamson's answer and modify it slightly to allow a vast speed increase when piping a column of many timestamps to the script. For example, piping 1000 timestamps to the original script with xargs -n1 on my machine took 6.929s as opposed to 0.027s with this modified version:

#!/bin/bash
LANG=C
if [[ -z "$1" ]]
then
    if [[ -p /dev/stdin ]]    # input from a pipe
    then
        cat - | gawk '{ print strftime("%c", $1); }'
    else
        echo "No timestamp given." >&2
        exit
    fi
else
    date -d @$1 +%c
fi

Calling a function on bootstrap modal open

You can use belw code for show and hide bootstrap model.

$('#my-model').on('shown.bs.modal', function (e) {
  // do something here...
})

and if you want to hide model then you can use below code.

$('#my-model').on('hidden.bs.modal', function() {
    // do something here...
});

I hope this answer is useful for your project.

How do I determine if a port is open on a Windows server?

On a Windows machine you can use PortQry from Microsoft to check whether an application is already listening on a specific port using the following command:

portqry -n 11.22.33.44 -p tcp -e 80

Java: Calling a super method which calls an overridden method

The keyword super doesn't "stick". Every method call is handled individually, so even if you got to SuperClass.method1() by calling super, that doesn't influence any other method call that you might make in the future.

That means there is no direct way to call SuperClass.method2() from SuperClass.method1() without going though SubClass.method2() unless you're working with an actual instance of SuperClass.

You can't even achieve the desired effect using Reflection (see the documentation of java.lang.reflect.Method.invoke(Object, Object...)).

[EDIT] There still seems to be some confusion. Let me try a different explanation.

When you invoke foo(), you actually invoke this.foo(). Java simply lets you omit the this. In the example in the question, the type of this is SubClass.

So when Java executes the code in SuperClass.method1(), it eventually arrives at this.method2();

Using super doesn't change the instance pointed to by this. So the call goes to SubClass.method2() since this is of type SubClass.

Maybe it's easier to understand when you imagine that Java passes this as a hidden first parameter:

public class SuperClass
{
    public void method1(SuperClass this)
    {
        System.out.println("superclass method1");
        this.method2(this); // <--- this == mSubClass
    }

    public void method2(SuperClass this)
    {
        System.out.println("superclass method2");
    }

}

public class SubClass extends SuperClass
{
    @Override
    public void method1(SubClass this)
    {
        System.out.println("subclass method1");
        super.method1(this);
    }

    @Override
    public void method2(SubClass this)
    {
        System.out.println("subclass method2");
    }
}



public class Demo 
{
    public static void main(String[] args) 
    {
        SubClass mSubClass = new SubClass();
        mSubClass.method1(mSubClass);
    }
}

If you follow the call stack, you can see that this never changes, it's always the instance created in main().

How do I test a private function or a class that has private methods, fields or inner classes?

Today, I pushed a Java library to help testing private methods and fields. It has been designed with Android in mind, but it can really be used for any Java project.

If you got some code with private methods or fields or constructors, you can use BoundBox. It does exactly what you are looking for. Here below is an example of a test that accesses two private fields of an Android activity to test it:

@UiThreadTest
public void testCompute() {

    // Given
    boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());

    // When
    boundBoxOfMainActivity.boundBox_getButtonMain().performClick();

    // Then
    assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());
}

BoundBox makes it easy to test private/protected fields, methods and constructors. You can even access stuff that is hidden by inheritance. Indeed, BoundBox breaks encapsulation. It will give you access to all that through reflection, BUT everything is checked at compile time.

It is ideal for testing some legacy code. Use it carefully. ;)

https://github.com/stephanenicolas/boundbox

latex large division sign in a math formula

Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.

And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.

In Go's http package, how do I get the query string on a POST request?

Below is an example:

value := r.FormValue("field")

for more info. about http package, you could visit its documentation here. FormValue basically returns POST or PUT values, or GET values, in that order, the first one that it finds.

Group by multiple field names in java 8

You have a few options here. The simplest is to chain your collectors:

Map<String, Map<Integer, List<Person>>> map = people
    .collect(Collectors.groupingBy(Person::getName,
        Collectors.groupingBy(Person::getAge));

Then to get a list of 18 year old people called Fred you would use:

map.get("Fred").get(18);

A second option is to define a class that represents the grouping. This can be inside Person. This code uses a record but it could just as easily be a class (with equals and hashCode defined) in versions of Java before JEP 359 was added:

class Person {
    record NameAge(String name, int age) { }

    public NameAge getNameAge() {
        return new NameAge(name, age);
    }
}

Then you can use:

Map<NameAge, List<Person>> map = people.collect(Collectors.groupingBy(Person::getNameAge));

and search with

map.get(new NameAge("Fred", 18));

Finally if you don't want to implement your own group record then many of the Java frameworks around have a pair class designed for this type of thing. For example: apache commons pair If you use one of these libraries then you can make the key to the map a pair of the name and age:

Map<Pair<String, Integer>, List<Person>> map =
    people.collect(Collectors.groupingBy(p -> Pair.of(p.getName(), p.getAge())));

and retrieve with:

map.get(Pair.of("Fred", 18));

Personally I don't really see much value in generic tuples now that records are available in the language as records display intent better and require very little code.

symfony 2 twig limit the length of the text and put three dots

why not use twig's truncate or wordwrap filter? It belongs to twig extensions and lib is part of Symfony2.0 as i see.

{{ text|truncate(50) }}

How to create a self-signed certificate for a domain name for development?

With IIS's self-signed certificate feature, you cannot set the common name (CN) for the certificate, and therefore cannot create a certificate bound to your choice of subdomain.

One way around the problem is to use makecert.exe, which is bundled with the .Net 2.0 SDK. On my server it's at:

C:\Program Files\Microsoft.Net\SDK\v2.0 64bit\Bin\makecert.exe

You can create a signing authority and store it in the LocalMachine certificates repository as follows (these commands must be run from an Administrator account or within an elevated command prompt):

makecert.exe -n "CN=My Company Development Root CA,O=My Company,
 OU=Development,L=Wallkill,S=NY,C=US" -pe -ss Root -sr LocalMachine
 -sky exchange -m 120 -a sha1 -len 2048 -r

You can then create a certificate bound to your subdomain and signed by your new authority:

(Note that the the value of the -in parameter must be the same as the CN value used to generate your authority above.)

makecert.exe -n "CN=subdomain.example.com" -pe -ss My -sr LocalMachine
 -sky exchange -m 120 -in "My Company Development Root CA" -is Root
 -ir LocalMachine -a sha1 -eku 1.3.6.1.5.5.7.3.1

Your certificate should then appear in IIS Manager to be bound to your site as explained in Tom Hall's post.

All kudos for this solution to Mike O'Brien for his excellent blog post at http://www.mikeobrien.net/blog/creating-self-signed-wildcard

How large should my recv buffer be when calling recv in the socket library

The answers to these questions vary depending on whether you are using a stream socket (SOCK_STREAM) or a datagram socket (SOCK_DGRAM) - within TCP/IP, the former corresponds to TCP and the latter to UDP.

How do you know how big to make the buffer passed to recv()?

  • SOCK_STREAM: It doesn't really matter too much. If your protocol is a transactional / interactive one just pick a size that can hold the largest individual message / command you would reasonably expect (3000 is likely fine). If your protocol is transferring bulk data, then larger buffers can be more efficient - a good rule of thumb is around the same as the kernel receive buffer size of the socket (often something around 256kB).

  • SOCK_DGRAM: Use a buffer large enough to hold the biggest packet that your application-level protocol ever sends. If you're using UDP, then in general your application-level protocol shouldn't be sending packets larger than about 1400 bytes, because they'll certainly need to be fragmented and reassembled.

What happens if recv gets a packet larger than the buffer?

  • SOCK_STREAM: The question doesn't really make sense as put, because stream sockets don't have a concept of packets - they're just a continuous stream of bytes. If there's more bytes available to read than your buffer has room for, then they'll be queued by the OS and available for your next call to recv.

  • SOCK_DGRAM: The excess bytes are discarded.

How can I know if I have received the entire message?

  • SOCK_STREAM: You need to build some way of determining the end-of-message into your application-level protocol. Commonly this is either a length prefix (starting each message with the length of the message) or an end-of-message delimiter (which might just be a newline in a text-based protocol, for example). A third, lesser-used, option is to mandate a fixed size for each message. Combinations of these options are also possible - for example, a fixed-size header that includes a length value.

  • SOCK_DGRAM: An single recv call always returns a single datagram.

Is there a way I can make a buffer not have a fixed amount of space, so that I can keep adding to it without fear of running out of space?

No. However, you can try to resize the buffer using realloc() (if it was originally allocated with malloc() or calloc(), that is).

ajax jquery simple get request

i think the problem is that there is no data in the success-function because the request breaks up with an 401 error in your case and thus has no success.

if you use

$.ajax({
        url: "https://app.asana.com/-/api/0.1/workspaces/",
        type: 'GET',
         error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(thrownError);
  }
    });

there will be your 401 code i think (this link says so)

Update Top 1 record in table sql server

When TOP is used with INSERT, UPDATE, MERGE, or DELETE, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in these statements. If you need to use TOP to insert, delete, or modify rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause that is specified in a subselect statement.

TOP cannot be used in an UPDATE and DELETE statements on partitioned views.

TOP cannot be combined with OFFSET and FETCH in the same query expression (in the same query scope). For more information, see http://technet.microsoft.com/en-us/library/ms189463.aspx

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Should use Entity class name for em.createQuery method or Should use em.createNativeQuery method for native query without entity class

With Entity class:

em.createQuery("select first_name from CUSTOMERV")

Without Entity class or Native query:

em.createNativeQuery("select c.first_name from CUSTOMERV c")

How to generate random float number in C

while it might not matter now here is a function which generate a float between 2 values.

#include <math.h>

float func_Uniform(float left, float right) {
    float randomNumber = sin(rand() * rand());
    return left + (right - left) * fabs(randomNumber);
}

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

Eclipse IDE for Java - Full Dark Theme

  • Help ? Install New Software.
  • Enter Eclipse Color Theme Plugin URL: http://eclipse-color-theme.github.com/update
  • Install Eclipse Color Theme Plugin.
  • Restart Eclipse.
  • Goto Window ? Preferences ? General ? Appearance ? Color Theme
  • I like the Havenjark default Color Theme. Eclipse Color Theme Plugin comes loaded with 24 default Color Themes and option to Import a theme. enter image description here

Toggle Checkboxes on/off

The most basic example would be:

_x000D_
_x000D_
// get DOM elements_x000D_
var checkbox = document.querySelector('input'),_x000D_
    button = document.querySelector('button');_x000D_
_x000D_
// bind "cilck" event on the button_x000D_
button.addEventListener('click', toggleCheckbox);_x000D_
_x000D_
// when clicking the button, toggle the checkbox_x000D_
function toggleCheckbox(){_x000D_
  checkbox.checked = !checkbox.checked;_x000D_
};
_x000D_
<input type="checkbox">_x000D_
<button>Toggle checkbox</button>
_x000D_
_x000D_
_x000D_

Send Email Intent

This code is working in my device

Intent mIntent = new Intent(Intent.ACTION_SENDTO);
mIntent.setData(Uri.parse("mailto:"));
mIntent.putExtra(Intent.EXTRA_EMAIL  , new String[] {"[email protected]"});
mIntent.putExtra(Intent.EXTRA_SUBJECT, "");
startActivity(Intent.createChooser(mIntent, "Send Email Using..."));

How can I get the count of milliseconds since midnight for the current?

You can use java.util.Calendar class to get time in milliseconds. Example:

Calendar cal = Calendar.getInstance();
int milliSec = cal.get(Calendar.MILLISECOND);
// print milliSec

java.util.Date date = cal.getTime();
System.out.println("Output: " +  new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(date));

What is a tracking branch?

Below are my personal learning notes on GIT tracking branches, hopefully it will be helpful for future visitors:

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here


Tracking branches and "git fetch":

enter image description here enter image description here enter image description here

How can I get the iOS 7 default blue color programmatically?

swift 4 way:

extension UIColor {
  static let system = UIView().tintColor!
}

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

Cross compile Go on OSX?

for people who need CGO enabled and cross compile from OSX targeting windows

I needed CGO enabled while compiling for windows from my mac since I had imported the https://github.com/mattn/go-sqlite3 and it needed it. Compiling according to other answers gave me and error:

/usr/local/go/src/runtime/cgo/gcc_windows_amd64.c:8:10: fatal error: 'windows.h' file not found

If you're like me and you have to compile with CGO. This is what I did:

1.We're going to cross compile for windows with a CGO dependent library. First we need a cross compiler installed like mingw-w64

brew install mingw-w64

This will probably install it here /usr/local/opt/mingw-w64/bin/.

2.Just like other answers we first need to add our windows arch to our go compiler toolchain now. Compiling a compiler needs a compiler (weird sentence) compiling go compiler needs a separate pre-built compiler. We can download a prebuilt binary or build from source in a folder eg: ~/Documents/go now we can improve our Go compiler, according to top answer but this time with CGO_ENABLED=1 and our separate prebuilt compiler GOROOT_BOOTSTRAP(Pooya is my username):

cd /usr/local/go/src
sudo GOOS=windows GOARCH=amd64 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean
sudo GOOS=windows GOARCH=386 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean

3.Now while compiling our Go code use mingw to compile our go file targeting windows with CGO enabled:

GOOS="windows" GOARCH="386" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/i686-w64-mingw32-gcc" go build hello.go
GOOS="windows" GOARCH="amd64" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/x86_64-w64-mingw32-gcc" go build hello.go

Controlling a USB power supply (on/off) with Linux

I have found these solutions that at least work for properly configured Terminus FE 1.1 USB hub chip:

1.To turn off power on all USB ports of a hub, you may unbind the hub from kernel using:

echo "1-4.4.4" > /sys/bus/usb/drivers/usb/unbind

to turn power back on - you may bind it back using

echo "1-4.4.4" > /sys/bus/usb/drivers/usb/bind

2.Switching power at each port individually is trickier: I was able to use hubpower to control each port - but it comes with a downside: hubpower first disconnects the usbdevfs wich causes all of the USB devices to disconect from system, at least on ubuntu:

usb_ioctl.ioctl_code = USBDEVFS_DISCONNECT;
rc = ioctl(fd, USBDEVFS_IOCTL, &usb_ioctl);

With this ioctl disabled I was able to switch off individual port power without detaching all devices - but the power goes back on immediately (probably due to kernel seeing an uninitialized device) which causes USB device just to do a "cold restart" which is what I generally wanted to do. My patched hubpower is here

Using global variables in a function

If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global. You don't have to use it in all cases (as someone here incorrectly claims) - if the name referenced in an expression cannot be found in local scope or scopes in the functions in which this function is defined, it is looked up among global variables.

However, if you assign to a new variable not declared as global in the function, it is implicitly declared as local, and it can overshadow any existing global variable with the same name.

Also, global variables are useful, contrary to some OOP zealots who claim otherwise - especially for smaller scripts, where OOP is overkill.

jQuery Call to WebService returns "No Transport" error

For me it is an entirely different story.
Since this page has a good search engine ranking, I should add my case and the solution here too.

I built jquery myself with webpack picking only the modules I use. The ajax is always failed with "No Transport" message as the only clue.

After a long debugging, the problem turns out to be XMLHttpRequest is pluggable in jquery and it not include by default.

You have to explicitly include jquery/src/ajax/xhr file in order to make the ajax working in browsers.

How to get folder path from file path with CMD

In order to assign these to variables, be sure not to add spaces in front or after the equals sign:

set filepath=%~dp1
set filename=%~nx1

Then you should have no issues.

Getting the ID of the element that fired an event

In case of Angular 7.x you can get the native element and its id or properties.

myClickHandler($event) {
    this.selectedElement = <Element>$event.target;
    console.log(this.selectedElement.id)
    this.selectedElement.classList.remove('some-class');
}

html:

<div class="list-item" (click)="myClickHandler($event)">...</div>

Changing button text onclick

i know this is an old post but there is an option to sent the elemd id with the function call:

<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>


function f1(objButton)
    {
        if (objButton.innerHTML=="EXPAND") objButton.innerHTML = "MINIMIZE";
        else objButton.innerHTML = "EXPAND";
    }

jQuery - Getting the text value of a table cell in the same row as a clicked element

it should work fine:

var Something = $(this).children("td:nth-child(n)").text();

jQuery Keypress Arrow Keys

You can check wether an arrow key is pressed by:

$(document).keydown(function(e){
    if (e.keyCode > 36 && e.keyCode < 41) 
      alert( "arrowkey pressed" );          
});

jsfiddle demo

When to use std::size_t?

When using size_t be careful with the following expression

size_t i = containner.find("mytoken");
size_t x = 99;
if (i-x>-1 && i+x < containner.size()) {
    cout << containner[i-x] << " " << containner[i+x] << endl;
}

You will get false in the if expression regardless of what value you have for x. It took me several days to realize this (the code is so simple that I did not do unit test), although it only take a few minutes to figure the source of the problem. Not sure it is better to do a cast or use zero.

if ((int)(i-x) > -1 or (i-x) >= 0)

Both ways should work. Here is my test run

size_t i = 5;
cerr << "i-7=" << i-7 << " (int)(i-7)=" << (int)(i-7) << endl;

The output: i-7=18446744073709551614 (int)(i-7)=-2

I would like other's comments.

Xcode 5 and iOS 7: Architecture and Valid architectures

You do not need to limit your compiler to only armv7 and armv7s by removing arm64 setting from supported architectures. You just need to set Deployment target setting to 5.1.1

Important note: you cannot set Deployment target to 5.1.1 in Build Settings section because it is drop-down only with fixed values. But you can easily set it to 5.1.1 in General section of application settings by just typing the value in text field.

Tuples( or arrays ) as Dictionary keys in C#

If you're on C# 7, you should consider using value tuples as your composite key. Value tuples typically offer better performance than the traditional reference tuples (Tuple<T1, …>) since value tuples are value types (structs), not reference types, so they avoid the memory allocation and garbage collection costs. Also, they offer conciser and more intuitive syntax, allowing for their fields to be named if you so wish. They also implement the IEquatable<T> interface needed for the dictionary.

var dict = new Dictionary<(int PersonId, int LocationId, int SubjectId), string>();
dict.Add((3, 6, 9), "ABC");
dict.Add((PersonId: 4, LocationId: 9, SubjectId: 10), "XYZ");
var personIds = dict.Keys.Select(k => k.PersonId).Distinct().ToList();

How to make <div> fill <td> height

This questions is already answered here. Just put height: 100% in both the div and the container td.

How can I check if a value is a json object?

I know this thread has been answered already, but coming here didn't really solve my problems, I found this function somewhere else. maybe someone coming here will find it to be of some use to them;

function getClass(obj) {
  if (typeof obj === "undefined")
    return "undefined";
  if (obj === null)
    return "null";
  return Object.prototype.toString.call(obj)
    .match(/^\[object\s(.*)\]$/)[1];
}

Argument of type 'X' is not assignable to parameter of type 'X'

In my case, it was that I had a custom interface called Item, but I imported accidentally because of the auto-completion, the angular Item class. Be sure that you're importing from the right package.

how to convert string into time format and add two hours

You can use SimpleDateFormat to convert the String to Date. And after that you have two options,

  • Make a Calendar object and and then use that to add two hours, or
  • get the time in millisecond from that date object, and add two hours like, (2 * 60 * 60 * 1000)

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // replace with your start date string
    Date d = df.parse("2008-04-16 00:05:05"); 
    Calendar gc = new GregorianCalendar();
    gc.setTime(d);
    gc.add(Calendar.HOUR, 2);
    Date d2 = gc.getTime();
    

    Or,

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // replace with your start date string
    Date d = df.parse("2008-04-16 00:05:05");
    Long time = d.getTime();
    time +=(2*60*60*1000);
    Date d2 = new Date(time);
    

Have a look to these tutorials.

Why am I seeing "TypeError: string indices must be integers"?

I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows

data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
    print('{} {}'.format(item["gravatar_id"], item["position"]))

note that you need to handle the index in the dataset that is also returned by the function.

Change the jquery show()/hide() animation?

Use slidedown():

$("test").slideDown("slow");

Possible reason for NGINX 499 error codes

This doesn't answer the OPs question, but since I ended up here after searching furiously for an answer, I wanted to share what we discovered.

In our case, it turns out these 499s are expected. When users use the type-ahead feature in some search boxes, for example, we see something like this in the logs.

GET /api/search?q=h [Status 499] 
GET /api/search?q=he [Status 499]
GET /api/search?q=hel [Status 499]
GET /api/search?q=hell [Status 499]
GET /api/search?q=hello [Status 200]

So in our case I think its safe to use proxy_ignore_client_abort on which was suggested in a previous answer. Thanks for that!

How to make a div with no content have a width?

I had the same issue. I wanted icons to appear by pressing the button but without any movement and sliding the enviroment, just like bulb: on and off, appeared and dissapeared, so I needed to make an empty div with fixed sizes.

width: 13px;
min-width: 13px;

did the trick for me

HttpClient won't import in Android Studio

Which API target do you have within your project?AndroidHttpClientis only for API Level 8 <. and please have a look on here

enjoy your code:)

Convert datetime to valid JavaScript date

Just use Date.parse() which returns a Number, then use new Date() to parse it:

var thedate = new Date(Date.parse("2011-07-14 11:23:00"));

How can I pad a String in Java?

Use this function.

private String leftPadding(String word, int length, char ch) {
   return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}

how to use?

leftPadding(month, 2, '0');

output: 01 02 03 04 .. 11 12

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I fully agree with Mikko, but if you still want to do it, here is the way:

  • Restart in recovery mode (Hold cmd + R)
  • Open terminal from utilities
  • Use the command csrutil disable

Gradle error: could not execute build using gradle distribution

      1- delete .gradle folder in the root directory of the app
      2- invalidate cache and restart 

How do you get the file size in C#?

If you have already a file path as input, this is the code you need:

long length = new System.IO.FileInfo(path).Length;

Selecting non-blank cells in Excel with VBA

I know I'm am very late on this, but here some usefull samples:

'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select

or

'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
    .value = .value
end with

To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data). Instead, I use someting like

 lngLast = cells(rows.count,3).end(xlUp).row

ShowAllData method of Worksheet class failed

Add this code below. Once turns it off, releases the filter. Second time turns it back on without filters.

Not very elegant, but served my purpose.

ActiveSheet.ListObjects("MyTable").Range.AutoFilter

'then call it again?
ActiveSheet.ListObjects("MyTable").Range.AutoFilter

UIScrollView Scrollable Content Size Ambiguity

@Matteo Gobbi's answer is perfect, but in my case, the scrollview can't scroll, i remove "align center Y" and add "height >=1", the scrollview will became scrollable

Pandas DataFrame to List of Dictionaries

As an extension to John Galt's answer -

For the following DataFrame,

   customer  item1   item2   item3
0         1  apple    milk  tomato
1         2  water  orange  potato
2         3  juice   mango   chips

If you want to get a list of dictionaries including the index values, you can do something like,

df.to_dict('index')

Which outputs a dictionary of dictionaries where keys of the parent dictionary are index values. In this particular case,

{0: {'customer': 1, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 1: {'customer': 2, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 2: {'customer': 3, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}}

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

I ran into this issue when I changed the name of the variable which connected to one of my buttons. So keep that in mind!

Iterate a certain number of times without storing the iteration number anywhere

for word in ['hello'] * 2:
    print word

It's not idiomatic Python, but neither is what you're trying to do.

What is a clearfix?

Simply put, clearfix is a hack.

It is one of those ugly things that we all just have to live with as it is really the only reasonable way of ensuring floated child elements don't overflow their parents. There are other layout schemes out there but floating is too commonplace in web design/development today to ignore the value of the clearfix hack.

I personally lean towards the Micro Clearfix solution (Nicolas Gallagher)

.container:before,
.container:after {
  content:"";
  display:table;
}
.container:after {
  clear:both;
}
.container {
  zoom:1; /* For IE 6/7 (trigger hasLayout) */
}

reference

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

This was my problem and how I fixed it...

I had done everything everyone had mentioned above etc. but was still getting this error. Turns out I was using the uri's of http://java.sun.com/jsp/jstl/fmt and http://java.sun.com/jsp/jstl/core which were incorrect.

Try switching the uris from above to:

http://java.sun.com/jstl/fmt
http://java.sun.com/jstl/core

Also, make sure you have the correct jars referenced in your class path.

How to compare two dates?

Use time

Let's say you have the initial dates as strings like these:
date1 = "31/12/2015"
date2 = "01/01/2016"

You can do the following:
newdate1 = time.strptime(date1, "%d/%m/%Y") and newdate2 = time.strptime(date2, "%d/%m/%Y") to convert them to python's date format. Then, the comparison is obvious:

newdate1 > newdate2 will return False
newdate1 < newdate2 will return True

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

CodeIgniter Active Record not equal

According to the manual this should work:

Custom key/value method:

You can include an operator in the first parameter in order to control the comparison:

$this->db->where('name !=', $name);
$this->db->where('id <', $id);
Produces: WHERE name != 'Joe' AND id < 45

Search for $this->db->where(); and look at item #2.

Get all mysql selected rows into an array

$name=array(); 
while($result=mysql_fetch_array($res)) {
    $name[]=array('Id'=>$result['id']); 
    // here you want to fetch all 
    // records from table like this. 
    // then you should get the array 
    // from all rows into one array 
}

Move the most recent commit(s) to a new branch with Git

Most previous answers are dangerously wrong!

Do NOT do this:

git branch -t newbranch
git reset --hard HEAD~3
git checkout newbranch

As the next time you run git rebase (or git pull --rebase) those 3 commits would be silently discarded from newbranch! (see explanation below)

Instead do this:

git reset --keep HEAD~3
git checkout -t -b newbranch
git cherry-pick ..HEAD@{2}
  • First it discards the 3 most recent commits (--keep is like --hard, but safer, as fails rather than throw away uncommitted changes).
  • Then it forks off newbranch.
  • Then it cherry-picks those 3 commits back onto newbranch. Since they're no longer referenced by a branch, it does that by using git's reflog: HEAD@{2} is the commit that HEAD used to refer to 2 operations ago, i.e. before we 1. checked out newbranch and 2. used git reset to discard the 3 commits.

Warning: the reflog is enabled by default, but if you've manually disabled it (e.g. by using a "bare" git repository), you won't be able to get the 3 commits back after running git reset --keep HEAD~3.

An alternative that doesn't rely on the reflog is:

# newbranch will omit the 3 most recent commits.
git checkout -b newbranch HEAD~3
git branch --set-upstream-to=oldbranch
# Cherry-picks the extra commits from oldbranch.
git cherry-pick ..oldbranch
# Discards the 3 most recent commits from oldbranch.
git branch --force oldbranch oldbranch~3

(if you prefer you can write @{-1} - the previously checked out branch - instead of oldbranch).


Technical explanation

Why would git rebase discard the 3 commits after the first example? It's because git rebase with no arguments enables the --fork-point option by default, which uses the local reflog to try to be robust against the upstream branch being force-pushed.

Suppose you branched off origin/master when it contained commits M1, M2, M3, then made three commits yourself:

M1--M2--M3  <-- origin/master
         \
          T1--T2--T3  <-- topic

but then someone rewrites history by force-pushing origin/master to remove M2:

M1--M3'  <-- origin/master
 \
  M2--M3--T1--T2--T3  <-- topic

Using your local reflog, git rebase can see that you forked from an earlier incarnation of the origin/master branch, and hence that the M2 and M3 commits are not really part of your topic branch. Hence it reasonably assumes that since M2 was removed from the upstream branch, you no longer want it in your topic branch either once the topic branch is rebased:

M1--M3'  <-- origin/master
     \
      T1'--T2'--T3'  <-- topic (rebased)

This behavior makes sense, and is generally the right thing to do when rebasing.

So the reason that the following commands fail:

git branch -t newbranch
git reset --hard HEAD~3
git checkout newbranch

is because they leave the reflog in the wrong state. Git sees newbranch as having forked off the upstream branch at a revision that includes the 3 commits, then the reset --hard rewrites the upstream's history to remove the commits, and so next time you run git rebase it discards them like any other commit that has been removed from the upstream.

But in this particular case we want those 3 commits to be considered as part of the topic branch. To achieve that, we need to fork off the upstream at the earlier revision that doesn't include the 3 commits. That's what my suggested solutions do, hence they both leave the reflog in the correct state.

For more details, see the definition of --fork-point in the git rebase and git merge-base docs.

How to percent-encode URL parameters in Python?

If you're using django, you can use urlquote:

>>> from django.utils.http import urlquote
>>> urlquote(u"Müller")
u'M%C3%BCller'

Note that changes to Python since this answer was published mean that this is now a legacy wrapper. From the Django 2.1 source code for django.utils.http:

A legacy compatibility wrapper to Python's urllib.parse.quote() function.
(was used for unicode handling on Python 2)

Does Spring Data JPA have any way to count entites using method name resolving?

If anyone wants to get the count with based on multiple conditions than here is a sample custom query

@Query("select count(sl) from SlUrl sl where sl.user =?1 And sl.creationDate between ?2 And ?3")
    long countUrlsBetweenDates(User user, Date date1, Date date2);

Converting XDocument to XmlDocument and vice versa

You could try writing the XDocument to an XmlWriter piped to an XmlReader for an XmlDocument.

If I understand the concepts properly, a direct conversion is not possible (the internal structure is different / simplified with XDocument). But then, I might be wrong...

LINQ select one field from list of DTO objects to array

In the case you're interested in extremely minor, almost immeasurable performance increases, add a constructor to your Line class, giving you such:

public class Line
{
    public Line(string sku, int qty)
    {
        this.Sku = sku;
        this.Qty = qty;
    }

    public string Sku { get; set; }
    public int Qty    { get; set; }
}

Then create a specialized collection class based on List<Line> with one new method, Add:

public class LineList : List<Line>
{
    public void Add(string sku, int qty)
    {
        this.Add(new Line(sku, qty));
    }
}

Then the code which populates your list gets a bit less verbose by using a collection initializer:

LineList myLines = new LineList
{
    { "ABCD1", 1 },
    { "ABCD2", 1 },
    { "ABCD3", 1 }
};

And, of course, as the other answers state, it's trivial to extract the SKUs into a string array with LINQ:

string[] mySKUsArray = myLines.Select(myLine => myLine.Sku).ToArray();

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

Maven and adding JARs to system scope

Try this configuration. It worked for me:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <warSourceDirectory>mywebRoot</warSourceDirectory>
        <warSourceExcludes>source\**,build\**,dist\**,WEB-INF\lib\*,
            WEB-INF\classes\**,build.*
        </warSourceExcludes>
        <webXml>myproject/source/deploiement/web.xml</webXml>
        <webResources>
            <resource>
                <directory>mywebRoot/WEB-INF/lib</directory>
                <targetPath>WEB-INF/lib</targetPath>
                <includes>
                        <include>mySystemJar1.jar.jar</include>
                         <include>mySystemJar2.jar</include>
                   </includes>
            </resource>
        </webResources>
    </configuration>
</plugin>

What does "exited with code 9009" mean during this build?

This is pretty basic, I had this problem, and embarrassing simple fail.

Application use Command line arguments, I removed them and then added them back. Suddenly the project failed to build.

Visual Studio -> Project Properties -> verify that you use 'Debug' tab (not 'Build Events' tab) -> Command Line Arguments

I used the and Post/Pre-build text area, which was wrong this case.

TypeScript for ... of with index / key?

"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)

for (let i = 0; i < someArray.length ; i++) {
  let item = someArray[i];
}

CSS / HTML Navigation and Logo on same line

The <ul> is by default a block element, make it inline-block instead:

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  display:inline-block;
  vertical-align:top;
}

CodePen Demo

Convert a list of characters into a string

If the list contains numbers, you can use map() with join().

Eg:

>>> arr = [3, 30, 34, 5, 9]
>>> ''.join(map(str, arr))
3303459

Git: How to squash all commits on branch

Git reset, as mentioned in many answers before, is by far the best and simplest way to achieve what you want. I use it in the following workflow:

(on development branch)

git fetch
git merge origin/master  #so development branch has all current changes from master
git reset origin/master  #will show all changes from development branch to master as unstaged
git gui # do a final review, stage all changes you really want
git commit # all changes in a single commit
git branch -f master #update local master branch
git push origin master #push it

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

Using angular-google-maps

$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
    $scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};    
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());

Changing the CommandTimeout in SQL Management studio

Right click in the query pane, select Query Options... and in the Execution->General section (the default when you first open it) there is an Execution time-out setting.

incompatible character encodings: ASCII-8BIT and UTF-8

I've experienced similar problem. Although I had have UTF-8 encodings solved (with mysql2 and Encoding.default_external = Encoding::UTF_8 ...) incompatible character encodings: UTF-8 and ASCII-8BIT arose when I used incorrect helper parameters e.g. f.button :submit, "Zrušit" - works perfectly but f.button "Zrušit"- throws encoding error.

Using underscores in Java variables and method names

it's just your own style,nothing a bad style code,and nothing a good style code,just difference our code with the others.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I had this same problem because I bought a CSS template and it grabbed a javascript an external javascript file through http://whatever.js.com/javascript.js. I went to that page in my browser and then changed it to https://whatever... using SSL and it worked, so in my HTML javascript tag I just changed the URL to use https instead of http and it worked.

Using Python, how can I access a shared folder on windows network?

Use forward slashes to specify the UNC Path:

open('//HOST/share/path/to/file')

(if your Python client code is also running under Windows)

Get only part of an Array in Java?

public static int[] range(int[] array, int start, int end){
        int returner[] = new int[end-start];
        for(int x = 0; x <= end-start-1; x++){
            returner[x] = array[x+start];
        }
        return returner;
    }

this is a way to do the same thing as Array.copyOfRange but without importing anything

How to calculate an angle from three points?

I ran into a similar problem recently, only I needed to differentiate between a positive and negative angles. In case this is of use to anyone, I recommend the code snippet I grabbed from this mailing list about detecting rotation over a touch event for Android:

 @Override
 public boolean onTouchEvent(MotionEvent e) {
    float x = e.getX();
    float y = e.getY();
    switch (e.getAction()) {
    case MotionEvent.ACTION_MOVE:
       //find an approximate angle between them.

       float dx = x-cx;
       float dy = y-cy;
       double a=Math.atan2(dy,dx);

       float dpx= mPreviousX-cx;
       float dpy= mPreviousY-cy;
       double b=Math.atan2(dpy, dpx);

       double diff  = a-b;
       this.bearing -= Math.toDegrees(diff);
       this.invalidate();
    }
    mPreviousX = x;
    mPreviousY = y;
    return true;
 }

Update Jenkins from a war file

#on ubuntu, in /usr/share/jenkins:

sudo service jenkins stop
sudo mv jenkins.war jenkins.war.old
sudo wget https://updates.jenkins-ci.org/latest/jenkins.war
sudo service jenkins start

How to securely save username/password (local)?

I have used this before and I think in order to make sure credential persist and in a best secure way is

  1. you can write them to the app config file using the ConfigurationManager class
  2. securing the password using the SecureString class
  3. then encrypting it using tools in the Cryptography namespace.

This link will be of great help I hope : Click here

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

Git: How to return from 'detached HEAD' state

I had this edge case, where I checked out a previous version of the code in which my file directory structure was different:

git checkout 1.87.1                                    
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. 
Example:

  git checkout -b <new-branch-name>

HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'

In a case like this you may need to use --force (when you know that going back to the original branch and discarding changes is a safe thing to do).

git checkout master did not work:

$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...

git checkout master --force (or git checkout master -f) worked:

git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

How to get browser width using JavaScript code?

var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;

Both return integers and don't require jQuery. Cross-browser compatible.

I often find jQuery returns invalid values for width() and height()

Convert IQueryable<> type object to List<T> type?

Here's a couple of extension methods I've jury-rigged together to convert IQueryables and IEnumerables from one type to another (i.e. DTO). It's mainly used to convert from a larger type (i.e. the type of the row in the database that has unneeded fields) to a smaller one.

The positive sides of this approach are:

  • it requires almost no code to use - a simple call to .Transform<DtoType>() is all you need
  • it works just like .Select(s=>new{...}) i.e. when used with IQueryable it produces the optimal SQL code, excluding Type1 fields that DtoType doesn't have.

LinqHelper.cs:

public static IQueryable<TResult> Transform<TResult>(this IQueryable source)
{
    var resultType = typeof(TResult);
    var resultProperties = resultType.GetProperties().Where(p => p.CanWrite);

    ParameterExpression s = Expression.Parameter(source.ElementType, "s");

    var memberBindings =
        resultProperties.Select(p =>
            Expression.Bind(typeof(TResult).GetMember(p.Name)[0], Expression.Property(s, p.Name))).OfType<MemberBinding>();

    Expression memberInit = Expression.MemberInit(
        Expression.New(typeof(TResult)),
        memberBindings
        );

    var memberInitLambda = Expression.Lambda(memberInit, s);

    var typeArgs = new[]
        {
            source.ElementType, 
            memberInit.Type
        };

    var mc = Expression.Call(typeof(Queryable), "Select", typeArgs, source.Expression, memberInitLambda);

    var query = source.Provider.CreateQuery<TResult>(mc);

    return query;
}

public static IEnumerable<TResult> Transform<TResult>(this IEnumerable source)
{
    return source.AsQueryable().Transform<TResult>();
}

How to check if pytorch is using the GPU?

On the office site and the get start page, check GPU for PyTorch as below:

import torch
torch.cuda.is_available()

Reference: PyTorch|Get Start

VBA macro that search for file in multiple subfolders

I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.

Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant

For Each vFile In colFiles
     'file operation here or store file name/path in a string array for use later in the script
     filepath(n) = vFile
     filename = fso.GetFileName(vFile) 'If you want the filename without full path
     n=n+1
Next vFile


'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
    colFiles.Add strFolder & strTemp
    strTemp = Dir
Loop
If bIncludeSubfolders Then

    strTemp = Dir(strFolder, vbDirectory)
    Do While strTemp <> vbNullString
        If (strTemp <> ".") And (strTemp <> "..") Then
            If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
                colFolders.Add strTemp
            End If
        End If
        strTemp = Dir
    Loop
    'Call RecursiveDir for each subfolder in colFolders
    For Each vFolderName In colFolders
        Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
    Next vFolderName
End If
End Function

Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
    If Right(strFolder, 1) = "\" Then
        TrailingSlash = strFolder
    Else
        TrailingSlash = strFolder & "\"
    End If
End If
End Function

This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).

Unable to compile class for JSP

From the error it seems that you are trying to import something which is not a class.

If your MyFunctions is a class, you should import it like this:

<%@page import="com.TransportPortal.MyFunctions"%>

If it is a package and you want to import everything in the package you should do like this:

<%@page import="com.TransportPortal.MyFunctions.* "%>

Edit:

There are two cases which will give you this error, edited to cover both.

How to specify preference of library path?

As an alternative, you can use the environment variables LIBRARY_PATH and CPLUS_INCLUDE_PATH, which respectively indicate where to look for libraries and where to look for headers (CPATH will also do the job), without specifying the -L and -I options.

Edit: CPATH includes header with -I and CPLUS_INCLUDE_PATH with -isystem.

Create ul and li elements in javascript.

Here is my working code :

<!DOCTYPE html>
<html>
<head>
<style>
   ul#proList{list-style-position: inside}
   li.item{list-style:none; padding:5px;}
</style>
</head>
<body>
    <div id="renderList"></div>
</body>
<script>
    (function(){
        var ul = document.createElement('ul');
        ul.setAttribute('id','proList');

        productList = ['Electronics Watch','House wear Items','Kids wear','Women Fashion'];

        document.getElementById('renderList').appendChild(ul);
        productList.forEach(renderProductList);

        function renderProductList(element, index, arr) {
            var li = document.createElement('li');
            li.setAttribute('class','item');

            ul.appendChild(li);

            li.innerHTML=li.innerHTML + element;
        }
    })();
</script>
</html>

working jsfiddle example here

Converting to upper and lower case in Java

I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)

/**
 * Converts the given string to title case, where the first
 * letter is capitalized and the rest of the string is in
 * lower case.
 * 
 * @param s a string with unknown capitalization
 * @return a title-case version of the string
 */
public static String toTitleCase(String s)
{
    if (s.isEmpty())
    {
        return s;
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

Strings of length 1 do not needed to be treated as a special case because s.substring(1) returns the empty string when s has length 1.

VBA vlookup reference in different sheet

The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use. Please read this explanation and its conclusion, which I guess will give essential information.

The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:

  1. The value is actually not present (pointed out by chris nielsen).

  2. You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range. Code accounting for this (and items below) follows:

    Sub srch()
        Dim ws1 As Worksheet, ws2 As Worksheet
        Dim srchres As Variant
    
        Set ws1 = Worksheets("Sheet1")
        Set ws2 = Worksheets("Sheet2")
    
        On Error Resume Next
        srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
        On Error GoTo 0
        If (IsEmpty(srchres)) Then
          ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
        Else
          ws2.Range("E2").Value = srchres
        End If
    End Sub
    

I will point out a few additional notable points:

  1. Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).

  2. This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).

  3. Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.

  4. Both solutions by L42 qualify Ranges suitably.

  5. You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).

How to find whether or not a variable is empty in Bash?

Presuming Bash:

var=""

if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi

Single Line Nested For Loops

First of all, your first code doesn't use a for loop per se, but a list comprehension.

  1. Would be equivalent to

    for j in range(0, width): for i in range(0, height): m[i][j]

  2. Much the same way, it generally nests like for loops, right to left. But list comprehension syntax is more complex.

  3. I'm not sure what this question is asking


  1. Any iterable object that yields iterable objects that yield exactly two objects (what a mouthful - i.e [(1,2),'ab'] would be valid )

  2. The order in which the object yields upon iteration. i goes to the first yield, j the second.

  3. Yes, but not as pretty. I believe it is functionally equivalent to:

    l = list()
    for i,j in object:
        l.append(function(i,j))
    

    or even better use map:

    map(function, object)
    

    But of course function would have to get i, j itself.

  4. Isn't this the same question as 3?

How to create a delay in Swift?

DispatchQueue.global(qos: .background).async {
    sleep(4)
    print("Active after 4 sec, and doesn't block main")
    DispatchQueue.main.async{
        //do stuff in the main thread here
    }
}

How to check if Thread finished execution

Use the Thread.IsAlive flag. This is to give the thread status.

Why do I need 'b' to encode a string with Base64?

There is all you need:

expected bytes, not str

The leading b makes your string binary.

What version of Python do you use? 2.x or 3.x?

Edit: See http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit for the gory details of strings in Python 3.x

How do I install Keras and Theano in Anaconda Python on Windows?

In windows with anaconda, just go on conda prompt and use this command

conda install --channel https://conda.anaconda.org/conda-forge keras

Fastest way to download a GitHub project

You say:

To me if a source repository is available for public it should take less than 10 seconds to have that code in my filesystem.

And of course, if you want to use Git (which GitHub is all about), then what you do to get the code onto your system is called "cloning the repository".

It's a single Git invocation on the command line, and it will give you the code just as seen when you browse the repository on the web (when getting a ZIP archive, you will need to unpack it and so on, it's not always directly browsable). For the repository you mention, you would do:

$ git clone git://github.com/SpringSource/spring-data-graph-examples.git

The git:-type URL is the one from the page you linked to. On my system just now, running the above command took 3.2 seconds. Of course, unlike ZIP, the time to clone a repository will increase when the repository's history grows. There are options for that, but let's keep this simple.

I'm just saying: You sound very frustrated when a large part of the problem is your reluctance to actually use Git.

What is the __del__ method, How to call it?

__del__ is a finalizer. It is called when an object is garbage collected which happens at some point after all references to the object have been deleted.

In a simple case this could be right after you say del x or, if x is a local variable, after the function ends. In particular, unless there are circular references, CPython (the standard Python implementation) will garbage collect immediately.

However, this is an implementation detail of CPython. The only required property of Python garbage collection is that it happens after all references have been deleted, so this might not necessary happen right after and might not happen at all.

Even more, variables can live for a long time for many reasons, e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of cycle of references — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.

Since you have no guarantee it's executed, one should never put the code that you need to be run into __del__() — instead, this code belongs to finally clause of the try block or to a context manager in a with statement. However, there are valid use cases for __del__: e.g. if an object X references Y and also keeps a copy of Y reference in a global cache (cache['X -> Y'] = Y) then it would be polite for X.__del__ to also delete the cache entry.

If you know that the destructor provides (in violation of the above guideline) a required cleanup, you might want to call it directly, since there is nothing special about it as a method: x.__del__(). Obviously, you should you do so only if you know that it doesn't mind to be called twice. Or, as a last resort, you can redefine this method using

type(x).__del__ = my_safe_cleanup_method  

Markdown `native` text alignment

For python markdown with attr_list extension the syntax is a little different:

{: #someid .someclass somekey='some value' }

Example:

[Click here](http://exmaple.com){: .btn .btn-primary }

Lead information paragraph
{: .lead }

How to fix Error: laravel.log could not be opened?

If chmod does not work, you can try the following:

sudo nano /etc/php/7.x/fpm/pool.d/www.conf

Change the following paramaters:

user = www-data
group = www-data

To:

user = vagrant
group = vagrant

Remember to restart PHP FPM

sudo service php7.x-fpm restart

How to make an inline element appear on new line, or block element not occupy the whole line?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.feature_wrapper span {
    float: left;
    clear: left;
    display:inline
}

EDIT: now browsers have better support you can make use of the do inline-block.

.feature_wrapper span {
    display:inline-block;
    *display:inline; *zoom:1;
}

Depending on the text-align this will appear as through its inline while also acting like a block element.

Ping all addresses in network, windows

This post asks the same question, but for linux - you may find it helpful. Send a ping to each IP on a subnet

nmap is probably the best tool to use, as it can help identify host OS as well as being faster. It is available for the windows platform on the nmap.org site

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

The C# summarized descendant.

More reading: http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx

public sealed class ObservableCollectionEx<T> : ObservableCollection<T>
{
    #region Ctor

    public ObservableCollectionEx()
    {
    }

    public ObservableCollectionEx(List<T> list) : base(list)
    {
    }

    public ObservableCollectionEx(IEnumerable<T> collection) : base(collection)
    {
    }

    #endregion

    /// <summary> 
    /// Adds the elements of the specified collection to the end of the ObservableCollection(Of T). 
    /// </summary> 
    public void AddRange(
        IEnumerable<T> itemsToAdd,
        ECollectionChangeNotificationMode notificationMode = ECollectionChangeNotificationMode.Add)
    {
        if (itemsToAdd == null)
        {
            throw new ArgumentNullException("itemsToAdd");
        }
        CheckReentrancy();

        if (notificationMode == ECollectionChangeNotificationMode.Reset)
        {
            foreach (var i in itemsToAdd)
            {
                Items.Add(i);
            }

            OnPropertyChanged(new PropertyChangedEventArgs("Count"));
            OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

            return;
        }

        int startIndex = Count;
        var changedItems = itemsToAdd is List<T> ? (List<T>) itemsToAdd : new List<T>(itemsToAdd);
        foreach (var i in changedItems)
        {
            Items.Add(i);
        }

        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, changedItems, startIndex));
    }

    public enum ECollectionChangeNotificationMode
    {
        /// <summary>
        /// Notifies that only a portion of data was changed and supplies the changed items (not supported by some elements,
        /// like CollectionView class).
        /// </summary>
        Add,

        /// <summary>
        /// Notifies that the entire collection was changed, does not supply the changed items (may be inneficient with large
        /// collections as requires the full update even if a small portion of items was added).
        /// </summary>
        Reset
    }
}

replace \n and \r\n with <br /> in java

For me, this worked:

rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\n");

Tip: use regex tester for quick testing without compiling in your environment

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

this may help

Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");

Docker is in volume in use, but there aren't any Docker containers

I am fairly new to Docker. I was cleaning up some initial testing mess and was not able to remove a volume either. I had stopped all the running instances, performed a docker rmi -f $(docker image ls -q), but still received the Error response from daemon: unable to remove volume: remove uuid: volume is in use.

I did a docker system prune and it cleaned up what was needed to remove the last volume:

[0]$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Containers:
... about 15 containers UUID's truncated

Total reclaimed space: 2.273MB
[0]$ docker volume ls
DRIVER              VOLUME NAME
local              uuid
[0]$ docker volume rm uuid
uuid
[0]$

docker system prune

The client and daemon API must both be at least 1.25 to use this command. Use the docker version command on the client to check your client and daemon API versions.

Text file in VBA: Open/Find Replace/SaveAs/Close File

Just add this line

sFileName = "C:\someotherfilelocation"

right before this line

Open sFileName For Output As iFileNum

The idea is to open and write to a different file than the one you read earlier (C:\filelocation).

If you want to get fancy and show a real "Save As" dialog box, you could do this instead:

sFileName = Application.GetSaveAsFilename()

How to set ChartJS Y axis title?

In Chart.js version 2.0 this is possible:

options = {
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'probability'
      }
    }]
  }
}

See axes labelling documentation for more details.

Android, Java: HTTP POST Request

to @BalusC answer I would add how to convert the response in a String:

HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();

    String result = RestClient.convertStreamToString(instream);
    Log.i("Read from server", result);
}

Here is an example of convertStramToString.

AngularJS does not send hidden field value

In the controller:

$scope.entityId = $routeParams.entityId;

In the view:

<input type="hidden" name="entityId" ng-model="entity.entityId" ng-init="entity.entityId = entityId" />

Making view resize to its parent when added with addSubview

You can always do it in your UIViews - (void)didMoveToSuperview method. It will get called when added or removed from your parent (nil when removed). At that point in time just set your size to that of your parent. From that point on the autoresize mask should work properly.

Python match a string with regex

As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:

line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
     i in line

>> True
>> True

CustomErrors mode="Off"

This has been driving me insane for the past few days and couldn't get around it but have finally figured it out:

In my machine.config file I had an entry under <system.web>:

<deployment retail="true" />

This seems to override any other customError settings that you have specified in a web.config file, so setting the above entry to:

<deployment retail="false" />

now means that I can once again see the detailed error messages that I need to.

The machine.config is located at

32-bit

%windir%\Microsoft.NET\Framework\[version]\config\machine.config

64-bit

%windir%\Microsoft.NET\Framework64\[version]\config\machine.config 

Hope that helps someone out there and saves a few hours of hair-pulling.

Open Sublime Text from Terminal in macOS

Creating the file in the Default path did not work for me as the Menu.sublime-menu file has overridden almost all other menu options and left me with only the custom one.

What worked for me is creating the below file in path ~/Library/Application Support/Sublime Text 3/Packages/User/Main.sublime-menu (note directory User instead of Default):

[
    {
        "caption": "File",
        "mnemonic": "F",
        "id": "file",
        "children":
        [
            {
                "caption": "Open Recent More",
                "children":
                [
                    { "command": "open_recent_file", "args": {"index": 1 } },
                    { "command": "open_recent_file", "args": {"index": 2 } },
                    { "command": "open_recent_file", "args": {"index": 3 } },
                    { "command": "open_recent_file", "args": {"index": 4 } },
                    { "command": "open_recent_file", "args": {"index": 5 } },
                    { "command": "open_recent_file", "args": {"index": 6 } },
                    { "command": "open_recent_file", "args": {"index": 7 } },
                    { "command": "open_recent_file", "args": {"index": 8 } },
                    { "command": "open_recent_file", "args": {"index": 9 } },
                    { "command": "open_recent_file", "args": {"index": 10 } },
                    { "command": "open_recent_file", "args": {"index": 11 } },
                    { "command": "open_recent_file", "args": {"index": 12 } },
                    { "command": "open_recent_file", "args": {"index": 13 } },
                    { "command": "open_recent_file", "args": {"index": 14 } },
                    { "command": "open_recent_file", "args": {"index": 15 } },
                    { "command": "open_recent_file", "args": {"index": 16 } },
                    { "command": "open_recent_file", "args": {"index": 17 } },
                    { "command": "open_recent_file", "args": {"index": 18 } },
                    { "command": "open_recent_file", "args": {"index": 19 } },
                    { "command": "open_recent_file", "args": {"index": 20 } },
                    { "command": "open_recent_file", "args": {"index": 21 } },
                    { "command": "open_recent_file", "args": {"index": 22 } },
                    { "command": "open_recent_file", "args": {"index": 23 } },
                    { "command": "open_recent_file", "args": {"index": 24 } },
                    { "command": "open_recent_file", "args": {"index": 25 } },
                    { "command": "open_recent_file", "args": {"index": 26 } },
                    { "command": "open_recent_file", "args": {"index": 27 } },
                    { "command": "open_recent_file", "args": {"index": 28 } },
                    { "command": "open_recent_file", "args": {"index": 29 } },
                    { "command": "open_recent_file", "args": {"index": 30 } },
                    { "command": "open_recent_file", "args": {"index": 31 } },
                    { "command": "open_recent_file", "args": {"index": 32 } },
                    { "command": "open_recent_file", "args": {"index": 33 } },
                    { "command": "open_recent_file", "args": {"index": 34 } },
                    { "command": "open_recent_file", "args": {"index": 35 } },
                    { "command": "open_recent_file", "args": {"index": 36 } },
                    { "command": "open_recent_file", "args": {"index": 37 } },
                    { "command": "open_recent_file", "args": {"index": 38 } },
                    { "command": "open_recent_file", "args": {"index": 39 } },
                    { "command": "open_recent_file", "args": {"index": 40 } },
                    { "command": "open_recent_file", "args": {"index": 41 } },
                    { "command": "open_recent_file", "args": {"index": 42 } },
                    { "command": "open_recent_file", "args": {"index": 43 } },
                    { "command": "open_recent_file", "args": {"index": 44 } },
                    { "command": "open_recent_file", "args": {"index": 45 } },
                    { "command": "open_recent_file", "args": {"index": 46 } },
                    { "command": "open_recent_file", "args": {"index": 47 } },
                    { "command": "open_recent_file", "args": {"index": 48 } },
                    { "command": "open_recent_file", "args": {"index": 49 } },
                    { "command": "open_recent_file", "args": {"index": 50 } }
                ]
            }
        ]
    }
]

Result:

(needed to blur some parts of the image for security reasons)

open-recent-more.png

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

In order to be independent of the language and locale settings, you should use the ISO 8601 YYYYMMDD format - this will work on any SQL Server system with any language and regional setting in effect:

SELECT
   CAST(
      CAST(year AS VARCHAR(4)) +
      RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
      RIGHT('0' + CAST(day AS VARCHAR(2)), 2) 
   AS DATETIME)

Using setattr() in python

To add to the other answers, a common use case I have found for setattr() is when using configs. It is common to parse configs from a file (.ini file or whatever) into a dictionary. So you end up with something like:

configs = {'memory': 2.5, 'colour': 'red', 'charge': 0, ... }

If you want to then assign these configs to a class to be stored and passed around, you could do simple assignment:

MyClass.memory = configs['memory']
MyClass.colour = configs['colour']
MyClass.charge = configs['charge']
...

However, it is much easier and less verbose to loop over the configs, and setattr() like so:

for name, val in configs.items():
    setattr(MyClass, name, val)

As long as your dictionary keys have the proper names, this works very well and is nice and tidy.

*Note, the dict keys need to be strings as they will be the class object names.

How to display raw JSON data on a HTML page

JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.

However, about formatting, that's another matter. I guess you should change the title of your question.

Take a look at this question. Also see this page.

Adding values to a C# array

If you're writing in C# 3, you can do it with a one-liner:

int[] terms = Enumerable.Range(0, 400).ToArray();

This code snippet assumes that you have a using directive for System.Linq at the top of your file.

On the other hand, if you're looking for something that can be dynamically resized, as it appears is the case for PHP (I've never actually learned it), then you may want to use a List instead of an int[]. Here's what that code would look like:

List<int> terms = Enumerable.Range(0, 400).ToList();

Note, however, that you cannot simply add a 401st element by setting terms[400] to a value. You'd instead need to call Add(), like this:

terms.Add(1337);

How can I make one python file run another?

I used subprocess.call it's almost same like subprocess.Popen

from subprocess import call
call(["python", "your_file.py"])

VB.NET: Clear DataGridView

You may have a user scenario such that you want to keep the data binding and only temporarily clear the DataGridView. For instance, you have the user click on a facility on a map to show its attributes for editing. He is clicking for the first time, or he has already clicked on one and edited it. When the user clicks the "Select Facility" button, you would like to clear the DataGridView of the data from the previous facility (and not throw an error if it's his first selection). In this scenario, you can achieve the clean DataGridView by adapting the generated code that fills the DataGridView. Suppose the generated code looks like this:

    Try
        Me.Fh_maintTableAdapter.FillByHydrantNumber(Me.Fh2010DataSet.fh_maint, hydrantNum)
    Catch ex As System.Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    End Try

We are filling the DataGridView based on the hydrant number. Copy this code to the point where you want to clear the DataGridView and substitute a value for "hydrantNum" that you know will retrieve no data. The grid will clear. And when the user actually selects a facility (in this case, a hydrant), the binding is in place to fill the DataGridView appropriately.

Send mail via CMD console

A couple more command-line mailer programs:

Both support SSL too.

How can I convert integer into float in Java?

You just need to transfer the first value to float, before it gets involved in further computations:

float z = x * 1.0 / y;

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

CentOS: Enabling GD Support in PHP Installation

With CentOS 6.5+ and PHP 5.5:

yum install php55u-gd
service httpd restart

If you get an error like: cannot map zero-fill pages: Cannot allocate memory in Unknown on line 0, it could be because you don't have a swap file. I suggest you take a look at the tutorial mentioned in this answer: https://stackoverflow.com/a/20275282/828366

Tutorial: https://www.digitalocean.com/community/articles/how-to-add-swap-on-centos-6

Set folder browser dialog start location

Found on dotnet-snippets.de

With reflection this works and sets the real RootFolder!

using System;
using System.Reflection;
using System.Windows.Forms;

namespace YourNamespace
{
    public class RootFolderBrowserDialog
    {

        #region Public Properties

        /// <summary>
        ///   The description of the dialog.
        /// </summary>
        public string Description { get; set; } = "Chose folder...";

        /// <summary>
        ///   The ROOT path!
        /// </summary>
        public string RootPath { get; set; } = "";

        /// <summary>
        ///   The SelectedPath. Here is no initialization possible.
        /// </summary>
        public string SelectedPath { get; private set; } = "";

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        ///   Shows the dialog...
        /// </summary>
        /// <returns>OK, if the user selected a folder or Cancel, if no folder is selected.</returns>
        public DialogResult ShowDialog()
        {
            var shellType = Type.GetTypeFromProgID("Shell.Application");
            var shell = Activator.CreateInstance(shellType);
            var folder = shellType.InvokeMember(
                             "BrowseForFolder", BindingFlags.InvokeMethod, null,
                             shell, new object[] { 0, Description, 0, RootPath, });
            if (folder is null)
            {
                return DialogResult.Cancel;
            }
            else
            {
                var folderSelf = folder.GetType().InvokeMember(
                                     "Self", BindingFlags.GetProperty, null,
                                     folder, null);
                SelectedPath = folderSelf.GetType().InvokeMember(
                                   "Path", BindingFlags.GetProperty, null,
                                   folderSelf, null) as string;
                // maybe ensure that SelectedPath is set
                return DialogResult.OK;
            }
        }

        #endregion Public Methods

    }
}

How to convert string to float?

Main()  {
    float rmvivek,arni,csc;
    char *c="1234.00";
    csc=atof(c);
    csc+=55;
    printf("the value is %f",csc);
}

Generating a PDF file from React Components

you can user canvans with jsPDF

import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

 _exportPdf = () => {

     html2canvas(document.querySelector("#capture")).then(canvas => {
        document.body.appendChild(canvas);  // if you want see your screenshot in body.
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'PNG', 0, 0);
        pdf.save("download.pdf"); 
    });

 }

and you div with id capture is:

example

<div id="capture">
  <p>Hello in my life</p>
  <span>How can hellp you</span>
</div>

Specifying content of an iframe instead of the src attribute to a page

iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.

How to use ADB to send touch events to device using sendevent command?

In order to do a particular action (for example to open the web browser), you need to first figure out where to tap. To do that, you can first run:

adb shell getevent -l

Once you press on the device, at the location that you want, you will see this output:

<...>
/dev/input/event3: EV_KEY       BTN_TOUCH            DOWN
/dev/input/event3: EV_ABS       ABS_MT_POSITION_X    000002f5
/dev/input/event3: EV_ABS       ABS_MT_POSITION_Y    0000069e

adb is telling you that a key was pressed (button down) at position 2f5, 69e in hex which is 757 and 1694 in decimal.

If you now want to generate the same event, you can use the input tap command at the same position:

adb shell input tap 757 1694

More info can be found at:

https://source.android.com/devices/input/touch-devices.html http://source.android.com/devices/input/getevent.html

Why is the Java main method static?

main method always needs to be static because at RunTime JVM does not create any object to call main method and as we know in java static methods are the only methods which can be called using class name so main methods always needs to be static.

for more information visit this video :https://www.youtube.com/watch?v=Z7rPNwg-bfk&feature=youtu.be

Why do we have to override the equals() method in Java?

The default behavior for java.lang.Object is to compare references, but that's not appropriate for every kind of object. There are things called Value Objects (like BigDecimal or String), where objects with the same value are considered to be interchangeable, so the default behavior of equals is not desirable. Those kinds of objects have to implement equals and hashcode based on the value that the object takes on.

Marquee text in Android

I have tried all of the above, but for me its didn't work. When I add

android:clickable="true"

then it's worked perfectly for me. I don't know why. But I am happy to work it.

Here is my full answer.

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"

android:clickable="true"

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

Putting this before the command seems to work NODE_TLS_REJECT_UNAUTHORIZED=0. ex: NODE_TLS_REJECT_UNAUTHORIZED=0 npm ...

It would be best to figure out how to make node see self signed certificate as valid. strict-ssl suggestion above didn't work for me for some reason. If you understand the security implications and need a temporary quick fix, this is what I found in some random github issues during Google search of the error.

How to get a list of all valid IP addresses in a local network?

If you want to see which IP addresses are in use on a specific subnet then there are several different IP Address managers.

Try Angry IP Scanner or Solarwinds or Advanced IP Scanner

Why call super() in a constructor?

There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame
{
    public MyFrame() {
        super("My Window Title");
        ...
    }
}

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

In my application I have set

grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;

Also, I have set the

grid.AllowUserToOrderColumns = true;
grid.AllowUserToResizeColumns = true;

Now the column widths can be changed and the columns can be rearranged by the user. That works pretty well for me.

Maybe that will work for you.

Syntax for async arrow function

Async arrow functions look like this:

const foo = async () => {
  // do something
}

Async arrow functions look like this for a single argument passed to it:

const foo = async evt => {
  // do something with evt
}

Async arrow functions look like this for multiple arguments passed to it:

const foo = async (evt, callback) => {
  // do something with evt
  // return response with callback
}

The anonymous form works as well:

const foo = async function() {
  // do something
}

An async function declaration looks like this:

async function foo() {
  // do something
}

Using async function in a callback:

const foo = event.onCall(async () => {
  // do something
})

How can I transition height: 0; to height: auto; using CSS?

The max-height solution from Jake works well, if the hard-coded max-height value supplied is not much bigger than the real height (because otherwise there are undesirable delays and timing problems). On the other hand if the hard-coded value accidentially is not bigger than the real height the element won't open up completely.

The following CSS only solution also requires a hard-coded size that should be bigger than most of the occurring real sizes. However this solution also works if the real size is in some situations bigger than the hard-coded size. In that event the transition might jump a bit, but it will never leave a partially visible element. So this solution could also be used for unknown content, e.g. from a database, where you just know that the content is usually not bigger than x pixels, but there are exceptions.

Idea is to use a negative value for margin-bottom (or margin-top for a slightly diffenrent animation) and to place the content element into a middle element with overflow:hidden. The negative margin of the content element so reduces the height of the middle element.

The following code uses a transition on margin-bottom from -150px to 0px. This alone works fine as long as the content element is not higher than 150px. In addition it uses a transition on max-height for the middle element from 0px to 100%. This finally hides the middle element if the content element is higher than 150px. For max-height the transition is just used to delay its application by a second when closing, not for a smooth visiual effect ( and therefore it can run from 0px to 100%).

CSS:

.content {
  transition: margin-bottom 1s ease-in;
  margin-bottom: -150px;
}
.outer:hover .middle .content {
  transition: margin-bottom 1s ease-out;
  margin-bottom: 0px
}
.middle {
  overflow: hidden;
  transition: max-height .1s ease 1s;
  max-height: 0px
}
.outer:hover .middle {
  transition: max-height .1s ease 0s;
  max-height: 100%
}

HTML:

<div class="outer">
  <div class="middle">
    <div class="content">
      Sample Text
      <br> Sample Text
      <br> Sample Text
      <div style="height:150px">Sample Test of height 150px</div>
      Sample Text
    </div>
  </div>
  Hover Here
</div>

The value for margin bottom should be negative and as close as possible to the real height of the content element. If it('s absoute value) is bigger there are similar delay and timing problems as with the max-height solutions, which however can be limited as long as the hard coded size is not much bigger than the real one. If the absolute value for margin-bottom is smaller than the real height the tansition jumps a bit. In any case after the transition the content element is either fully displayed or fully removed.

For more details see my blog post http://www.taccgl.org/blog/css_transition_display.html#combined_height

How to declare a static const char* in your header file?

With C++11 you can use the constexpr keyword and write in your header:

private:
    static constexpr const char* SOMETHING = "something";


Notes:

  • constexpr makes SOMETHING a constant pointer so you cannot write

    SOMETHING = "something different";
    

    later on.

  • Depending on your compiler, you might also need to write an explicit definition in the .cpp file:

    constexpr const char* MyClass::SOMETHING;
    

inline if statement java, why is not working

The ternary operator ? : is to return a value, don't use it when you want to use if for flow control.

if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");

would work good enough.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

How can I change the size of a Bootstrap checkbox?

Or you can style it with pixels.

 .big-checkbox {width: 30px; height: 30px;}

Access denied for user 'homestead'@'localhost' (using password: YES)

A. After updating the .env file with database settings, clear larval setting by "running php artisan config:clear"

B. Please make sure you restart your apache server / rerun the "php artisan serve" command for your settings to take effect.

How to use zIndex in react-native

I finally solved this by creating a second object that imitates B.

My schema now looks like this:

enter image description here

I now have B1 (within parent of A) and B2 outside of it.

B1 and B2 are right next to one another, so to the naked eye it looks as if it's just 1 object.

How to add an element to a list?

Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

WebSocket with SSL

To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.

for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.

In firefox, this can be done from 'about:preferences' and searching for 'Certificates'

Not equal <> != operator on NULL

NULL is not anything...it is unknown. NULL does not equal anything. That is why you have to use the magic phrase IS NULL instead of = NULL in your SQL queries

You can refer this: http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx

How to check which locks are held on a table

I use a Dynamic Management View (DMV) to capture locks as well as the object_id or partition_id of the item that is locked.

(MUST switch to the Database you want to observe to get object_id)

SELECT 
     TL.resource_type,
     TL.resource_database_id,
     TL.resource_associated_entity_id,
     TL.request_mode,
     TL.request_session_id,
     WT.blocking_session_id,
     O.name AS [object name],
     O.type_desc AS [object descr],
     P.partition_id AS [partition id],
     P.rows AS [partition/page rows],
     AU.type_desc AS [index descr],
     AU.container_id AS [index/page container_id]
FROM sys.dm_tran_locks AS TL
INNER JOIN sys.dm_os_waiting_tasks AS WT 
 ON TL.lock_owner_address = WT.resource_address
LEFT OUTER JOIN sys.objects AS O 
 ON O.object_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.partitions AS P 
 ON P.hobt_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.allocation_units AS AU 
 ON AU.allocation_unit_id = TL.resource_associated_entity_id;

PHP - iterate on string characters

Step 1: convert the string to an array using the str_split function

$array = str_split($your_string);

Step 2: loop through the newly created array

foreach ($array as $char) {
 echo $char;
}

You can check the PHP docs for more information: str_split

How do I remove background-image in css?

div#a {
  background-image: url('../images/spacer.png');
  background-image: none !important;
}

I use a transparent spacer image in addition to the rule to remove the background image because IE6 seems to ignore the background-image: none even though it is marked !important.

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

To fix this you can simply use the exclamation mark if you're sure that the object is not null when accessing its property:

list!.values

At first sight, some people might confuse this with the safe navigation operator from angular, this is not the case!

list?.values

The ! post-fix expression will tell the TS compiler that variable is not null, if that's not the case it will crash at runtime

useRef

for useRef hook use like this

const value = inputRef?.current?.value

How to get a specific output iterating a hash in Ruby?

hash.keys.sort.each do |key|
  puts "#{key}-----"
  hash[key].each { |val| puts val }
end

How do I remove version tracking from a project cloned from git?

It's not a clever choice to move all .git* by hand, particularly when these .git files are hidden in sub-folders just like my condition: when I installed Skeleton Zend 2 by composer+git, there are quite a number of .git files created in folders and sub-folders.

I tried rm -rf .git on my GitHub shell, but the shell can not recognize the parameter -rf of Remove-Item.

www.montanaflynn.me introduces the following shell command to remove all .git files one time, recursively! It's really working!

find . | grep "\.git/" | xargs rm -rf

PDO error message?

Maybe this post is too old but it may help as a suggestion for someone looking around on this : Instead of using:

 print_r($this->pdo->errorInfo());

Use PHP implode() function:

 echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());

This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.

Hope it helps

ASP.NET set hiddenfield a value in Javascript

My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is

Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css. If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :

placeholderId.Attributes["style"] = "display:none";

Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.

How to export html table to excel or pdf in php

Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel

And for PDF generation use http://princexml.com/

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

I had an issue and fixed it after spending 2 hours to find. My environment as below:

cocoapod 0.39.0

swift 2.x

XCode 7.3.1

Steps:

  1. project path: project_name/project_name/your_bridging_header.h
  2. In Swift section at Build Setting, Objective-C Bridging Header should be: project_name/your_bridging_header.h
  3. In your_bridging_header.h, change all declarations from .h to #import
  4. In class which is being used your_3rd_party. Declare import your_3rd_party

Messages Using Command prompt in Windows 7

Open Notepad and write this

@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A

and then save as "Messenger.bat" and close the Notepad
Step 1:

when you open that saved notepad file it will open as a file Messenger command prompt with this details.

Messenger
User:

after "User" write the ip of the computer you want to contact and then press enter.

Get DOS path instead of Windows path

similar to this answer but uses a sub-routine

@echo off
CLS

:: my code goes here
set "my_variable=C:\Program Files (x86)\Microsoft Office"

echo %my_variable%

call :_sub_Short_Path "%my_variable%"
set "my_variable=%_s_Short_Path%"

echo %my_variable%

:: rest of my code goes here
goto EOF

:_sub_Short_Path
set _s_Short_Path=%~s1
EXIT /b

:EOF

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

create procedure <procedure_name>(p_cur out sys_refcursor) as begin open p_cur for select * from <table_name> end;

Unrecognized SSL message, plaintext connection? Exception

I think this is due to the connection established with the client machine is not secure.

It is due to the fact that you are talking to an HTTP server, not an HTTPS server. Probably you didn't use the correct port number for HTTPS.

Is it valid to have a html form inside another html form?

If you need your form to submit/commit data to a 1:M relational database, I would recommend creating an "after insert" DB trigger on table A that will insert the necessary data for table B.

How can I find out what version of git I'm running?

Or even just

git version

Results in something like

git version 1.8.3.msysgit.0

Arrays.asList() of an array

Arrays.asList(factors) returns a List<int[]>, not a List<Integer>. Since you're doing new ArrayList instead of new ArrayList<Integer> you don't get a compile error for that, but create an ArrayList<Object> which contains an int[] and you then implicitly cast that arraylist to ArrayList<Integer>. Of course the first time you try to use one of those "Integers" you get an exception.

JSON to string variable dump

Yes, JSON.stringify, can be found here, it's included in Firefox 3.5.4 and above.

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html

var myJSONText = JSON.stringify(myObject, replacer);

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

How to get Current Directory?

IMHO here are some improvements to anon's answer.

#include <windows.h>
#include <string>
#include <iostream>

std::string GetExeFileName()
{
  char buffer[MAX_PATH];
  GetModuleFileName( NULL, buffer, MAX_PATH );
  return std::string(buffer);
}

std::string GetExePath() 
{
  std::string f = GetExeFileName();
  return f.substr(0, f.find_last_of( "\\/" ));
}

How do I read a large csv file with pandas?

In addition to the answers above, for those who want to process CSV and then export to csv, parquet or SQL, d6tstack is another good option. You can load multiple files and it deals with data schema changes (added/removed columns). Chunked out of core support is already built in.

def apply(dfg):
    # do stuff
    return dfg

c = d6tstack.combine_csv.CombinerCSV([bigfile.csv], apply_after_read=apply, sep=',', chunksize=1e6)

# or
c = d6tstack.combine_csv.CombinerCSV(glob.glob('*.csv'), apply_after_read=apply, chunksize=1e6)

# output to various formats, automatically chunked to reduce memory consumption
c.to_csv_combine(filename='out.csv')
c.to_parquet_combine(filename='out.pq')
c.to_psql_combine('postgresql+psycopg2://usr:pwd@localhost/db', 'tablename') # fast for postgres
c.to_mysql_combine('mysql+mysqlconnector://usr:pwd@localhost/db', 'tablename') # fast for mysql
c.to_sql_combine('postgresql+psycopg2://usr:pwd@localhost/db', 'tablename') # slow but flexible

What is the difference between 'my' and 'our' in Perl?

Great question: How does our differ from my and what does our do?

In Summary:

Available since Perl 5, my is a way to declare non-package variables, that are:

  • private
  • new
  • non-global
  • separate from any package, so that the variable cannot be accessed in the form of $package_name::variable.


On the other hand, our variables are package variables, and thus automatically:

  • global variables
  • definitely not private
  • not necessarily new
  • can be accessed outside the package (or lexical scope) with the qualified namespace, as $package_name::variable.


Declaring a variable with our allows you to predeclare variables in order to use them under use strict without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars, which was only file-scoped, and not lexically scoped as is our.

For example, the formal, qualified name for variable $x inside package main is $main::x. Declaring our $x allows you to use the bare $x variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict or use strict "vars". The scope might be one, or two, or more packages, or one small block.

How to convert xml into array in php?

$array = json_decode(json_encode((array)simplexml_load_string($xml)),true);

Replace spaces with dashes and make all letters lower-case

_x000D_
_x000D_
var str = "Tatwerat Development Team";_x000D_
str = str.replace(/\s+/g, '-');_x000D_
console.log(str);_x000D_
console.log(str.toLowerCase())
_x000D_
_x000D_
_x000D_

PHP checkbox set to check based on database value

You can read database value in to a variable and then set the variable as follows

$app_container->assign('checked_flag', $db_data=='0'  ? '' : 'checked');

And in html you can just use the checked_flag variable as follows

<input type="checkbox" id="chk_test" name="chk_test" value="1" {checked_flag}>