Programs & Examples On #Amortized analysis

An amortized analysis is an analysis of the total runtime of a set of operations rather than the individual runtime of any one operation.

Equivalent of typedef in C#

If you know what you're doing, you can define a class with implicit operators to convert between the alias class and the actual class.

class TypedefString // Example with a string "typedef"
{
    private string Value = "";
    public static implicit operator string(TypedefString ts)
    {
        return ((ts == null) ? null : ts.Value);
    }
    public static implicit operator TypedefString(string val)
    {
        return new TypedefString { Value = val };
    }
}

I don't actually endorse this and haven't ever used something like this, but this could probably work for some specific circumstances.

Replace text in HTML page with jQuery

var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);

for variable:

var replaced = $("body").html().replace(new RegExp("-1o9-2202", "igm"),'The ALL new string');
$("body").html(replaced);

bash echo number of lines of file given in a bash variable without the file name

An Example Using Your Own Data

You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:

NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")

Explanation: Use Pipes or Redirection to Avoid Filenames in Output

The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:

# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd

# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41

# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41

# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41

As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.

SQL Inner Join On Null Values

This article has a good discussion on this issue. You can use

SELECT * 
FROM Y
INNER JOIN X ON EXISTS(SELECT X.QID 
                       INTERSECT 
                       SELECT y.QID);

How can I share Jupyter notebooks with non-programmers?

It depends on what you are intending to do with your Notebook: do you want that the user can recompute the results or just playing with them?

Static notebook

NBViewer is a great tool. You can directly use it inside Jupyter. Github has also a render, so you can directly link your file (such as https://github.com/my-name/my-repo/blob/master/mynotebook.ipynb)

Alive notebook

If you want your user to be able to recompute some parts, you can also use MyBinder. It takes some time to start your notebook, but the result is worth it.

As said by @Mapl, Google can host your notebook with Colab. A nice feature is to compute your cells over a GPU.

How to get date, month, year in jQuery UI datepicker?

Use the javascript Date object.

$(document).ready(function()  {
    $('#calendar').datepicker({
      dateFormat: 'yy-m-d',
      inline: true,
      onSelect: function(dateText, inst) { 
            var date = new Date(dateText);
            // change date.GetDay() to date.GetDate()
            alert(date.getDate() + date.getMonth() + date.getFullYear());
     } 
    });
});

PHP - Check if the page run on Mobile or Desktop browser

There are many great open source projects that make detection a lot easier. To name two:

  1. PHP mobile detect
  2. WURFL

Is mathematics necessary for programming?

I think it really depends on what you're trying to do, but IMHO, the CS and OS theory are more important than math here, and you really need only the math that they involve.

For example, there's a lot of CS background of scheduling theory and optimization that stands behind many schedulers in modern OSs. That is an example of something that would require some math, though not something super complicated.

But honestly, for most stuff, you don't need math. What you need is to learn the ability to think in base 2 and 16, such as the ability to mentally OR/AND. For example, if you have a byte and within that byte there are two 3-bit fields and 2 wasted bits, knowing which bits are in which fields are active when the byte value is something like 11 will make things slightly faster than having to use pen and paper.

read word by word from file in C++

I have edited the function for you,

void readFile()
{
    ifstream file;
    file.open ("program.txt");
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        cout<< word << '\n';
    }
}

How to redirect to previous page in Ruby On Rails?

In your edit action, store the requesting url in the session hash, which is available across multiple requests:

session[:return_to] ||= request.referer

Then redirect to it in your update action, after a successful save:

redirect_to session.delete(:return_to)

Import Android volley to Android Studio

Updating Warpzit's answer for Android Studio 1.3.2 (differences in bold)
(update: appears to be the same for Android 2.0)

  1. First get latest volley with git.
  2. In your current project (android studio) click [file] --> [New]--> [New Module].
  3. Now select [Import Gradle Project], Click Next
  4. Now select the directory where you downloaded Volley to.
  5. Now Android studio might guide you to do the rest but continue guide to verify that everything works correct
  6. Open settings.gradle (find in root) and add (or verify this is included):

    include ':app', ':volley'

  7. Now go to your build.gradle in your project and add the dependency:

    compile project(":volley")

Jquery UI Datepicker not displaying

This is a slightly different problem. With me the date picker would display but the css was not loading.

I fixed it by: Reload the theme (go to jquery ui css, line 43 and copy the url there to edit your themeroller theme) > Resave without the advanced options > Replace old files > Try not to change the urls and see if that helps as well.

RandomForestClassfier.fit(): ValueError: could not convert string to float

Well, there are important differences between how OneHot Encoding and Label Encoding work :

  • Label Encoding will basically switch your String variables to int. In this case, the 1st class found will be coded as 1, the 2nd as 2, ... But this encoding creates an issue.

Let's take the example of a variable Animal = ["Dog", "Cat", "Turtle"].

If you use Label Encoder on it, Animal will be [1, 2, 3]. If you parse it to your machine learning model, it will interpret Dog is closer than Cat, and farther than Turtle (because distance between 1 and 2 is lower than distance between 1 and 3).

Label encoding is actually excellent when you have ordinal variable.

For example, if you have a value Age = ["Child", "Teenager", "Young Adult", "Adult", "Old"],

then using Label Encoding is perfect. Child is closer than Teenager than it is from Young Adult. You have a natural order on your variables

  • OneHot Encoding (also done by pd.get_dummies) is the best solution when you have no natural order between your variables.

Let's take back the previous example of Animal = ["Dog", "Cat", "Turtle"].

It will create as much variable as classes you encounter. In my example, it will create 3 binary variables : Dog, Cat and Turtle. Then if you have Animal = "Dog", encoding will make it Dog = 1, Cat = 0, Turtle = 0.

Then you can give this to your model, and he will never interpret that Dog is closer from Cat than from Turtle.

But there are also cons to OneHotEncoding. If you have a categorical variable encountering 50 kind of classes

eg : Dog, Cat, Turtle, Fish, Monkey, ...

then it will create 50 binary variables, which can cause complexity issues. In this case, you can create your own classes and manually change variable

eg : regroup Turtle, Fish, Dolphin, Shark in a same class called Sea Animals and then appy a OneHotEncoding.

Mark error in form using Bootstrap

Bootstrap V3:

Official Doc Link 1
Official Doc Link 2

<div class="form-group has-success">
  <label class="control-label" for="inputSuccess">Input with success</label>
  <input type="text" class="form-control" id="inputSuccess" />
  <span class="help-block">Woohoo!</span>
</div>
<div class="form-group has-warning">
  <label class="control-label" for="inputWarning">Input with warning</label>
  <input type="text" class="form-control" id="inputWarning">
  <span class="help-block">Something may have gone wrong</span>
</div>
<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
  <span class="help-block">Please correct the error</span>
</div>

Solution to "subquery returns more than 1 row" error

use MAX in your SELECT to return on value.. EXAMPLE

INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))

instead of

INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))

try it without MAX it will more than one value

Today's Date in Perl in MM/DD/YYYY format

Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)

use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";

This gives you:

14.05.2014

When do I need to use a semicolon vs a slash in Oracle SQL?

I only use the forward slash once at the end of each script, to tell sqlplus that there is not more lines of code. In the middle of a script, I do not use a slash.

How to remove border of drop down list : CSS

This solution seems not working for me.

select {
    border: 0px;
    outline: 0px;
}

But you may set select border to the background color of the container and it will work.

How to add `style=display:"block"` to an element using jQuery?

There are multiple function to do this work that wrote in bottom based on priority.

Set one or more CSS properties for the set of matched elements.

$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
  display: "block",
  color: "red",
  ...
})

Display the matched elements and is roughly equivalent to calling .css("display", "block")

You can display element using .show() instead

$("div").show()

Set one or more attributes for the set of matched elements.

If target element hasn't style attribute, you can use this method to add inline style to element.

$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")

  • JavaScript

You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.

var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red"; 
// Multiple properties
div.setAttribute("style", "display:block; color:red");

Align two divs horizontally side by side center to the page using bootstrap css

The response provided by Ranveer (second answer above) absolutely does NOT work.

He says to use col-xx-offset-#, but that is not how offsets are used.

If you wasted your time trying to use col-xx-offset-#, as I did based on his answer, the solution is to use offset-xx-#.

Access-control-allow-origin with multiple domains

You can use owin middleware to define cors policy in which you can define multiple cors origins

return new CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider
            {
                PolicyResolver = context =>
                {
                    var policy = new CorsPolicy()
                    {
                        AllowAnyOrigin = false,
                        AllowAnyMethod = true,
                        AllowAnyHeader = true,
                        SupportsCredentials = true
                    };
                    policy.Origins.Add("http://foo.com");
                    policy.Origins.Add("http://bar.com");
                    return Task.FromResult(policy);
                }
            }
        };

Python dictionary replace values

I think this may help you solve your issue.

Imagine you have a dictionary like this:

dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}

And you want to change values by this one:

dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}

You can use code bellow to change values of dic0 properly respected to dic0t01 without worrying yourself about indexes in dictionary:

for x, y in dic0.items():
    dic0[x] = dic0to1[y]

Now you have:

>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}

How to tackle daylight savings using TimeZone in Java

This is the problem to start with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

The 3-letter abbreviations should be wholeheartedly avoided in favour of TZDB zone IDs. EST is Eastern Standard Time - and Standard time never observes DST; it's not really a full time zone name. It's the name used for part of a time zone. (Unfortunately I haven't come across a good term for this "half time zone" concept.)

You want a full time zone name. For example, America/New_York is in the Eastern time zone:

TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);

System.out.println(format.format(new Date()));

Get list from pandas DataFrame column headers

n = []
for i in my_dataframe.columns:
    n.append(i)
print n

C# static class constructor

Yes, a static class can have static constructor, and the use of this constructor is initialization of static member.

static class Employee1
{
    static int EmpNo;
    static Employee1()
    {
        EmpNo = 10;
        // perform initialization here
    }
    public static void Add()
    { 

    }
    public static void Add1()
    { 

    }
}

and static constructor get called only once when you have access any type member of static class with class name Class1

Suppose you are accessing the first EmployeeName field then constructor get called this time, after that it will not get called, even if you will access same type member.

 Employee1.EmployeeName = "kumod";
        Employee1.Add();
        Employee1.Add();

Why does a base64 encoded string have an = sign at the end

Its defined in RFC 2045 as a special padding character if fewer than 24 bits are available at the end of the encoded data.

OpenCV Python rotate image by X degrees around specific point

You can simply use the imutils package to do the rotation. it has two methods

  1. rotate: Rotate the image at specified angle. however the drawback is image might get cropped if it is not a square image.
  2. Rotate_bound: it overcomes the problem happened with rotate. It adjusts the size of the image accordingly while rotating the image.

more info you can get on this blog: https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/

NGinx Default public www location?

If you are on Ubuntu 14.04 you can find nginx www directory at following path:

yusuf@yusuf-he:/usr/share/nginx/html$ pwd
/usr/share/nginx/html
yusuf@yusuf-he:/usr/share/nginx/html$

glob exclude pattern

As mentioned by the accepted answer, you can't exclude patterns with glob, so the following is a method to filter your glob result.

The accepted answer is probably the best pythonic way to do things but if you think list comprehensions look a bit ugly and want to make your code maximally numpythonic anyway (like I did) then you can do this (but note that this is probably less efficient than the list comprehension method):

import glob

data_files = glob.glob("path_to_files/*.fits")

light_files = np.setdiff1d( data_files, glob.glob("*BIAS*"))
light_files = np.setdiff1d(light_files, glob.glob("*FLAT*"))

(In my case, I had some image frames, bias frames, and flat frames all in one directory and I just wanted the image frames)

How to use DISTINCT and ORDER BY in same SELECT statement?

Distinct will sort records in ascending order. If you want to sort in desc order use:

SELECT DISTINCT Category
FROM MonitoringJob
ORDER BY Category DESC

If you want to sort records based on CreationDate field then this field must be in the select statement:

SELECT DISTINCT Category, creationDate
FROM MonitoringJob
ORDER BY CreationDate DESC

How to concatenate two numbers in javascript?

Use "" + 5 + 6 to force it to strings. This works with numerical variables too:

_x000D_
_x000D_
var a = 5;_x000D_
var b = 6;_x000D_
console.log("" + a + b);
_x000D_
_x000D_
_x000D_

no module named zlib

For the case I met, I found there are missing modules after make. So I did the following:

  1. install zlib-devel
  2. make and install python again.

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

   <shape
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
   </shape>

circular ( >= Lollipop OR API Level >= 21)

    <shape
        android:useLevel="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
     </shape>

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();

Stop Animation

progressBar.clearAnimation();

P.S. unlike examples above, it give smooth animation.

How do I drop a MongoDB database from the command line?

LogIn into your mongoDB command line: And type the below commands. use "YOUR_DATABASE_NAME"; db.dropDatabase();

How to pass the values from one jsp page to another jsp without submit button?

You could do it in either of this ways , triggering an onclick on a form button like this,

<form id="myform" name="myform" method="post" action="demo2.jsp">
    <input type="text"  name="usnername" />
    <input type="text" name="password"/>        
    <input type="button" value="go" onclick="submitForm" />
</form>

And using javascript,

        function submitForm() {                
            document.forms[0].submit();
            return true;
        }

or you could also try Ajax to post your page

here is the link jQueryAjax

And also nice startup examples using Ajax and here

Hope this helps !!

instantiate a class from a variable in PHP?

I would recommend the call_user_func() or call_user_func_arrayphp methods. You can check them out here (call_user_func_array , call_user_func).

example

class Foo {
static public function test() {
    print "Hello world!\n";
}
}

 call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
 //or
 call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array

If you have arguments you are passing to the method , then use the call_user_func_array() function.

example.

class foo {
function bar($arg, $arg2) {
    echo __METHOD__, " got $arg and $arg2\n";
}
}

// Call the $foo->bar() method with 2 arguments
call_user_func_array(array("foo", "bar"), array("three", "four"));
//or
//FOO is the class, bar is the method both separated by ::
call_user_func_array("foo::bar"), array("three", "four"));

Converting a JToken (or string) to a given Type

var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:

var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);

Google Play Services Library update and missing symbol @integer/google_play_services_version

Android Studio 3.3.2 under Windows 10

File -> Invalidate Caches/Restart and choose invalidate and Restart button in the dialog appeared.

What is the difference between DAO and Repository patterns?

Repository is more abstract domain oriented term that is part of Domain Driven Design, it is part of your domain design and a common language, DAO is a technical abstraction for data access technology, repository is concerns only with managing existing data and factories for creation of data.

check these links:

http://warren.mayocchi.com/2006/07/27/repository-or-dao/ http://fabiomaulo.blogspot.com/2009/09/repository-or-dao-repository.html

How to import multiple .csv files at once?

Something like the following should result in each data frame as a separate element in a single list:

temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)

This assumes that you have those CSVs in a single directory--your current working directory--and that all of them have the lower-case extension .csv.

If you then want to combine those data frames into a single data frame, see the solutions in other answers using things like do.call(rbind,...), dplyr::bind_rows() or data.table::rbindlist().

If you really want each data frame in a separate object, even though that's often inadvisable, you could do the following with assign:

temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))

Or, without assign, and to demonstrate (1) how the file name can be cleaned up and (2) show how to use list2env, you can try the following:

temp = list.files(pattern="*.csv")
list2env(
  lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))), 
         read.csv), envir = .GlobalEnv)

But again, it's often better to leave them in a single list.

Oracle Age calculation from Date of birth and Today

Or how about this?

with some_birthdays as
( 
    select date '1968-06-09' d from dual union all
    select date '1970-06-10' from dual union all
    select date '1972-06-11' from dual union all
    select date '1974-12-11' from dual union all
    select date '1976-09-17' from dual
)
select trunc(sysdate) today
, d birth_date
, floor(months_between(trunc(sysdate),d)/12) age
from some_birthdays;

Ignore mapping one property with Automapper

Just for anyone trying to do this automatically, you can use that extension method to ignore non existing properties on the destination type :

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
        && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

to be used as follow :

Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();

thanks to Can Gencer for the tip :)

source : http://cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/

Get cart item name, quantity all details woocommerce

This will show only Cart Items Count.

 global $woocommerce; 
    echo $woocommerce->cart->cart_contents_count;

What is the 'override' keyword in C++ used for?

Wikipedia says:

Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

In detail, when you have an object foo that has a void hello() function:

class foo {
    virtual void hello(); // Code : printf("Hello!");
}

A child of foo, will also have a hello() function:

class bar : foo {
    // no functions in here but yet, you can call
    // bar.hello()
}

However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override

class bar : foo {
    virtual void hello() override; // Code : printf("Hello Bar!");
}

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Spring Test & Security: How to mock authentication?

Options to avoid using SecurityContextHolder in tests:

  • Option 1: use mocks - I mean mock SecurityContextHolder using some mock library - EasyMock for example
  • Option 2: wrap call SecurityContextHolder.get... in your code in some service - for example in SecurityServiceImpl with method getCurrentPrincipal that implements SecurityService interface and then in your tests you can simply create mock implementation of this interface that returns the desired principal without access to SecurityContextHolder.

How to enable cURL in PHP / XAMPP

If none of the above solves your problem and have installed with php-x86 (Windows 32 bit), then problem may be of openssl - for more info : How to fix libeay32.dll was not found error

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

If it is in inline context, in HTML try this:

onclick="functionCall();event.stopPropagation();

JQUERY: Uncaught Error: Syntax error, unrecognized expression

This can also happen in safari if you try a selector with a missing ], for example

$('select[name="something"')

but interestingly, this same jquery selector with a missing bracket will work in chrome.

fcntl substitute on Windows

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

What is default session timeout in ASP.NET?

It is 20 Minutes according to MSDN

From MSDN:

Optional TimeSpan attribute.

Specifies the number of minutes a session can be idle before it is abandoned. The timeout attribute cannot be set to a value that is greater than 525,601 minutes (1 year) for the in-process and state-server modes. The session timeout configuration setting applies only to ASP.NET pages. Changing the session timeout value does not affect the session time-out for ASP pages. Similarly, changing the session time-out for ASP pages does not affect the session time-out for ASP.NET pages. The default is 20 minutes.

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

PostgreSQL query to list all table names?

Open up the postgres terminal with the databse you would like:

psql dbname (run this line in a terminal)

then, run this command in the postgres environment

\d

This will describe all tables by name. Basically a list of tables by name ascending.

Then you can try this to describe a table by fields:

\d tablename.

Hope this helps.

How can I remove time from date with Moment.js?

formatCalendarDate = function (dateTime) {
    return moment.utc(dateTime).format('LL')
}

Removing index column in pandas when reading a csv

If your problem is same as mine where you just want to reset the column headers from 0 to column size. Do

df = pd.DataFrame(df.values);

EDIT:

Not a good idea if you have heterogenous data types. Better just use

df.columns = range(len(df.columns))

Including jars in classpath on commandline (javac or apt)

javac HelloWorld.java -classpath ./javax.jar , assuming javax is in current folder, and compile target is "HelloWorld.java", and you can compile without a main method

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs

@Bean
WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
        }
    }
}

javascript clear field value input

do like

<input name="name" id="name" type="text" value="Name" 
   onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>

and js

function fillField(input,val) {
      if(input.value == "")
         input.value=val;
};

function clearField(input,val) {
      if(input.value == val)
         input.value="";
};

update

here is a demo fiddle of the same

Relative paths in Python

A simple solution would be

import os
os.chdir(os.path.dirname(__file__))

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

Best way to iterate through a Perl array

IMO, implementation #1 is typical and being short and idiomatic for Perl trumps the others for that alone. A benchmark of the three choices might offer you insight into speed, at least.

Padding or margin value in pixels as integer using jQuery

The parseInt function has a "radix" parameter which defines the numeral system used on the conversion, so calling parseInt(jQuery('#something').css('margin-left'), 10); returns the left margin as an Integer.

This is what JSizes use.

How to get an array of specific "key" in multidimensional array without looping

If id is the first key in the array, this'll do:

$ids = array_map('current', $users);

You should not necessarily rely on this though. :)

Convert .pfx to .cer

If you're working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:

Get-PfxCertificate -FilePath InputBundle.pfx | 
Export-Certificate -FilePath OutputCert.der -Type CERT

Newline added for clarity, but you can of course have this all on a single line.

If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem

If you need to export to a different format than DER encoded, you can change the -Type parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed:

-Type <CertType>
    Specifies the type of output file for the certificate export as follows. 
     -- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates. 
     -- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate. 
     -- P7B: A PKCS#7 file format which can contain one or more certificates.

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

I followed the steps in killthrush's answer and to my surprise it did not work. Logging in as sa I could see my Windows domain user and had made them a sysadmin, but when I tried logging in with Windows auth I couldn't see my login under logins, couldn't create databases, etc. Then it hit me. That login was probably tied to another domain account with the same name (with some sort of internal/hidden ID that wasn't right). I had left this organization a while back and then came back months later. Instead of re-activating my old account (which they might have deleted) they created a new account with the same domain\username and a new internal ID. Using sa I deleted my old login, re-added it with the same name and added sysadmin. I logged back in with Windows Auth and everything looks as it should. I can now see my logins (and others) and can do whatever I need to do as a sysadmin using my Windows auth login.

Remove all padding and margin table HTML and CSS

Try this:

table { 
border-spacing: 0;
border-collapse: collapse;
}

How to get the response of XMLHttpRequest?

I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

_x000D_
_x000D_
const url = "https://stackoverflow.com";
fetch(url)
    .then(
        response => response.text() // .json(), etc.
        // same as function(response) {return response.text();}
    ).then(
        html => console.log(html)
    );
_x000D_
_x000D_
_x000D_

In Node.js, you'll need to import fetch using:

const fetch = require("node-fetch");

If you want to use it synchronously (doesn't work in top scope):

const json = await fetch(url)
  .then(response => response.json())
  .catch((e) => {});

More Info:

Mozilla Documentation

Can I Use (95% Feb 2020)

Matt Walsh Tutorial

rbind error: "names do not match previous names"

The names of the first dataframe do not match the names of the second one. Just as the error message says.

> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE

If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:

> names(xd.small[[1]]) <- names(xd.small[[2]]) 
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE

Then things should proceed happily.

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

You can simply add an inspect() method to your object which will override the representation of object in console.log messages

eg:

var myObject = {
   "a":"a",
   "b":{
      "c":"c",
      "d":{
         "e":"e",
         "f":{
            "g":"g",
            "h":{
               "i":"i"
            }
         }
      }
   }
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }

then, your object will be represented as required in both console.log and node shell


Update:

object.inspect has been deprecated ( https://github.com/nodejs/node/issues/15549). Use myObject[util.inspect.custom] instead:

const util = require('util')

var myObject = {
  /* nested properties not shown */
}

myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }


console.log(util.inspect(myObject))

Read from file or stdin

You may want to look at how this is done in the cat utility, for example.

See code here. If there is no filename as argument, or it is "-", then stdin is used for input. stdin will be there, even if no data is pushed to it (but then, your read call may wait forever).

Is there an arraylist in Javascript?

In Java script you declare array as below:

var array=[];
array.push();

and for arraylist or object or array you have to use json; and Serialize it using json by using following code:

 var serializedMyObj = JSON.stringify(myObj);

Combine [NgStyle] With Condition (if..else)

The previous answers did not work for me, so I decided to improve this.

You should work with url(''), and not with value.

<li *ngFor="let item of items">
  <div
    class="img-wrapper"
    [ngStyle]="{'background-image': !item.featured ? 'url(\'images/img1.png\')' : 'url(\'images/img2.png\')'}">
  </div>
</li>

Remove characters from C# string

I might as well throw this out here.

Make an extension to remove chars from a string:

public static string RemoveChars(this string input, params char[] chars)
{
    var sb = new StringBuilder();
    for (int i = 0; i < input.Length; i++)
    {
        if (!chars.Contains(input[i]))
            sb.Append(input[i]);
    }
    return sb.ToString();
}

And it's usable like this:

string str = "My name @is ,Wan.;'; Wan";
string cleanedUpString = str.RemoveChars('@', ',', '.', ';', '\'');

Or just like this:

string str = "My name @is ,Wan.;'; Wan".RemoveChars('@', ',', '.', ';', '\'');

Converting from signed char to unsigned char and back again?

This is one of the reasons why C++ introduced the new cast style, which includes static_cast and reinterpret_cast

There's two things you can mean by saying conversion from signed to unsigned, you might mean that you wish the unsigned variable to contain the value of the signed variable modulo the maximum value of your unsigned type + 1. That is if your signed char has a value of -128 then CHAR_MAX+1 is added for a value of 128 and if it has a value of -1, then CHAR_MAX+1 is added for a value of 255, this is what is done by static_cast. On the other hand you might mean to interpret the bit value of the memory referenced by some variable to be interpreted as an unsigned byte, regardless of the signed integer representation used on the system, i.e. if it has bit value 0b10000000 it should evaluate to value 128, and 255 for bit value 0b11111111, this is accomplished with reinterpret_cast.

Now, for the two's complement representation this happens to be exactly the same thing, since -128 is represented as 0b10000000 and -1 is represented as 0b11111111 and likewise for all in between. However other computers (usually older architectures) may use different signed representation such as sign-and-magnitude or ones' complement. In ones' complement the 0b10000000 bitvalue would not be -128, but -127, so a static cast to unsigned char would make this 129, while a reinterpret_cast would make this 128. Additionally in ones' complement the 0b11111111 bitvalue would not be -1, but -0, (yes this value exists in ones' complement,) and would be converted to a value of 0 with a static_cast, but a value of 255 with a reinterpret_cast. Note that in the case of ones' complement the unsigned value of 128 can actually not be represented in a signed char, since it ranges from -127 to 127, due to the -0 value.

I have to say that the vast majority of computers will be using two's complement making the whole issue moot for just about anywhere your code will ever run. You will likely only ever see systems with anything other than two's complement in very old architectures, think '60s timeframe.

The syntax boils down to the following:

signed char x = -100;
unsigned char y;

y = (unsigned char)x;                    // C static
y = *(unsigned char*)(&x);               // C reinterpret
y = static_cast<unsigned char>(x);       // C++ static
y = reinterpret_cast<unsigned char&>(x); // C++ reinterpret

To do this in a nice C++ way with arrays:

jbyte memory_buffer[nr_pixels];
unsigned char* pixels = reinterpret_cast<unsigned char*>(memory_buffer);

or the C way:

unsigned char* pixels = (unsigned char*)memory_buffer;

Laravel Escaping All HTML in Blade Template

Change your syntax from {{ }} to {!! !!}.

As The Alpha said in a comment above (not an answer so I thought I'd post), in Laravel 5, the {{ }} (previously non-escaped output syntax) has changed to {!! !!}. Replace {{ }} with {!! !!} and it should work.

Change URL parameters

I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.

                      function addOrUpdateQueryParam(param, newval, search) {

                        var questionIndex = search.indexOf('?');

                        if (questionIndex < 0) {
                            search = search + '?';
                            search = search + param + '=' + newval;
                            return search;
                        }

                        var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
                        var query = search.replace(regex, "$1").replace(/&$/, '');

                        var indexOfEquals = query.indexOf('=');

                        return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
                    }

How to render html with AngularJS templates

So maybe you want to have this in your index.html to load the library, script, and initialize the app with a view:

<html>
  <body ng-app="yourApp">
    <div class="span12">
      <div ng-view=""></div>
    </div>
    <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
    <script src="script.js"></script>
  </body>
</html>

Then yourView.html could just be:

<div>
  <h1>{{ stuff.h1 }}</h1>
  <p>{{ stuff.content }}</p>
</div>

scripts.js could have your controller with data $scope'd to it.

angular.module('yourApp')
    .controller('YourCtrl', function ($scope) {
      $scope.stuff = {
        'h1':'Title',
        'content':"A paragraph..."
      };
    });

Lastly, you'll have to config routes and assign the controller to view for it's $scope (i.e. your data object)

angular.module('yourApp', [])
.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'views/yourView.html',
      controller: 'YourCtrl'
    });
});

I haven't tested this, sorry if there's a bug but I think this is the Angularish way to get data

Spark Dataframe distinguish columns with duplicated name

If you have a more complicated use case than described in the answer of Glennie Helles Sindholt e.g. you have other/few non-join column names that are also same and want to distinguish them while selecting it's best to use aliasses, e.g:

df3 = df1.select("a", "b").alias("left")\
   .join(df2.select("a", "b").alias("right"), ["a"])\
   .select("left.a", "left.b", "right.b")

df3.columns
['a', 'b', 'b']

Convert string to buffer Node

Note: Just reposting John Zwinck's comment as answer.

One issue might be that you are using a older version of Node (for the moment, I cannot upgrade, codebase struck with v4.3.1). Simple solution here is, using the deprecated way:

new Buffer(bufferStr)

Note #2: This is for people struck in older version, for whom Buffer.from does not work

Transferring files over SSH

No, you still need to scp [from] [to] whichever way you're copying

The difference is, you need to scp -p server:serverpath localpath

Selenium C# WebDriver: Wait until element is present

Alternatively you can use an implicit wait:

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

Best way to convert pdf files to tiff files

Using GhostScript from the command line, I've used the following in the past:

on Windows:

gswin32c -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf

on *nix:

gs -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf

For a large number of files, a simple batch/shell script could be used to convert an arbitrary number of files...

Javascript getElementById based on a partial string

querySelectorAll with modern enumeration

polls = document.querySelectorAll('[id ^= "poll-"]');
Array.prototype.forEach.call(polls, callback);

function callback(element, iterator) {
    console.log(iterator, element.id);
}

The first line selects all elements which id starts with the string poll-. The second line evokes the enumeration and a callback function.

How do I search an SQL Server database for a string?

For getting a table by name in SQL Server:

SELECT *
FROM sys.Tables
WHERE name LIKE '%Employees%'

For finding a stored procedure by name:

SELECT name
FROM sys.objects
WHERE name = 'spName'

To get all stored procedures related to a table:

----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

"OverflowError: Python int too large to convert to C long" on windows but not mac

Could anyone help explain why

In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.

The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.

or give a solution for the code on windows? Thanks so much!

Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in the most sensible choice would probably be np.int64

How to change the interval time on bootstrap carousel?

The best way to get rid on it is adding or modifying the data-interval attribute like this:

<div data-ride="carousel" class="carousel slide" data-interval="10000" id="myCarousel">

It's specified on ms like it's usually on js, so 1000 = 1s, 3000 = 3s... 10000 = 10s.

By the way you can also specify it at 0 for not sliding automatically. It's useful when showing product images on mobile for example.

<div data-ride="carousel" class="carousel slide" data-interval="0" id="myCarousel">

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

In my circumstances the error was due to the fact the listener did not have the db's service registered. I solved this by registering the services. Example:

My descriptor in tnsnames.ora:

LOCALDB =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = LOCALDB)
    )
  )

So, I proceed to register the service in the listener.ora manually:

SID_LIST_LISTENER =
    (SID_DESC =
      (GLOBAL_DBNAME = LOCALDB)
      (ORACLE_HOME = C:\Oracle\product\11.2.0\dbhome_1)
      (SID_NAME = LOCALDB)
    )

Finally, restart the listener by command:

> lsnrctl stop
> lsnrctl start

Done!

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

Can Console.Clear be used to only clear a line instead of whole console?

public static void ClearLine(int lines = 1)
{
    for (int i = 1; i <= lines; i++)
    {
        Console.SetCursorPosition(0, Console.CursorTop - 1);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, Console.CursorTop - 1);
    }
}

Preloading CSS Images

If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)

Change PictureBox's image to image from my resources?

Ken has the right solution, but you don't want to add the picturebox.Image.Load() member method.

If you do it with a Load and the ImageLocation is not set, it will fail with a "Image Location must be set" exception. If you use the picturebox.Refresh() member method, it works without the exception.

Completed code below:

public void showAnimatedPictureBox(PictureBox thePicture)
{
            thePicture.Image = Properties.Resources.hamster;
            thePicture.Refresh();
            thePicture.Visible = true;
}

It is invoked as: showAnimatedPictureBox( myPictureBox );

My XAML looks like:

    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="myApp.MainWindow"
        Title="myApp" Height="679.079" Width="986">

        <StackPanel Width="136" Height="Auto" Background="WhiteSmoke" x:Name="statusPanel">
            <wfi:WindowsFormsHost>
                <winForms:PictureBox x:Name="myPictureBox">
                </winForms:PictureBox>
            </wfi:WindowsFormsHost>
            <Label x:Name="myLabel" Content="myLabel" Margin="10,3,10,5" FontSize="20" FontWeight="Bold" Visibility="Hidden"/>
        </StackPanel>
</Window>

I realize this is an old post, but loading the image directly from a resource is was extremely unclear on Microsoft's site, and this was the (partial) solution I came to. Hope it helps someone!

Simple way to compare 2 ArrayLists

List<String> oldList = Arrays.asList("a", "b", "c", "d", "e", "f");
List<String> modifiedList = Arrays.asList("a", "b", "c", "d", "e", "g");

List<String> added = new HashSet<>(modifiedList);
List<String> removed = new HashSet<>(oldList);

modifiedList.stream().filter(removed::remove).forEach(added::remove);

// added items
System.out.println(added);
// removed items
System.out.println(removed);

font-weight is not working properly?

Its because the font size (9px) is too small to display bold. Try 11px or more and it works fine.

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

A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL (doc). The URL object has a Query() method (doc) that returns a Values type, which is simply a map[string][]string of the QueryString parameters.

If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm() and then use req.Form field to get the map of key-value pairs, but you can also call FormValue(key) to get the value of a specific key. This calls ParseForm() if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).

How to add an event after close the modal window?

I find answer. Thanks all but right answer next:

$("#myModal").on("hidden", function () {
  $('#result').html('yes,result');
});

Events here http://bootstrap-ru.com/javascript.php#modals

UPD

For Bootstrap 3.x need use hidden.bs.modal:

$("#myModal").on("hidden.bs.modal", function () {
  $('#result').html('yes,result');
});

How to get domain root url in Laravel 4?

My hint:

  1. FIND IF EXISTS in .env:

    APP_URL=http://yourhost.dev

  2. REPLACE TO (OR ADD)

    APP_DOMAIN=yourhost.dev

  3. FIND in config/app.php:

    'url' => env('APP_URL'),

  4. REPLACE TO

    'domain' => env('APP_DOMAIN'),

    'url' => 'http://' . env('APP_DOMAIN'),

  5. USE:

    Config::get('app.domain'); // yourhost.dev

    Config::get('app.url') // http://yourhost.dev

  6. Do your magic!

Chrome DevTools Devices does not detect device when plugged in

workaround if you don't have ADT (Android Development Toolkit) installed:

Managed to detect android based Samsung Galaxy phone after downloading andorid SDK platform-tools.zip and running the following command: "adb devices". It started some deamon, found attached device, and I was also able to see it in chrome canary inspect tab.

previously I also installed "Universal ADB driver" but not sure if this was required

Can CSS detect the number of children an element has?

No, there is nothing like this in CSS. You can, however, use JavaScript to calculate the number of children and apply styles.

Convert NSNumber to int in Objective-C

A less verbose approach:

int number = [dict[@"integer"] intValue];

Add single element to array in numpy

a[0] isn't an array, it's the first element of a and therefore has no dimensions.

Try using a[0:1] instead, which will return the first element of a inside a single item array.

Why shouldn't `&apos;` be used to escape single quotes?

&apos; is not part of the HTML 4 standard.

&quot; is, though, so is fine to use.

Define global constants

Using a property file that is generated during a build is simple and easy. This is the approach that the Angular CLI uses. Define a property file for each environment and use a command during build to determine which file gets copied to your app. Then simply import the property file to use.

https://github.com/angular/angular-cli#build-targets-and-environment-files

How to declare an array of strings in C++?

Instead of that macro, might I suggest this one:

template<typename T, int N>
inline size_t array_size(T(&)[N])
{
    return N;
}

#define ARRAY_SIZE(X)   (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1)

1) We want to use a macro to make it a compile-time constant; the function call's result is not a compile-time constant.

2) However, we don't want to use a macro because the macro could be accidentally used on a pointer. The function can only be used on compile-time arrays.

So, we use the defined-ness of the function to make the macro "safe"; if the function exists (i.e. it has non-zero size) then we use the macro as above. If the function does not exist we return a bad value.

Adding a default value in dropdownlist after binding with database

You can add it programmatically or in the markup, but if you add it programmatically, rather than Add the item, you should Insert it as position zero so that it is the first item:

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");

The default item is expected to be the first item in the list. If you just Add it, it will be on the bottom and will not be selected by default.

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

Path of assets in CSS files in Symfony 2

If it can help someone, we have struggled a lot with Assetic, and we are now doing the following in development mode:

  • Set up like in Dumping Asset Files in the dev Environmen so in config_dev.yml, we have commented:

    #assetic:
    #    use_controller: true
    

    And in routing_dev.yml

    #_assetic:
    #    resource: .
    #    type:     assetic
    
  • Specify the URL as absolute from the web root. For example, background-image: url("/bundles/core/dynatree/skins/skin/vline.gif"); Note: our vhost web root is pointing on web/.

  • No usage of cssrewrite filter

What are the differences between numpy arrays and matrices? Which one should I use?

Just to add one case to unutbu's list.

One of the biggest practical differences for me of numpy ndarrays compared to numpy matrices or matrix languages like matlab, is that the dimension is not preserved in reduce operations. Matrices are always 2d, while the mean of an array, for example, has one dimension less.

For example demean rows of a matrix or array:

with matrix

>>> m = np.mat([[1,2],[2,3]])
>>> m
matrix([[1, 2],
        [2, 3]])
>>> mm = m.mean(1)
>>> mm
matrix([[ 1.5],
        [ 2.5]])
>>> mm.shape
(2, 1)
>>> m - mm
matrix([[-0.5,  0.5],
        [-0.5,  0.5]])

with array

>>> a = np.array([[1,2],[2,3]])
>>> a
array([[1, 2],
       [2, 3]])
>>> am = a.mean(1)
>>> am.shape
(2,)
>>> am
array([ 1.5,  2.5])
>>> a - am #wrong
array([[-0.5, -0.5],
       [ 0.5,  0.5]])
>>> a - am[:, np.newaxis]  #right
array([[-0.5,  0.5],
       [-0.5,  0.5]])

I also think that mixing arrays and matrices gives rise to many "happy" debugging hours. However, scipy.sparse matrices are always matrices in terms of operators like multiplication.

How to get featured image of a product in woocommerce

In WC 3.0+ versions the image can get by below code.

$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $item->get_product_id() ), 'single-post-thumbnail' );
echo $image_url[0]

Intent from Fragment to Activity

For Kotlin you can use

val myIntent = Intent(activity, your_destination_activity::class.java)
startActivity(myIntent)

How to download and save a file from Internet using Java?

If you are behind a proxy, you can set the proxies in java program as below:

        Properties systemSettings = System.getProperties();
        systemSettings.put("proxySet", "true");
        systemSettings.put("https.proxyHost", "https proxy of your org");
        systemSettings.put("https.proxyPort", "8080");

If you are not behind a proxy, don't include the lines above in your code. Full working code to download a file when you are behind a proxy.

public static void main(String[] args) throws IOException {
        String url="https://raw.githubusercontent.com/bpjoshi/fxservice/master/src/test/java/com/bpjoshi/fxservice/api/TradeControllerTest.java";
        OutputStream outStream=null;
        URLConnection connection=null;
        InputStream is=null;
        File targetFile=null;
        URL server=null;
        //Setting up proxies
        Properties systemSettings = System.getProperties();
            systemSettings.put("proxySet", "true");
            systemSettings.put("https.proxyHost", "https proxy of my organisation");
            systemSettings.put("https.proxyPort", "8080");
            //The same way we could also set proxy for http
            System.setProperty("java.net.useSystemProxies", "true");
            //code to fetch file
        try {
            server=new URL(url);
            connection = server.openConnection();
            is = connection.getInputStream();
            byte[] buffer = new byte[is.available()];
            is.read(buffer);

                targetFile = new File("src/main/resources/targetFile.java");
                outStream = new FileOutputStream(targetFile);
                outStream.write(buffer);
        } catch (MalformedURLException e) {
            System.out.println("THE URL IS NOT CORRECT ");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Io exception");
            e.printStackTrace();
        }
        finally{
            if(outStream!=null) outStream.close();
        }
    }

Selecting data from two different servers in SQL Server

These are all fine answers, but this one is missing and it has it's own powerful uses. Possibly it doesn't fit what the OP wanted, but the question was vague and I feel others may find their way here. Basically you can use 1 window to simultaneously run a query against multiple servers, here's how:

In SSMS open Registered Servers and create a New Server Group under Local Server Groups.

Under this group create New Server Registration for each server you wish to query. If the DB names are different ensure to set a default for each in the properties.

Now go back to the Group you created in the first step, right click and select New Query. A new query window will open and any query you run will be executed on each server in the group. The results are presented in a single data set with an extra column name indicating which server the record came from. If you use the status bar you will note the server name is replaced with multiple.

Find where java class is loaded from

Assuming that you're working with a class named MyClass, the following should work:

MyClass.class.getClassLoader();

Whether or not you can get the on-disk location of the .class file is dependent on the classloader itself. For example, if you're using something like BCEL, a certain class may not even have an on-disk representation.

How do I empty an array in JavaScript?

Performance test:

http://jsperf.com/array-clear-methods/3

a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length)  // 97% slower
while (a.length > 0) {
    a.pop();
} // Fastest

How to change the style of a DatePicker in android?

call like this

 button5.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub

 DialogFragment dialogfragment = new DatePickerDialogTheme();

 dialogfragment.show(getFragmentManager(), "Theme");

 }
 });

public static class DatePickerDialogTheme extends DialogFragment implements DatePickerDialog.OnDateSetListener{

     @Override
     public Dialog onCreateDialog(Bundle savedInstanceState){
     final Calendar calendar = Calendar.getInstance();
     int year = calendar.get(Calendar.YEAR);
     int month = calendar.get(Calendar.MONTH);
     int day = calendar.get(Calendar.DAY_OF_MONTH);

//for one

//for two 

 DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(),
 AlertDialog.THEME_DEVICE_DEFAULT_DARK,this,year,month,day);

//for three 
 DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(),
 AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,this,year,month,day);

// for four

   DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(),
 AlertDialog.THEME_HOLO_DARK,this,year,month,day);

//for five

 DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(),
     AlertDialog.THEME_HOLO_LIGHT,this,year,month,day);

//for six

 DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(),
 AlertDialog.THEME_TRADITIONAL,this,year,month,day);


     return datepickerdialog;
     }

     public void onDateSet(DatePicker view, int year, int month, int day){

     TextView textview = (TextView)getActivity().findViewById(R.id.textView1);

     textview.setText(day + ":" + (month+1) + ":" + year);

     }
     }

follow this it will give you all type date picker style(copy from this)

http://www.android-examples.com/change-datepickerdialog-theme-in-android-using-dialogfragment/

enter image description here

enter image description here

enter image description here

How to check if a string contains text from an array of substrings in JavaScript?

One line solution

substringsArray.some(substring=>yourBigString.includes(substring))

Returns true\false if substring exists\does'nt exist

Needs ES6 support

Processing $http response in service

I really don't like the fact that, because of the "promise" way of doing things, the consumer of the service that uses $http has to "know" about how to unpack the response.

I just want to call something and get the data out, similar to the old $scope.items = Data.getData(); way, which is now deprecated.

I tried for a while and didn't come up with a perfect solution, but here's my best shot (Plunker). It may be useful to someone.

app.factory('myService', function($http) {
  var _data;  // cache data rather than promise
  var myService = {};

  myService.getData = function(obj) { 
    if(!_data) {
      $http.get('test.json').then(function(result){
        _data = result.data;
        console.log(_data);  // prove that it executes once
        angular.extend(obj, _data);
      }); 
    } else {  
      angular.extend(obj, _data);
    }
  };

  return myService;
}); 

Then controller:

app.controller('MainCtrl', function( myService,$scope) {
  $scope.clearData = function() {
    $scope.data = Object.create(null);
  };
  $scope.getData = function() {
    $scope.clearData();  // also important: need to prepare input to getData as an object
    myService.getData($scope.data); // **important bit** pass in object you want to augment
  };
});

Flaws I can already spot are

  • You have to pass in the object which you want the data added to, which isn't an intuitive or common pattern in Angular
  • getData can only accept the obj parameter in the form of an object (although it could also accept an array), which won't be a problem for many applications, but it's a sore limitation
  • You have to prepare the input object $scope.data with = {} to make it an object (essentially what $scope.clearData() does above), or = [] for an array, or it won't work (we're already having to assume something about what data is coming). I tried to do this preparation step IN getData, but no luck.

Nevertheless, it provides a pattern which removes controller "promise unwrap" boilerplate, and might be useful in cases when you want to use certain data obtained from $http in more than one place while keeping it DRY.

How can I find the version of the Fedora I use?

The proposed standard file is /etc/os-release. See http://www.freedesktop.org/software/systemd/man/os-release.html

You can execute something like:

$ source /etc/os-release
$ echo $ID
fedora
$ echo $VERSION_ID
17
$ echo $VERSION
17 (Beefy Miracle)

How do you force a CIFS connection to unmount

I had this issue for a day until I found the real resolution. Instead of trying to force unmount an smb share that is hung, mount the share with the "soft" option. If a process attempts to connect to the share that is not available it will stop trying after a certain amount of time.

soft Make the mount soft. Fail file system calls after a number of seconds.

mount -t smbfs -o soft //username@server/share /users/username/smb/share

stat /users/username/smb/share/file
stat: /users/username/smb/share/file: stat: Operation timed out

May not be a real answer to your question but it is a solution to the problem

Check if a radio button is checked jquery

First of all, have only one id="test"

Secondly, try this:

if ($('[name="test"]').is(':checked'))

Java best way for string find and replace?

One possibility, reducing the longer form before expanding all:

string.replaceAll("Milan Vasic", "Milan").replaceAll("Milan", "Milan Vasic")

Another way, treating Vasic as optional:

string.replaceAll("Milan( Vasic)?", "Milan Vasic")

Others have described solutions based on lookahead or alternation.

How to make exe files from a node.js app?

I did find any of these solutions met my requirements, so made my own version of node called node2exe that does this. It's available from https://github.com/areve/node2exe

Loop through each cell in a range of cells when given a Range object

You could use Range.Rows, Range.Columns or Range.Cells. Each of these collections contain Range objects.

Here's how you could modify Dick's example so as to work with Rows:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Rows
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

And Columns:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCol In rRng.Columns
        For Each rCell In rCol.Rows
            Debug.Print rCell.Address, rCell.Value
        Next rCell
    Next rCol

End Sub

Why is super.super.method(); not allowed in Java?

If you think you are going to be needing the superclass, you could reference it in a variable for that class. For example:

public class Foo
{
  public int getNumber()
  {
    return 0;
  }
}

public class SuperFoo extends Foo
{
  public static Foo superClass = new Foo();
  public int getNumber()
  {
    return 1;
  }
}

public class UltraFoo extends Foo
{
  public static void main(String[] args)
  {
    System.out.println(new UltraFoo.getNumber());
    System.out.println(new SuperFoo().getNumber());
    System.out.println(new SuperFoo().superClass.getNumber());
  }
  public int getNumber()
  {
    return 2;
  }
}

Should print out:

2
1
0

Defining an abstract class without any abstract methods

Yes, you can define an abstract class without an abstract method. However, if there is no method inside you might better go with an interface

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

You do not need to keep the system images unless you want to use the emulator on your desktop. Along with it you can remove other unwanted stuff to clear disk space.

Adding as an answer to my own question as I've had to narrate this to people in my team more than a few times. Hence this answer as a reference to share with other curious ones.

In the last few weeks there were several colleagues who asked me how to safely get rid of the unwanted stuff to release disk space (most of them were beginners). I redirected them to this question but they came back to me for steps. So for android beginners here is a step by step guide to safely remove unwanted stuff.

Note

  • Do not blindly delete everything directly from disk that you "think" is not required occupying. I did that once and had to re-download.
  • Make sure you have a list of all active projects with the kind of emulators (if any) and API Levels and Build tools required for those to continue working/compiling properly.

First, be sure you are not going to use emulators and will always do you development on a physical device. In case you are going to need emulators, note down the API Levels and type of emulators you'll need. Do not remove those. For the rest follow the below steps:

Steps to safely clear up unwanted stuff from Android SDK folder on the disk

  1. Open the Stand Alone Android SDK Manager. To open do one of the following:
  • Click the SDK Manager button on toolbar in android studio or eclipse
  • In Android Studio, go to settings and search "Android SDK". Click Android SDK -> "Open Standalone SDK Manager"
  • In Eclipse, open the "Window" menu and select "Android SDK Manager"
  • Navigate to the location of the android-sdk directory on your computer and run "SDK Manager.exe"

.

  1. Uncheck all items ending with "System Image". Each API Level will have more than a few. In case you need some and have figured the list already leave them checked to avoid losing them and having to re-download.

.

  1. Optional (may help save a marginally more amount of disk space): To free up some more space, you can also entirely uncheck unrequired API levels. Be careful again to avoid re-downloading something you are actually using in other projects.

.

  1. In the end make sure you have at least the following (check image below) for the remaining API levels to be able to seamlessly work with your physical device.

In the end the clean android sdk installed components should look something like this in the SDK manager.

enter image description here

how to calculate binary search complexity

Here is the solution using the master theorem, with readable LaTeX.

For each recurrence in the recurrence relation for binary search, we convert the problem into one subproblem, with runtime T(N/2). Therefore:

T(n) = T(n/2)+1

Substituting into the master theorem, we get:

T(n) = aT(n/b) + f(n)

Now, because logba is 0 and f(n) is 1, we can use the second case of the master theorem because:

f(n) = O(1) = O(n0) = O(nlogba)

This means that:

T(n)=O(nlogbalogn) = O(n0logn) = O(logn)

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

Make virtualenv inherit specific packages from your global site-packages

You can use the --system-site-packages and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

Minimal example

And just to make what Mizux said as a minimal example:

main_c.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

main_cpp.cpp

#include <iostream>

int main(void) {
    std::cout << "hello" << std::endl;
}

Then, without any Makefile:

make CFLAGS='-g -O3' \
     CXXFLAGS='-ggdb3 -O0' \
     CPPFLAGS='-DX=1 -DY=2' \
     CCFLAGS='--asdf' \
     main_c \
     main_cpp

runs:

cc -g -O3 -DX=1 -DY=2   main_c.c   -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2   main_cpp.cpp   -o main_cpp

So we understand that:

  • make had implicit rules to make main_c and main_cpp from main_c.c and main_cpp.cpp
  • CFLAGS and CPPFLAGS were used as part of the implicit rule for .c compilation
  • CXXFLAGS and CPPFLAGS were used as part of the implicit rule for .cpp compilation
  • CCFLAGS is not used

Those variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:

main_c: main_c.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<

main_cpp: main_c.c
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

to achieve a similar affect to the implicit rules.

We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.

Tested in Ubuntu 16.04, GNU Make 4.1.

How do I redirect users after submit button click?

use

window.location.replace("login.php");

or simply window.location("login.php");

It is better than using window.location.href =, because replace() does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

Simple state machine example in C#?

FiniteStateMachine is a Simple State Machine, written in C# Link

Advantages tu use my library FiniteStateMachine:

  1. Define a "context" class to present a single interface to the outside world.
  2. Define a State abstract base class.
  3. Represent the different "states" of the state machine as derived classes of the State base class.
  4. Define state-specific behavior in the appropriate State derived classes.
  5. Maintain a pointer to the current "state" in the "context" class.
  6. To change the state of the state machine, change the current "state" pointer.

Download DLL Download

Example on LINQPad:

void Main()
{
            var machine = new SFM.Machine(new StatePaused());
            var output = machine.Command("Input_Start", Command.Start);
            Console.WriteLine(Command.Start.ToString() + "->  State: " + machine.Current);
            Console.WriteLine(output);

            output = machine.Command("Input_Pause", Command.Pause);
            Console.WriteLine(Command.Pause.ToString() + "->  State: " + machine.Current);
            Console.WriteLine(output);
            Console.WriteLine("-------------------------------------------------");
}
    public enum Command
    {
        Start,
        Pause,
    }

    public class StateActive : SFM.State
    {

        public override void Handle(SFM.IContext context)

        {
            //Gestione parametri
            var input = (String)context.Input;
            context.Output = input;

            //Gestione Navigazione
            if ((Command)context.Command == Command.Pause) context.Next = new StatePaused();
            if ((Command)context.Command == Command.Start) context.Next = this;

        }
    }


public class StatePaused : SFM.State
{

     public override void Handle(SFM.IContext context)

     {

         //Gestione parametri
         var input = (String)context.Input;
         context.Output = input;

         //Gestione Navigazione
         if ((Command)context.Command == Command.Start) context.Next = new  StateActive();
         if ((Command)context.Command == Command.Pause) context.Next = this;


     }

 }

REST API Best practice: How to accept list of parameter values as input

A Step Back

First and foremost, REST describes a URI as a universally unique ID. Far too many people get caught up on the structure of URIs and which URIs are more "restful" than others. This argument is as ludicrous as saying naming someone "Bob" is better than naming him "Joe" – both names get the job of "identifying a person" done. A URI is nothing more than a universally unique name.

So in REST's eyes arguing about whether ?id=["101404","7267261"] is more restful than ?id=101404,7267261 or \Product\101404,7267261 is somewhat futile.

Now, having said that, many times how URIs are constructed can usually serve as a good indicator for other issues in a RESTful service. There are a couple of red flags in your URIs and question in general.

Suggestions

  1. Multiple URIs for the same resource and Content-Location

    We may want to accept both styles but does that flexibility actually cause more confusion and head aches (maintainability, documentation, etc.)?

    URIs identify resources. Each resource should have one canonical URI. This does not mean that you can't have two URIs point to the same resource but there are well defined ways to go about doing it. If you do decide to use both the JSON and list based formats (or any other format) you need to decide which of these formats is the main canonical URI. All responses to other URIs that point to the same "resource" should include the Content-Location header.

    Sticking with the name analogy, having multiple URIs is like having nicknames for people. It is perfectly acceptable and often times quite handy, however if I'm using a nickname I still probably want to know their full name – the "official" way to refer to that person. This way when someone mentions someone by their full name, "Nichloas Telsa", I know they are talking about the same person I refer to as "Nick".

  2. "Search" in your URI

    A more complex case is when we want to offer more complex inputs. For example, if we want to allow multiple filters on search...

    A general rule of thumb of mine is, if your URI contains a verb, it may be an indication that something is off. URI's identify a resource, however they should not indicate what we're doing to that resource. That's the job of HTTP or in restful terms, our "uniform interface".

    To beat the name analogy dead, using a verb in a URI is like changing someone's name when you want to interact with them. If I'm interacting with Bob, Bob's name doesn't become "BobHi" when I want to say Hi to him. Similarly, when we want to "search" Products, our URI structure shouldn't change from "/Product/..." to "/Search/...".

Answering Your Initial Question

  1. Regarding ["101404","7267261"] vs 101404,7267261: My suggestion here is to avoid the JSON syntax for simplicity's sake (i.e. don't require your users do URL encoding when you don't really have to). It will make your API a tad more usable. Better yet, as others have recommended, go with the standard application/x-www-form-urlencoded format as it will probably be most familiar to your end users (e.g. ?id[]=101404&id[]=7267261). It may not be "pretty", but Pretty URIs does not necessary mean Usable URIs. However, to reiterate my initial point though, ultimately when speaking about REST, it doesn't matter. Don't dwell too heavily on it.

  2. Your complex search URI example can be solved in very much the same way as your product example. I would recommend going the application/x-www-form-urlencoded format again as it is already a standard that many are familiar with. Also, I would recommend merging the two.

Your URI...

/Search?term=pumas&filters={"productType":["Clothing","Bags"],"color":["Black","Red"]}    

Your URI after being URI encoded...

/Search?term=pumas&filters=%7B%22productType%22%3A%5B%22Clothing%22%2C%22Bags%22%5D%2C%22color%22%3A%5B%22Black%22%2C%22Red%22%5D%7D

Can be transformed to...

/Product?term=pumas&productType[]=Clothing&productType[]=Bags&color[]=Black&color[]=Red

Aside from avoiding the requirement of URL encoding and making things look a bit more standard, it now homogenizes the API a bit. The user knows that if they want to retrieve a Product or List of Products (both are considered a single "resource" in RESTful terms), they are interested in /Product/... URIs.

How can I search sub-folders using glob.glob module?

You can use Formic with Python 2.6

import formic
fileset = formic.FileSet(include="**/*.txt", directory="C:/Users/sam/Desktop/")

Disclosure - I am the author of this package.

How to set a maximum execution time for a mysql query?

You can find the answer on this other S.O. question:

MySQL - can I limit the maximum time allowed for a query to run?

a cron job that runs every second on your database server, connecting and doing something like this:

  • SHOW PROCESSLIST
  • Find all connections with a query time larger than your maximum desired time
  • Run KILL [process id] for each of those processes

Axios get access to response header fields

In case you're using Laravel 8 for the back-end side with CORS properly configured, add this line to config/cors.php:

'exposed_headers' => ['Authorization'],

SQL update from one Table to another based on a ID match

update within the same table:

  DECLARE @TB1 TABLE
    (
        No Int
        ,Name NVarchar(50)
        ,linkNo int
    )

    DECLARE @TB2 TABLE
    (
        No Int
        ,Name NVarchar(50)
        ,linkNo int
    )

    INSERT INTO @TB1 VALUES(1,'changed person data',  0);
    INSERT INTO @TB1 VALUES(2,'old linked data of person', 1);

INSERT INTO @TB2 SELECT * FROM @TB1 WHERE linkNo = 0


SELECT * FROM @TB1
SELECT * FROM @TB2


    UPDATE @TB1 
        SET Name = T2.Name
    FROM        @TB1 T1
    INNER JOIN  @TB2 T2 ON T2.No = T1.linkNo

    SELECT * FROM @TB1

Is there any way I can define a variable in LaTeX?

For variables describing distances, you would use \newlength (and manipulate the values with \setlength, \addlength, \settoheight, \settolength and \settodepth).

Similarly you have access to \newcounter for things like section and figure numbers which should increment throughout the document. I've used this one in the past to provide code samples that were numbered separatly of other figures...

Also of note is \makebox which allows you to store a bit of laid-out document for later re-use (and for use with \settolength...).

Prevent wrapping of span or div

Particularly when using something like Twitter's Bootstrap, white-space: nowrap; doesn't always work in CSS when applying padding or margin to a child div. Instead however, adding an equivalent border: 20px solid transparent; style in place of padding/margin works more consistently.

how to write procedure to insert data in to the table in phpmyadmin?

# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12

(IN numRating_Chapter INT(11) UNSIGNED, 

 IN txtRating_Chapter VARCHAR(250),

 IN chapterName VARCHAR(250),

 IN addedBy VARCHAR(250)

)

BEGIN
DECLARE numRating_Chapter INT;

DECLARE txtRating_Chapter VARCHAR(250);

DECLARE chapterName1 VARCHAR(250);

DECLARE addedBy1 VARCHAR(250);

DECLARE chapterId INT;

DECLARE studentId INT;

SET chapterName1 = chapterName;
SET addedBy1 = addedBy;

SET chapterId = (SELECT chapterId 
                   FROM chapters 
                   WHERE chaptername = chapterName1);

SET studentId = (SELECT Id 
                   FROM students 
                   WHERE email = addedBy1);

SELECT chapterId;
SELECT studentId;

INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);

END //

//DELIMITER;

How do I use Linq to obtain a unique list of properties from a list of objects?

Using straight Linq, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

Try the following:

var myToolBar = UIToolbar.init(frame: CGRect.init(x: 0, y: 0, width: 320, height: 44))

This is for the swift's latest version

Transposing a 2D-array in JavaScript

function invertArray(array,arrayWidth,arrayHeight) {
  var newArray = [];
  for (x=0;x<arrayWidth;x++) {
    newArray[x] = [];
    for (y=0;y<arrayHeight;y++) {
        newArray[x][y] = array[y][x];
    }
  }
  return newArray;
}

How to stop default link click behavior with jQuery

e.preventDefault();

from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Cancels the event if it is cancelable, without stopping further propagation of the event.

PHP, get file name without file extension

Another approach is by using regular expressions.

$fileName = basename($filePath);
$fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $fileName);

This removes from the last period . up until the end of the string.

Simple (non-secure) hash function for JavaScript?

Check out these implementations

Transpose/Unzip Function (inverse of zip)?

You could also do

result = ([ a for a,b in original ], [ b for a,b in original ])

It should scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.

(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like zip does.)

If generators instead of actual lists are ok, this would do that:

result = (( a for a,b in original ), ( b for a,b in original ))

The generators don't munch through the list until you ask for each element, but on the other hand, they do keep references to the original list.

Dealing with HTTP content in HTTPS pages

If you're looking for a quick solution to load images over HTTPS then the free reverse proxy service at https://images.weserv.nl/ may interest you. It was exactly what I was looking for.

If you're looking for a paid solution, I have previously used Cloudinary.com which also works well but is too expensive solely for this task, in my opinion.

Static array vs. dynamic array in C++

Local arrays are created on the stack, and have automatic storage duration -- you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size:

int foo[10];

Arrays created with operator new[] have dynamic storage duration and are stored on the heap (technically the "free store"). They can have any size, but you need to allocate and free them yourself since they're not part of the stack frame:

int* foo = new int[10];
delete[] foo;

endsWith in JavaScript

After all those long tally of answers, i found this piece of code simple and easy to understand!

function end(str, target) {
  return str.substr(-target.length) == target;
}

How to detect Safari, Chrome, IE, Firefox and Opera browser?

You can try following way to check Browser version.

    <!DOCTYPE html>
    <html>
    <body>
    <p>What is the name(s) of your browser?</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>
    <script>

    function myFunction() { 
     if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) 
    {
        alert('Opera');
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1 )
    {
        alert('Chrome');
    }
    else if(navigator.userAgent.indexOf("Safari") != -1)
    {
        alert('Safari');
    }
    else if(navigator.userAgent.indexOf("Firefox") != -1 ) 
    {
         alert('Firefox');
    }
    else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
    {
      alert('IE'); 
    }  
    else 
    {
       alert('unknown');
    }
    }
    </script>

    </body>
    </html>

And if you need to know only IE Browser version then you can follow below code. This code works well for version IE6 to IE11

<!DOCTYPE html>
<html>
<body>

<p>Click on Try button to check IE Browser version.</p>

<button onclick="getInternetExplorerVersion()">Try it</button>

<p id="demo"></p>

<script>
function getInternetExplorerVersion() {
   var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var rv = -1;

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer, return version number
        {               

            if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
                //For IE 11 >
                if (navigator.appName == 'Netscape') {
                    var ua = navigator.userAgent;
                    var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
                    if (re.exec(ua) != null) {
                        rv = parseFloat(RegExp.$1);
                        alert(rv);
                    }
                }
                else {
                    alert('otherbrowser');
                }
            }
            else {
                //For < IE11
                alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
            }
            return false;
        }}
</script>

</body>
</html>

Using variables inside strings

Use the following methods

1: Method one

var count = 123;
var message = $"Rows count is: {count}";

2: Method two

var count = 123;
var message = "Rows count is:" + count;

3: Method three

var count = 123;
var message = string.Format("Rows count is:{0}", count);

4: Method four

var count = 123;
var message = @"Rows
                count
                is:{0}" + count;

5: Method five

var count = 123;
var message = $@"Rows 
                 count 
                 is: {count}";

Oracle comparing timestamp with date

to_date format worked for me. Please consider the date formats: MON-, MM, ., -.

t.start_date >= to_date('14.11.2016 04:01:39', 'DD.MM.YYYY HH24:MI:SS')
t.start_date <=to_date('14.11.2016 04:10:07', 'DD.MM.YYYY HH24:MI:SS')

Parallel foreach with asynchronous lambda

The following is set to work with IAsyncEnumerable but can be modified to use IEnumerable by just changing the type and removing the "await" on the foreach. It's far more appropriate for large sets of data than creating countless parallel tasks and then awaiting them all.

    public static async Task ForEachAsyncConcurrent<T>(this IAsyncEnumerable<T> enumerable, Func<T, Task> action, int maxDegreeOfParallelism, int? boundedCapacity = null)
    {
        ActionBlock<T> block = new ActionBlock<T>(
           action, 
           new ExecutionDataflowBlockOptions 
           { 
             MaxDegreeOfParallelism = maxDegreeOfParallelism, 
             BoundedCapacity = boundedCapacity ?? maxDegreeOfParallelism * 3 
           });

        await foreach (T item in enumerable)
        {
           await block.SendAsync(item).ConfigureAwait(false);
        }

        block.Complete();
        await block.Completion;
    }

What is the official "preferred" way to install pip and virtualenv systemwide?

On Ubuntu 12.04 I've had good luck just using the package manager:

sudo apt-get install python-pip virtualenvwrapper

JavaScript/jQuery - "$ is not defined- $function()" error

if you are trying to use jquery in your electron app before adding jquery you should add it to your modules:

<script>
    if (typeof module === 'object') {
        window.module = module;
        module = undefined;
    }
</script>
<script src="js/jquery-3.5.1.min.js"></script>

How can I remove a trailing newline?

Just use :

line = line.rstrip("\n")

or

line = line.strip("\n")

You don't need any of this complicated stuff

mappedBy reference an unknown target entity property

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "USER_ID")
    Long userId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> receiver;
}

public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id

    @Column(name = "NOTIFICATION_ID")
    Long notificationId;

    @Column(name = "TEXT")
    String text;

    @Column(name = "ALERT_STATUS")
    @Enumerated(EnumType.STRING)
    AlertStatus alertStatus = AlertStatus.NEW;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SENDER_ID")
    @JsonIgnore
    User sender;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "RECEIVER_ID")
    @JsonIgnore
    User receiver;
}

What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..

User model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
    List<Notification> receiver;

Notification model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> **sender**;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> **receiver**;

I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.

OpenSSL: unable to verify the first certificate for Experian URL

Here is what you can do:-

Exim SSL certificates

By default, the /etc/exim.conf will use the cert/key files:

/etc/exim.cert
/etc/exim.key

so if you're wondering where to set your files, that's where.

They're controlled by the exim.conf's options:

tls_certificate = /etc/exim.cert
tls_privatekey = /etc/exim.key

Intermediate Certificates

If you have a CA Root certificate (ca bundle, chain, etc.) you'll add the contents of your CA into the exim.cert, after your actual certificate.

Probably a good idea to make sure you have a copy of everything elsewhere in case you make an error.

Dovecot and ProFtpd should also read it correctly, so dovecot no longer needs the ssl_ca option. So for both cases, there is no need to make any changes to either the exim.conf or dovecot.conf(/etc/dovecot/conf/ssl.conf)

How to add item to the beginning of List<T>?

Use List<T>.Insert

While not relevant to your specific example, if performance is important also consider using LinkedList<T> because inserting an item to the start of a List<T> requires all items to be moved over. See When should I use a List vs a LinkedList.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

The problem is because of post back happens on submit button click. So while posting data on submit click again write before returning View()

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");

How to set gradle home while importing existing project in Android studio

For OSX, if going to Finder, navigate to this category: /usr/local/opt/ if you do not see gradle folder, install your grandle version manually:

https://services.gradle.org/distributions/gradle-5.4.1-all.zip

https://services.gradle.org/distributions/gradle-4.4.1-all.zip

If you are looking for specific Gradle version, simply change the version number from the zip links above, unzip and add that in the Gradle folder /usr/local/opt/gradle

How to print Two-Dimensional Array like table

If you don't mind the commas and the brackets you can simply use:

System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));

How to get info on sent PHP curl request

curl_getinfo() must be added before closing the curl handler

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
curl_close($ch);

Test if a command outputs an empty string

if [ -z "$(ls -lA)" ]; then
  echo "no files found"
else
  echo "There are files"
fi

This will run the command and check whether the returned output (string) has a zero length. You might want to check the 'test' manual pages for other flags.

Use the "" around the argument that is being checked, otherwise empty results will result in a syntax error as there is no second argument (to check) given!

Note: that ls -la always returns . and .. so using that will not work, see ls manual pages. Furthermore, while this might seem convenient and easy, I suppose it will break easily. Writing a small script/application that returns 0 or 1 depending on the result is much more reliable!

How to get the indices list of all NaN value in numpy array?

np.isnan combined with np.argwhere

x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
np.argwhere(np.isnan(x))

output:

array([[1, 2],
       [2, 0]])

Is there a "previous sibling" selector?

I had this same problem, while I was trying to change prepend icon fill color on input focus, my code looked something like this:

<template #append>
    <b-input-group-text><strong class="text-danger">!</strong></b-input-group-text>
</template>
<b-form-input id="password_confirmation" v-model="form.password_confirmation" type="password" placeholder="Repeat password" autocomplete="new-password" />

The problem was that I'm using a vue-bootstrap slot to inject the prepend, so even if i change the location still get rendered after the input

Well my solution was to swipe their location, and add custom prepend and used ~ symbol, as css doesn't support previous sibling.

<div class="form-input-prepend">
    <svg-vue icon="common.lock" />
</div>
<b-form-input id="password_confirmation" v-model="form.password_confirmation" type="password" placeholder="Repeat password" autocomplete="new-password" />

Scss style

.form-control:focus ~ .form-input-prepend {
    svg path {
        fill: $accent;
    }
}

So just try to change its position, and if necessary use css order or position: absolute; to achieve what you want, and to avoid using javascript for this kind of needs.

What HTTP status response code should I use if the request is missing a required parameter?

It could be argued that a 404 Not Found should be used since the resource specified could not be found.

Method to Add new or update existing item in Dictionary

I know it is not Dictionary<TKey, TValue> class, however you can avoid KeyNotFoundException while incrementing a value like:

dictionary[key]++; // throws `KeyNotFoundException` if there is no such key  

by using ConcurrentDictionary<TKey, TValue> and its really nice method AddOrUpdate()..

Let me show an example:

var str = "Hellooo!!!";
var characters = new ConcurrentDictionary<char, int>();
foreach (var ch in str)
    characters.AddOrUpdate(ch, 1, (k, v) => v + 1);

SQL Server - How to lock a table until a stored procedure finishes

BEGIN TRANSACTION

select top 1 *
from table1
with (tablock, holdlock)

-- You do lots of things here

COMMIT

This will hold the 'table lock' until the end of your current "transaction".

Lazy Method for Reading Big File in Python?

I think we can write like this:

def read_file(path, block_size=1024): 
    with open(path, 'rb') as f: 
        while True: 
            piece = f.read(block_size) 
            if piece: 
                yield piece 
            else: 
                return

for piece in read_file(path):
    process_piece(piece)

How to create strings containing double quotes in Excel formulas?

In the event that you need to do this with JSON:

=CONCATENATE("'{""service"": { ""field"": "&A2&"}}'")

This version of the application is not configured for billing through Google Play

Recently google has implemented a change on their systems, and since you have uploaded at least one APK to your console, you can test your in-app requests with your app with any version code / number.

Cross reference LINK

Configure gradle to sign your debug build for debugging.

android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("my-release-key.jks")
            storePassword "password"
            keyAlias "my-alias"
            keyPassword "password"
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.release
            ...
        }
    }
}

Date validation with ASP.NET validator

I think the following is the easiest way to do it.

<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>

Convert generic List/Enumerable to DataTable?

This is the simple Console Application to convert List to Datatable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;

namespace ConvertListToDataTable
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            List<MyObject> list = new List<MyObject>();
            for (int i = 0; i < 5; i++)
            {
                list.Add(new MyObject { Sno = i, Name = i.ToString() + "-KarthiK", Dat = DateTime.Now.AddSeconds(i) });
            }

            DataTable dt = ConvertListToDataTable(list);
            foreach (DataRow row in dt.Rows)
            {
                Console.WriteLine();
                for (int x = 0; x < dt.Columns.Count; x++)
                {
                    Console.Write(row[x].ToString() + " ");
                }
            }
            Console.ReadLine();
        }

        public class MyObject
        {
            public int Sno { get; set; }
            public string Name { get; set; }
            public DateTime Dat { get; set; }
        }

        public static DataTable ConvertListToDataTable<T>(this List<T> iList)
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = props[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);

                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[props.Count];
            foreach (T iListItem in iList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(iListItem);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }
    }
}

How to POST request using RestSharp

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

How to create a Restful web service with input parameters?

If you want query parameters, you use @QueryParam.

public Todo getXML(@QueryParam("summary") String x, 
                   @QueryParam("description") String y)

But you won't be able to send a PUT from a plain web browser (today). If you type in the URL directly, it will be a GET.

Philosophically, this looks like it should be a POST, though. In REST, you typically either POST to a common resource, /todo, where that resource creates and returns a new resource, or you PUT to a specifically-identified resource, like /todo/<id>, for creation and/or update.

In Android EditText, how to force writing uppercase?

Simple kotlin realization

fun EditText.onlyUppercase() {
    inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
    filters = arrayOf(InputFilter.AllCaps())
}

PS it seems that filters is always empty initially

Java - creating a new thread

Please try this. You will understand all perfectly after you will take a look on my solution.

There are only 2 ways of creating threads in java

with implements Runnable

class One implements Runnable {
@Override
public void run() {
    System.out.println("Running thread 1 ... ");
}

with extends Thread

class Two extends Thread {
@Override
public void run() {
    System.out.println("Running thread 2 ... ");
}

Your MAIN class here

public class ExampleMain {
public static void main(String[] args) {

    One demo1 = new One();
    Thread t1 = new Thread(demo1);
    t1.start();

    Two demo2 = new Two();
    Thread t2 = new Thread(demo2);
    t2.start();
}

}

How to hide a status bar in iOS?

You need to add this code in your AppDelegate file, not in your Root View Controller

Or add the property Status bar is initially hidden in your plist file

enter image description here

Folks, in iOS 7+

please add this to your info.plist file, It will make the difference :)

UIStatusBarHidden UIViewControllerBasedStatusBarAppearance

enter image description here

For iOS 11.4+ and Xcode 9.4 +

Use this code either in one or all your view controllers

override var prefersStatusBarHidden: Bool { return true }

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.

To make Python 2 code work in Python 3:

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2

jQuery - Illegal invocation

I think you need to have strings as the data values. It's likely something internally within jQuery that isn't encoding/serializing correctly the To & From Objects.

Try:

var data = {
    from : from.val(),
    to : to.val(),
    speed : speed
};

Notice also on the lines:

$(from).css(...
$(to).css(

You don't need the jQuery wrapper as To & From are already jQuery objects.

Is it possible to put CSS @media rules inline?

No, @media rules and media queries cannot exist in inline style attributes as they can only contain property: value declarations. As the spec puts it:

The value of the style attribute must match the syntax of the contents of a CSS declaration block

The only way to apply styles to an element only in certain media is with a separate rule in your stylesheet, which means you'll need to come up with a selector for it.

A dummy span selector would look like this, but if you're targeting a very specific element you will need a more specific selector:

span { background-image: url(particular_ad.png); }

@media (max-width: 300px) {
    span { background-image: url(particular_ad_small.png); }
}

How do I search for names with apostrophe in SQL Server?

select * from Header where userID like '%''%'

Hope this helps.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.

For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>

Show week number with Javascript?

All the proposed approaches may give wrong results because they don’t take into account summer/winter time changes. Rather than calculating the number of days between two dates using the constant of 86’400’000 milliseconds, it is better to use an approach like the following one:

getDaysDiff = function (dateObject0, dateObject1) {
    if (dateObject0 >= dateObject1) return 0;
    var d = new Date(dateObject0.getTime());
    var nd = 0;
    while (d <= dateObject1) {
        d.setDate(d.getDate() + 1);
        nd++;
    }
    return nd-1;
};

Smooth GPS data

I usually use the accelerometers. A sudden change of position in a short period implies high acceleration. If this is not reflected in accelerometer telemetry it is almost certainly due to a change in the "best three" satellites used to compute position (to which I refer as GPS teleporting).

When an asset is at rest and hopping about due to GPS teleporting, if you progressively compute the centroid you are effectively intersecting a larger and larger set of shells, improving precision.

To do this when the asset is not at rest you must estimate its likely next position and orientation based on speed, heading and linear and rotational (if you have gyros) acceleration data. This is more or less what the famous K filter does. You can get the whole thing in hardware for about $150 on an AHRS containing everything but the GPS module, and with a jack to connect one. It has its own CPU and Kalman filtering on board; the results are stable and quite good. Inertial guidance is highly resistant to jitter but drifts with time. GPS is prone to jitter but does not drift with time, they were practically made to compensate each other.

getResourceAsStream() is always returning null

I had a similar problem and I searched for the solution for quite a while: It appears that the string parameter is case sensitive. So if your filename is abc.TXT but you search for abc.txt, eclipse will find it - the executable JAR file won't.

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

This can also happen if you are attempting to connect over HTTPS and the server is not configured to handle SSL connections correctly.

I would check your application servers SSL settings and make sure that the certification is configured correctly.

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Create AMI -> Boot AMI on large instance.

More info http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/creating-an-image.html

You can do this all from the admin console too at aws.amazon.com

Trying to load local JSON file to show data in a html page using JQuery

app.js

$("button").click( function() {
 $.getJSON( "article.json", function(obj) {
  $.each(obj, function(key, value) {
         $("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
  });
 });
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Tax Calulator</title>
    <script src="jquery-3.2.0.min.js" type="text/javascript"></script>
  </head>
  <body>
    <ul></ul>
    <button>Users</button>
<script type="text/javascript" src="app.js"></script>
  </body>
</html>

article.json

{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}

server.js

var http = require('http');
var fs = require('fs');

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/') {
          response.writeHead(200,{"Content-Type":"text/html"});
          fs.createReadStream("./index.html").pipe(response);
  } else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
          response.writeHead(200,{"Content-Type":"text/javascript"});
          fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
  } else if(request.method == 'GET' && request.url == '/app.js') {
          response.writeHead(200,{"Content-Type":"text/javascript"});
          fs.createReadStream("./app.js").pipe(response);
  }
  else if(request.method == 'GET' && request.url == '/article.json') {
          response.writeHead(200,{"Content-Type":"text/json"});
          fs.createReadStream("./article.json").pipe(response);
  }
}

http.createServer(onRequest).listen(2341);
console.log("Server is running ....");

Server.js will run a simple node http server in your local to process the data.

Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html

This is my running one https://github.com/surya4/jquery-json.

Django: Display Choice Value

For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

In Views

person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()

In Template

{{ person.get_gender_display }}

Documentation of get_FOO_display()

Laravel 5 Application Key

For me the problem was in that I had not yet ran composer update for this new project/fork. The command failed silently, nothing happened.

After running composer update it worked.

org.hibernate.PersistentObjectException: detached entity passed to persist

You didn't provide many relevant details so I will guess that you called getInvoice and then you used result object to set some values and call save with assumption that your object changes will be saved.

However, persist operation is intended for brand new transient objects and it fails if id is already assigned. In your case you probably want to call saveOrUpdate instead of persist.

You can find some discussion and references here "detached entity passed to persist error" with JPA/EJB code