Programs & Examples On #Value restriction

In functional programming, in particular the ML programming language family, the value restriction means that declarations are only polymorphically generalized if they are syntactic values (also called non-expansive).

How to ensure that there is a delay before a service is started in systemd?

The systemd way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|

You might be able to do something inline like

ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'

or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here in an ExecStartPost

Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.

(May want to increase TimeoutStartSec from the default 90s as well)

How do you get a directory listing sorted by creation date in python?

Turns out os.listdir sorts by last modified but in reverse so you can do:

import os
last_modified=os.listdir()[::-1]

How to make an executable JAR file?

A jar file is simply a file containing a collection of java files. To make a jar file executable, you need to specify where the main Class is in the jar file. Example code would be as follows.

public class JarExample {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // your logic here
            }
        });
    }
}

Compile your classes. To make a jar, you also need to create a Manifest File (MANIFEST.MF). For example,

Manifest-Version: 1.0
Main-Class: JarExample

Place the compiled output class files (JarExample.class,JarExample$1.class) and the manifest file in the same folder. In the command prompt, go to the folder where your files placed, and create the jar using jar command. For example (if you name your manifest file as jexample.mf)

jar cfm jarexample.jar jexample.mf *.class

It will create executable jarexample.jar.

How to open/run .jar file (double-click not working)?

There are two different types of Java to download: The JDK, which is used to write Java programs, and the RE (runtime environment), which is used to actually run Java programs. Are you sure that you installed the RE instead of the SDK?

How to unmount a busy device

Niche Answer:

If you have a zfs pool on that device, at least when it's a file-based pool, lsof will not show the usage. But you can simply run

sudo zpool export mypoo

and then unmount.

How to print out all the elements of a List in Java?

System.out.println(list);//toString() is easy and good enough for debugging.

toString() of AbstractCollection will be clean and easy enough to do that. AbstractList is a subclass of AbstractCollection, so no need to for loop and no toArray() needed.

Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

If you are using any custom object in your list, say Student , you need to override its toString() method(it is always good to override this method) to have a meaningful output

See the below example:

public class TestPrintElements {

    public static void main(String[] args) {

        //Element is String, Integer,or other primitive type
        List<String> sList = new ArrayList<String>();
        sList.add("string1");
        sList.add("string2");
        System.out.println(sList);

        //Element is custom type
        Student st1=new Student(15,"Tom");
        Student st2=new Student(16,"Kate");
        List<Student> stList=new ArrayList<Student>();
        stList.add(st1);
        stList.add(st2);
        System.out.println(stList);
   }
}


public  class Student{
    private int age;
    private String name;

    public Student(int age, String name){
        this.age=age;
        this.name=name;
    }

    @Override
    public String toString(){
        return "student "+name+", age:" +age;
    }
}

output:

[string1, string2]
[student Tom age:15, student Kate age:16]

How to convert List<string> to List<int>?

Using Linq ...

List<string> listofIDs = collection.AllKeys.ToList();  
List<int> myStringList = listofIDs.Select(s => int.Parse(s)).ToList();

How to restore the dump into your running mongodb

mongodump: To dump all the records:

mongodump --db databasename

To limit the amount of data included in the database dump, you can specify --db and --collection as options to mongodump. For example:

mongodump --collection myCollection --db test

This operation creates a dump of the collection named myCollection from the database 'test' in a dump/ subdirectory of the current working directory. NOTE: mongodump overwrites output files if they exist in the backup data folder.


mongorestore: To restore all data to the original database:

1) mongorestore --verbose \path\dump

or restore to a new database:

2) mongorestore --db databasename --verbose \path\dump\<dumpfolder>

Note: Both requires mongod instances.

Reading integers from binary file in Python

When you read from a binary file, a data type called bytes is used. This is a bit like list or tuple, except it can only store integers from 0 to 255.

Try:

file_size = fin.read(4)
file_size0 = file_size[0]
file_size1 = file_size[1]
file_size2 = file_size[2]
file_size3 = file_size[3]

Or:

file_size = list(fin.read(4))

Instead of:

file_size = int(fin.read(4))

How do you share code between projects/solutions in Visual Studio?

You can wild-card inline using the following technique (which is the way in which @Andomar's solution is saved in the .csproj)

<Compile Include="..\MySisterProject\**\*.cs">
  <Link>_Inlined\MySisterProject\%(RecursiveDir)%(Filename)%(Extension)</Link>
</Compile>

Put in:

    <Visible>false</Visible>

If you want to hide the files and/or prevent the wild-card include being expanded if you add or remove an item from a 'virtual existing item' folder like MySisterProject above.

How to populate HTML dropdown list with values from database

My guess is that you have a problem since you don't close your select-tag after the loop. Could that do the trick?

<select name="owner">
<?php 
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

What is the difference between <section> and <div>?

The section tag provides a more semantic syntax for html. div is a generic tag for a section. When you use section tag for appropriate content, it can be used for search engine optimization also. section tag also makes it easy for html parsing. for more info, refer. http://blog.whatwg.org/is-not-just-a-semantic

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

With Javascript you can use:

yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);

If by chance you're generating your web page with PHP you can also use:

<?=ucfirst($your_text)?>

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

What's the best way to iterate an Android Cursor?

The cursor is the Interface that represents a 2-dimensional table of any database.

When you try to retrieve some data using SELECT statement, then the database will 1st create a CURSOR object and return its reference to you.

The pointer of this returned reference is pointing to the 0th location which is otherwise called as before the first location of the Cursor, so when you want to retrieve data from the cursor, you have to 1st move to the 1st record so we have to use moveToFirst

When you invoke moveToFirst() method on the Cursor, it takes the cursor pointer to the 1st location. Now you can access the data present in the 1st record

The best way to look :

Cursor cursor

for (cursor.moveToFirst(); 
     !cursor.isAfterLast();  
     cursor.moveToNext()) {
                  .........
     }

Checking if a string is empty or null in Java

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.

Example:

System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).

Example:

System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

Difference between logger.info and logger.debug

It depends on which level you selected in your log4j configuration file.

<Loggers>
        <Root level="info">
        ...

If your level is "info" (by default), logger.debug(...) will not be printed in your console. However, if your level is "debug", it will.

Depending on the criticality level of your code, you should use the most accurate level among the following ones :

ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF

How can I make my layout scroll both horizontally and vertically?

I was able to find a simple way to achieve both scrolling behaviors.

Here is the xml for it:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:scrollbars="vertical">

    <HorizontalScrollView 
        android:layout_width="320px" android:layout_height="fill_parent">

        <TableLayout
            android:id="@+id/linlay" android:layout_width="320px"
            android:layout_height="fill_parent" android:stretchColumns="1"
            android:background="#000000"/>

    </HorizontalScrollView>

</ScrollView>

Select dropdown with fixed width cutting off content in IE

I wanted this to work with selects that I added dynamically to the page, so after a lot of experimentation, I ended up giving all the selects that I wanted to do this with the class "fixedwidth", and then added the following CSS:

table#System_table select.fixedwidth { width: 10em; }
table#System_table select.fixedwidth.clicked { width: auto; }

and this code

<!--[if lt IE 9]>
    <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery(document).on(
              {
                'mouseenter': function(event) {
                    jQuery(this).addClass('clicked');
                    },
                'focusout change blur': function() {
                    jQuery(this).removeClass('clicked');
                    }
              }, 'select.fixedwidth');
        });
    </script>
<![endif]-->

A couple of things to note:

  • In spite of the fact that my selects are all in a table, I had to do "on" to the jQuery(document).on instead of to jQuery('table#System_table').on
  • In spite of the fact that the jQuery documentation says to use "mouseleave" instead of "blur", I found that in IE7 when I moved the mouse down the drop down list, it would get a mouseleave event but not a blur.

How to add items to a spinner in Android?

Try this code:

final List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
list.add("Item 5");

final String[] str = {"Report 1", "Report 2", "Report 3", "Report 4", "Report 5"};

final Spinner sp1 = (Spinner) findViewById(R.id.spinner1);
final Spinner sp2 = (Spinner) findViewById(R.id.spinner2);

ArrayAdapter<String> adp1 = new ArrayAdapter<String>(this,
                              android.R.layout.simple_list_item_1, list);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adp1);

ArrayAdapter<String> adp2 = new ArrayAdapter<String>(this,
                                  android.R.layout.simple_spinner_item, str);
adp2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adp2);

sp1.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), list.get(position), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

sp2.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), str[position], Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

You can also add spinner item value through String array xml file..

<resources>
    <string name="app_name">Spinner_ex5</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string-array name="str2">
        <item>Data 1</item>
        <item>Data 2</item>
        <item>Data 3</item>
        <item>Data 4</item>
        <item>Data 5</item>
    </string-array>
</resources>

In mainActivity.java:

final Spinner sp3 = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter<CharSequence> adp3 = ArrayAdapter.createFromResource(this,
                                    R.array.str2, android.R.layout.simple_list_item_1);

adp3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adp3);
sp3.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            String ss = sp3.getSelectedItem().toString();
            Toast.makeText(getBaseContext(), ss, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

Looping from 1 to infinity in Python

def to_infinity():
    index = 0
    while True:
        yield index
        index += 1

for i in to_infinity():
    if i > 10:
        break

startForeground fail after upgrade to Android 8.1

Thanks to @CopsOnRoad, his solution was a big help but only works for SDK 26 and higher. My app targets 24 and higher.

To keep Android Studio from complaining you need a conditional directly around the notification. It is not smart enough to know the code is in a method conditional to VERSION_CODE.O.

@Override
public void onCreate(){
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        startMyOwnForeground();
    else
        startForeground(1, new Notification());
}

private void startMyOwnForeground(){

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){

        String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(AppSpecific.SMALL_ICON)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }
}

Mongoose.js: Find user by username LIKE value

Just complementing @PeterBechP 's answer.

Don't forget to scape the special chars. https://stackoverflow.com/a/6969486

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

var name = 'Peter+with+special+chars';

model.findOne({name: new RegExp('^'+escapeRegExp(name)+'$', "i")}, function(err, doc) {
  //Do your action here..
});

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

Loading an image to a <img> from <input file>

Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.

* (Update 4/22/2013: HTML does now support this, in HTML5. See the other answers.)

Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)

Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
               creationComplete="init()">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
    <mx:Image id="myImage" x="9" y="44"/>
    <fx:Script>
        <![CDATA[
            private var fr:FileReference = new FileReference();

            // Called when the app starts.
            private function init():void
            {
                // Set up event handlers.
                fr.addEventListener(Event.SELECT, onSelect);
                fr.addEventListener(Event.COMPLETE, onComplete);
            }

            // Called when the user clicks "Choose file..."
            private function showFilePicker():void
            {
                fr.browse();
            }

            // Called when fr.browse() dispatches Event.SELECT to indicate
            // that the user has picked a file.
            private function onSelect(e:Event):void
            {
                fr.load(); // start reading the file
            }

            // Called when fr.load() dispatches Event.COMPLETE to indicate
            // that the file has finished loading.
            private function onComplete(e:Event):void
            {
                myImage.data = fr.data; // load the file's data into the Image
            }
        ]]>
    </fx:Script>
</s:Application>

jQuery Datepicker close datepicker after selected date

Answer above did not work for me on Chrome. The change event was been fired after I clicked out of the field somewhere, which did not help because the datepicker window is also closed too when you click out of the field.

I did use this code and it worked pretty well. You can place it after calling .datepicker();

HTML

<input type="text" class="datepicker-input" placeholder="click to show datepicker" />

JavaScript

$(".datepicker-input").each(function() {
    $(this).datepicker();
});

$(".datepicker-input").click(function() {
    $(".datepicker-days .day").click(function() {
        $('.datepicker').hide();
    });
});

What is the difference between a strongly typed language and a statically typed language?

Strong typing probably means that variables have a well-defined type and that there are strict rules about combining variables of different types in expressions. For example, if A is an integer and B is a float, then the strict rule about A+B might be that A is cast to a float and the result returned as a float. If A is an integer and B is a string, then the strict rule might be that A+B is not valid.

Static typing probably means that types are assigned at compile time (or its equivalent for non-compiled languages) and cannot change during program execution.

Note that these classifications are not mutually exclusive, indeed I would expect them to occur together frequently. Many strongly-typed languages are also statically-typed.

And note that when I use the word 'probably' it is because there are no universally accepted definitions of these terms. As you will already have seen from the answers so far.

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

I had the same problem when I used code-first migrations to build my database for an MVC 5 application. I eventually found the seed method in my configuration.cs file to be causing the issue. My seed method was creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.

ASP.NET Core return JSON with status code

What I do in my Asp Net Core Api applications it is to create a class that extends from ObjectResult and provide many constructors to customize the content and the status code. Then all my Controller actions use one of the costructors as appropiate. You can take a look at my implementation at: https://github.com/melardev/AspNetCoreApiPaginatedCrud

and

https://github.com/melardev/ApiAspCoreEcommerce

here is how the class looks like(go to my repo for full code):

public class StatusCodeAndDtoWrapper : ObjectResult
{



    public StatusCodeAndDtoWrapper(AppResponse dto, int statusCode = 200) : base(dto)
    {
        StatusCode = statusCode;
    }

    private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, string message) : base(dto)
    {
        StatusCode = statusCode;
        if (dto.FullMessages == null)
            dto.FullMessages = new List<string>(1);
        dto.FullMessages.Add(message);
    }

    private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, ICollection<string> messages) : base(dto)
    {
        StatusCode = statusCode;
        dto.FullMessages = messages;
    }
}

Notice the base(dto) you replace dto by your object and you should be good to go.

Merging two images with PHP

Use the GD library or ImageMagick. I googled 'PHP GD merge images' and got several articles on doing this. In the past what I've done is create a large blank image, and then used imagecopymerge() to paste those images into my original blank one. Check out the articles on google you'll find some source code you can start using right away.

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

Off the cuff, it feels like your project is connected to an older version of the Play Services library project. The recommended approach, by Google, is for you to find the library project in the SDK and make a local copy. This does mean, though, that any time you update the Play Services library project through the SDK Manager, you also need to replace your copy with a fresh copy.

How to permanently set $PATH on Linux/Unix?

For debian distribution, you have to:

  • edit ~/.bashrc e.g: vim ~/.bashrc
  • add export PATH=$PATH:/path/to/dir
  • then restart your computer. Be aware that if you edit ~/.bashrc as root, your environment variable you added will work only for root

Get element from within an iFrame

Below code will help you to find out iframe data.

let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;

Display XML content in HTML page

2017 Update I guess. textarea worked fine for me using Spring, Bootstrap and a bunch of other things. Got the SOAP payload stored in a DB, read by Spring and push via Spring-MVC. xmp didn't work at all.

How to show a dialog to confirm that the user wishes to exit an Android Activity?

I'd prefer to exit with double tap on the back button than with an exit Dialog.

In this solution, it show a toast when go back for the first time, warning that another back press will close the App. In this example less than 4 seconds.

private Toast toast;
private long lastBackPressTime = 0;

@Override
public void onBackPressed() {
  if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
    toast = Toast.makeText(this, "Press back again to close this app", 4000);
    toast.show();
    this.lastBackPressTime = System.currentTimeMillis();
  } else {
    if (toast != null) {
    toast.cancel();
  }
  super.onBackPressed();
 }
}

Token from: http://www.androiduipatterns.com/2011/03/back-button-behavior.html

How to remove focus around buttons on click

Add this in CSS:

*, ::after, ::before {
    box-sizing: border-box;
    outline: none !important;
    border: none !important;
    -webkit-box-shadow: none !important;
    box-shadow: none !important;
}

Reading entire html file to String?

For string operations use StringBuilder or StringBuffer classes for accumulating string data blocks. Do not use += operations for string objects. String class is immutable and you will produce a large amount of string objects upon runtime and it will affect on performance.

Use .append() method of StringBuilder/StringBuffer class instance instead.

JSON Java 8 LocalDateTime format in Spring Boot

As already mentioned, spring-boot will fetch all you need (for both web and webflux starter).

But what's even better - you don't need to register any modules yourself. Take a look here. Since @SpringBootApplication uses @EnableAutoConfiguration under the hood, it means JacksonAutoConfiguration will be added to the context automatically. Now, if you look inside JacksonAutoConfiguration, you will see:

    private void configureModules(Jackson2ObjectMapperBuilder builder) {
        Collection<Module> moduleBeans = getBeans(this.applicationContext,
                Module.class);
        builder.modulesToInstall(moduleBeans.toArray(new Module[0]));
    }

This fella will be called in the process of initialization and will fetch all the modules it can find in the classpath. (I use Spring Boot 2.1)

What is the meaning of Bus: error 10 in C

this is because str is pointing to a string literal means a constant string ...but you are trying to modify it by copying . Note : if it would have been an error due to memory allocation it would have been given segmentation fault at the run time .But this error is coming due to constant string modification or you can go through the below for more details abt bus error :

Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:

  • using a processor instruction with an address that does not satisfy its alignment requirements.

Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:

  • using a pointer to something that was deallocated.
  • using an uninitialized hence bogus pointer.
  • using a null pointer.
  • overflowing a buffer.

To be more precise this is not manipulating the pointer itself that will cause issues, it's accessing the memory it points to (dereferencing).

Codeigniter unset session

I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session

Proxy with urllib2

One can also use requests if we would like to access a web page using proxies. Python 3 code:

>>> import requests
>>> url = 'http://www.google.com'
>>> proxy = '169.50.87.252:80'
>>> requests.get(url, proxies={"http":proxy})
<Response [200]>

More than one proxies can also be added.

>>> proxy1 = '169.50.87.252:80'
>>> proxy2 = '89.34.97.132:8080'
>>> requests.get(url, proxies={"http":proxy1,"http":proxy2})
<Response [200]>

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

I fixed this. When you add the migration, in the Up() method there will be a line like this:

.ForeignKey("dbo.Members", t => t.MemberId, cascadeDelete:True)

If you just delete the cascadeDelete from the end it will work.

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

How to open a link in new tab (chrome) using Selenium WebDriver?

this below code works for me in Selenium 3 and chrome version 58.

    WebDriver driver = new ChromeDriver();
    driver.get("http://yahoo.com");  
    ((JavascriptExecutor)driver).executeScript("window.open()");
    ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));
    driver.get("http://google.com");

No grammar constraints (DTD or XML schema) detected for the document

I too had the same problem in eclipse using web.xml file
it showed me this " no grammar constraints referenced in the document "

but it can be resolved by adding tag
after the xml tag i.e. <?xml version = "1.0" encoding = "UTF-8"?>

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
  • status_code should just reconfirm the code you were given before, of course

How to write UTF-8 in a CSV file

It's very simple for Python 3.x (docs).

import csv

with open('output_file_name', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file, delimiter=';')
    writer.writerow('my_utf8_string')

For Python 2.x, look here.

How to call another controller Action From a controller in Mvc

This is exactly what I was looking for after finding that RedirectToAction() would not pass complex class objects.

As an example, I want to call the IndexComparison method in the LifeCycleEffectsResults controller and pass it a complex class object named model.

Here is the code that failed:

return RedirectToAction("IndexComparison", "LifeCycleEffectsResults", model);

Worth noting is that Strings, integers, etc were surviving the trip to this controller method, but generic list objects were suffering from what was reminiscent of C memory leaks.

As recommended above, here's the code I replaced it with:

var controller = DependencyResolver.Current.GetService<LifeCycleEffectsResultsController>();

var result = controller.IndexComparison(model);
return result;

All is working as intended now. Thank you for leading the way.

Jmeter - get current date and time

JMeter is using java SimpleDateFormat

For UTC with timezone use this

${__time(yyyy-MM-dd'T'hh:mm:ssX)}

Share application "link" in Android

Call this method:

public static void shareApp(Context context)
{
    final String appPackageName = context.getPackageName();
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out the App at: https://play.google.com/store/apps/details?id=" + appPackageName);
    sendIntent.setType("text/plain");
    context.startActivity(sendIntent);
}

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

If you migrate Visual Studio 2012 to 2013, then open *.csproj project file with edior.
and check 'Project' tag's ToolsVersion element.

Change its value from 4.0 to 12.0

  • From

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" ...
    
  • To

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="12.0" ...
    

Or If you build with msbuild then just specify VisualStudioVersion property

msbuild /p:VisualStudioVersion=12.0

Solution Source

How do I update zsh to the latest version?

If you have Homebrew installed, you can do this.

# check the zsh info
brew info zsh

# install zsh
brew install --without-etcdir zsh

# add shell path
sudo vim /etc/shells

# add the following line into the very end of the file(/etc/shells)
/usr/local/bin/zsh

# change default shell
chsh -s /usr/local/bin/zsh

Hope it helps, thanks.

Check if list contains element that contains a string and get that element

for (int i = 0; i < myList.Length; i++)
{
    if (myList[i].Contains(myString)) // (you use the word "contains". either equals or indexof might be appropriate)
    {
        return i;
    }
}

Old fashion loops are almost always the fastest.

What is the equivalent of the C# 'var' keyword in Java?

JEP - JDK Enhancement-Proposal

http://openjdk.java.net/jeps/286

JEP 286: Local-Variable Type Inference

Author Brian Goetz

// Goals:
var list = new ArrayList<String>();  // infers ArrayList<String>
var stream = list.stream();          // infers Stream<String>

How to check file MIME type with javascript before upload?

Here is a Typescript implementation that supports webp. This is based on the JavaScript answer by Vitim.us.

interface Mime {
  mime: string;
  pattern: (number | undefined)[];
}

// tslint:disable number-literal-format
// tslint:disable no-magic-numbers
const imageMimes: Mime[] = [
  {
    mime: 'image/png',
    pattern: [0x89, 0x50, 0x4e, 0x47]
  },
  {
    mime: 'image/jpeg',
    pattern: [0xff, 0xd8, 0xff]
  },
  {
    mime: 'image/gif',
    pattern: [0x47, 0x49, 0x46, 0x38]
  },
  {
    mime: 'image/webp',
    pattern: [0x52, 0x49, 0x46, 0x46, undefined, undefined, undefined, undefined, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50],
  }
  // You can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern
];
// tslint:enable no-magic-numbers
// tslint:enable number-literal-format

function isMime(bytes: Uint8Array, mime: Mime): boolean {
  return mime.pattern.every((p, i) => !p || bytes[i] === p);
}

function validateImageMimeType(file: File, callback: (b: boolean) => void) {
  const numBytesNeeded = Math.max(...imageMimes.map(m => m.pattern.length));
  const blob = file.slice(0, numBytesNeeded); // Read the needed bytes of the file

  const fileReader = new FileReader();

  fileReader.onloadend = e => {
    if (!e || !fileReader.result) return;

    const bytes = new Uint8Array(fileReader.result as ArrayBuffer);

    const valid = imageMimes.some(mime => isMime(bytes, mime));

    callback(valid);
  };

  fileReader.readAsArrayBuffer(blob);
}

// When selecting a file on the input
fileInput.onchange = () => {
  const file = fileInput.files && fileInput.files[0];
  if (!file) return;

  validateImageMimeType(file, valid => {
    if (!valid) {
      alert('Not a valid image file.');
    }
  });
};

_x000D_
_x000D_
<input type="file" id="fileInput">
_x000D_
_x000D_
_x000D_

`col-xs-*` not working in Bootstrap 4

They dropped XS because Bootstrap is considered a mobile-first development tool. It's default is considered xs and so doesn't need to be defined.

Batch file to copy directories recursively

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Windows Batch File Looping Through Directories to Process Files?

Action bar navigation modes are deprecated in Android L

I had the same problem and this solution suited me quite nicely:

In the layout xml file that contains the viewpager, add the a PagerTabStrip as shown:

<android.support.v4.view.PagerTabStrip
    android:id="@+id/pager_tab_strip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:background="#996633"
    android:textColor="#CCCCCC"
    android:paddingTop="5dp"
    android:paddingBottom="5dp" />

To control page titles, add a switch statement to your ViewPager file:

@Override
public CharSequence getPageTitle(int position)
{
    switch (position)
    {
    case 0:
        return "Page 1";

    case 1:
        return "Page 2";

    case 2:
        return "Page 3";

    }

    return null;
}

Update multiple rows with different values in a single SQL query

I could not make @Clockwork-Muse work actually. But I could make this variation work:

WITH Tmp AS (SELECT * FROM (VALUES (id1, newsPosX1, newPosY1), 
                                   (id2, newsPosX2, newPosY2),
                                   ......................... ,
                                   (idN, newsPosXN, newPosYN)) d(id, px, py))

UPDATE t

SET posX = (SELECT px FROM Tmp WHERE t.id = Tmp.id),
    posY = (SELECT py FROM Tmp WHERE t.id = Tmp.id)

FROM TableToUpdate t

I hope this works for you too!

Visual Studio window which shows list of methods

I have been using USysWare DPack since forever. It is very small and not intrusive so if all you want is a quick shortcut window showing list of methods of the current file you are using, it provides just that. Good thing is that the author is still active after more than 10 years just to keep providing the same features into latest VS release.

https://marketplace.visualstudio.com/items?itemName=SergeyM.DPack-16348

After installation, just use Alt + M to bring up the method list window. I prefer to show all members instead, but it's up to you.

How to loop through a dataset in powershell?

The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}

Additionally foreach allows you to iterate through a collection or array without needing to figure out the length.

Rewritten (and edited for compile) -

foreach ($Row in $ds.Tables[1].Rows)
{ 
  write-host "value is : $($Row[0])"
}

Non-static variable cannot be referenced from a static context

To be able to access them from your static methods they need to be static member variables, like this:

public class MyProgram7 {
  static Scanner scan = new Scanner(System.in);
  static int compareCount = 0;
  static int low = 0;
  static int high = 0;
  static int mid = 0;  
  static int key = 0;  
  static Scanner temp;  
  static int[]list;  
  static String menu, outputString;  
  static int option = 1;  
  static boolean found = false;

  public static void main (String[]args) throws IOException {
  ...

Error after upgrading pip: cannot import name 'main'

Same thing happened to me on Pixelbook using the new LXC (strech). This solution is very similar to the accepted one, with one subtle difference, whiched fixed pip3 for me.

sudo python3 -m pip install --upgrade pip

That bumped the version, and now it works as expected.

I found it here ... Python.org: Ensure pip is up-to-date

Use a JSON array with objects with javascript

This is your dataArray:

[
   {
      "id":28,
      "Title":"Sweden"
   },
   {
      "id":56,
      "Title":"USA"
   },
   {
      "id":89,
      "Title":"England"
   }
]

Then parseJson can be used:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});

How to make HTTP Post request with JSON body in Swift

func fucntion()
{

    var parameters = [String:String]()
    let apiToken = "Bearer \(ApiUtillity.sharedInstance.getUserData(key: "vAuthToken"))"
    let headers = ["Vauthtoken":apiToken]

    parameters = ["firstname":name,"lastname":last_name,"mobile":mobile_number,"email":emails_Address]


    Alamofire.request(ApiUtillity.sharedInstance.API(Join: "user/edit_profile"), method: .post, parameters: parameters, encoding: URLEncoding.default,headers:headers).responseJSON { response in
        debugPrint(response)
        if let json = response.result.value {
            let dict:NSDictionary = (json as? NSDictionary)!
            print(dict)
            //                print(response)

            let StatusCode = dict.value(forKey: "status") as! Int

            if StatusCode==200
            {
                ApiUtillity.sharedInstance.dismissSVProgressHUDWithSuccess(success: "Success")
                let UserData = dict.value(forKey: "data") as! NSDictionary
                print(UserData)

            }

            else if StatusCode==401
            {
                let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
                let ErrorMessage = ErrorDic.value(forKey: "error") as! String

            }
            else
            {

                let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
                let ErrorMessage = ErrorDic.value(forKey: "error") as! String
            }

        }
        else
        {
            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: "Something went wrong")
        }
    }

Position an element relative to its container

I know I am late but hope this helps.

Following are the values for the position property.

  • static
  • fixed
  • relative
  • absolute

position : static

This is default. It means the element will occur at a position that it normally would.

#myelem {
    position : static;
}

position : fixed

This will set the position of an element with respect to the browser window (viewport). A fixed positioned element will remain in its position even when the page scrolls.

(Ideal if you want scroll-to-top button at the bottom right corner of the page).

#myelem {
    position : fixed;
    bottom : 30px;
    right : 30px;
}

position : relative

To place an element at a new location relative to its original position.

#myelem {
    position : relative;
    left : 30px;
    top : 30px;
}

The above CSS will move the #myelem element 30px to the left and 30px from the top of its actual location.

position : absolute

If we want an element to be placed at an exact position in the page.

#myelem {
    position : absolute;
    top : 30px;
    left : 300px;
}

The above CSS will position #myelem element at a position 30px from top and 300px from the left in the page and it will scroll with the page.

And finally...

position relative + absolute

We can set the position property of a parent element to relative and then set the position property of the child element to absolute. This way we can position the child relative to the parent at an absolute position.

#container {
    position : relative;
}

#div-2 {
    position : absolute;
    top : 0;
    right : 0;
}

Absolute position of a child element w.r.t. a Relative positioned parent element.

We can see in the above image the #div-2 element is positioned at the top-right corner inside the #container element.

GitHub: You can find the HTML of the above image here and CSS here.

Hope this tutorial helps.

How to round up the result of integer division?

Converting to floating point and back seems like a huge waste of time at the CPU level.

Ian Nelson's solution:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

Can be simplified to:

int pageCount = (records - 1) / recordsPerPage + 1;

AFAICS, this doesn't have the overflow bug that Brandon DuRette pointed out, and because it only uses it once, you don't need to store the recordsPerPage specially if it comes from an expensive function to fetch the value from a config file or something.

I.e. this might be inefficient, if config.fetch_value used a database lookup or something:

int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');

This creates a variable you don't really need, which probably has (minor) memory implications and is just too much typing:

int recordsPerPage = config.fetch_value('records per page')
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

This is all one line, and only fetches the data once:

int pageCount = (records - 1) / config.fetch_value('records per page') + 1;

How to randomly select an item from a list?

How to randomly select an item from a list?

Assume I have the following list:

foo = ['a', 'b', 'c', 'd', 'e']  

What is the simplest way to retrieve an item at random from this list?

If you want close to truly random, then I suggest secrets.choice from the standard library (New in Python 3.6.):

>>> from secrets import choice         # Python 3 only
>>> choice(list('abcde'))
'c'

The above is equivalent to my former recommendation, using a SystemRandom object from the random module with the choice method - available earlier in Python 2:

>>> import random                      # Python 2 compatible
>>> sr = random.SystemRandom()
>>> foo = list('abcde')
>>> foo
['a', 'b', 'c', 'd', 'e']

And now:

>>> sr.choice(foo)
'd'
>>> sr.choice(foo)
'e'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'b'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'c'
>>> sr.choice(foo)
'c'

If you want a deterministic pseudorandom selection, use the choice function (which is actually a bound method on a Random object):

>>> random.choice
<bound method Random.choice of <random.Random object at 0x800c1034>>

It seems random, but it's actually not, which we can see if we reseed it repeatedly:

>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')

A comment:

This is not about whether random.choice is truly random or not. If you fix the seed, you will get the reproducible results -- and that's what seed is designed for. You can pass a seed to SystemRandom, too. sr = random.SystemRandom(42)

Well, yes you can pass it a "seed" argument, but you'll see that the SystemRandom object simply ignores it:

def seed(self, *args, **kwds):
    "Stub method.  Not used for a system random number generator."
    return None

How can I undo a mysql statement that I just executed?

in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:

copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.

since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.

Java Try and Catch IOException Problem

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }

   if(lines > 0) {
     // Do rest of program.
   }
}

Text Editor which shows \r\n?

You can get this in Emacs by changing the mode. For example, here is what things look like in Whitespace mode.

alt text

How to sort a List<Object> alphabetically using Object name field

something like

  List<FancyObject> theList = … ;
  Collections.sort (theList,
                    new Comparator<FancyObject> ()
                    { int compare (final FancyObject a, final FancyObject d)
                          { return (a.getName().compareTo(d.getName())); }});

How to assert greater than using JUnit Assert?

you can also try below simple soln:

previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";

Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);

Assert.assertTrue(prev  > curr );   

Python recursive folder read

If you want a flat list of all paths under a given dir (like find . in the shell):

   files = [ 
       os.path.join(parent, name)
       for (parent, subdirs, files) in os.walk(YOUR_DIRECTORY)
       for name in files + subdirs
   ]

To only include full paths to files under the base dir, leave out + subdirs.

Count(*) vs Count(1) - SQL Server

COUNT(*) and COUNT(1) are same in case of result and performance.

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

You can use:

SET PASSWORD FOR 'root' = PASSWORD('elephant7');

or, in latest versions:

SET PASSWORD FOR root = 'elephant7' 

You can also use:

UPDATE user SET password=password('elephant7') WHERE user='root';

but in Mysql 5.7 the field password is no more there, and you have to use:

UPDATE user SET authentication_string=password('elephant7') WHERE user='root';

Regards

How to integrate SAP Crystal Reports in Visual Studio 2017

FYI: Taken from: https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads

Overview

Support Packs for “SAP Crystal Reports, developer version for Microsoft Visual Studio” (SAP Crystal Reports for Visual Studio) are scheduled on a quarterly bases and support the following versions of Visual Studio:

  • VS 2010 – original release and higher
  • VS 2012 – SP 7 and higher
  • VS 2013 – SP 9 and higher
  • VS 2015RC – SP14
  • VS 2015 – SP 15 and higher
  • VS 2017 - SP 21 and higher

Download Crystal Reports developer, for Microsoft Visual Studio

Button background as transparent

You can do it easily by adding below attribute in xml file. This code was tested plenty of time.

android:background="@android:color/transparent"

Checking Value of Radio Button Group via JavaScript?

_x000D_
_x000D_
function myFunction() {_x000D_
document.getElementById("text").value='male'_x000D_
 document.getElementById("myCheck_2").checked = false;_x000D_
  var checkBox = document.getElementById("myCheck");_x000D_
  var text = document.getElementById("text");_x000D_
  if (checkBox.checked == true){_x000D_
    text.style.display = "block";_x000D_
  } else {_x000D_
     text.style.display = "none";_x000D_
  }_x000D_
}_x000D_
function myFunction_2() {_x000D_
document.getElementById("text").value='female'_x000D_
 document.getElementById("myCheck").checked = false;_x000D_
  var checkBox = document.getElementById("myCheck_2");_x000D_
  var text = document.getElementById("text");_x000D_
  if (checkBox.checked == true){_x000D_
    text.style.display = "block";_x000D_
  } else {_x000D_
     text.style.display = "none";_x000D_
  }_x000D_
}
_x000D_
Male: <input type="checkbox" id="myCheck"  onclick="myFunction()">_x000D_
Female: <input type="checkbox" id="myCheck_2"  onclick="myFunction_2()">_x000D_
_x000D_
<input type="text" id="text" placeholder="Name">
_x000D_
_x000D_
_x000D_

Delete all nodes and relationships in neo4j 1.8

Neo4j cannot delete nodes that have a relation. You have to delete the relations before you can delete the nodes.

But, it is simple way to delete "ALL" nodes and "ALL" relationships with a simple chyper. This is the code:

MATCH (n) DETACH DELETE n

--> DETACH DELETE will remove all of the nodes and relations by Match

How to create a directory if it doesn't exist using Node.js?

Just in case any one interested in the one line version. :)

//or in typescript: import * as fs from 'fs';
const fs = require('fs');
!fs.existsSync(dir) && fs.mkdirSync(dir);

Does Arduino use C or C++?

Arduino sketches are written in C++.

Here is a typical construct you'll encounter:

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");

That's C++, not C.

Hence do yourself a favor and learn C++. There are plenty of books and online resources available.

Is it possible to decrypt MD5 hashes?

Yes, exactly what you're asking for is possible. It is not possible to 'decrypt' an MD5 password without help, but it is possible to re-encrypt an MD5 password into another algorithm, just not all in one go.

What you do is arrange for your users to be able to logon to your new system using the old MD5 password. At the point that they login they have given your login program an unhashed version of the password that you prove matches the MD5 hash that you have. You can then convert this unhashed password to your new hashing algorithm.

Obviously, this is an extended process because you have to wait for your users to tell you what the passwords are, but it does work.

(NB: seven years later, oh well hopefully someone will find it useful)

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

CSS technique for a horizontal line with words in the middle

CSS grids to the rescue

Similar to the flex answers above, this can also be done using CSS Grids. This gives you more scope to offset the title, and a more simple way of expanding the gap between the lines (using grid-template-columns) and the content (using grid-gap).

The benefits of this method over flex methods is the ease of being able to offset the lines, and additionally only needing to add in a gap between columns once (not twice, for each the :before and :after pseudo element). It is also much more syntactically cleaner and obvious IMO.

_x000D_
_x000D_
h1 {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  align-items: center;
  grid-gap: 1rem;
}

h1:before,
h1:after {
  content: "";
  display: block;
  border-top: 2px solid currentColor;
}

h1.offset {
  grid-template-columns: 1fr auto 3fr;
}

h1.biggap {
  grid-gap: 4rem;
}
_x000D_
<h1>This is a title</h1>

<h1 class="offset">Offset title</h1>

<h1 class="biggap">Gappy title</h1>

<h1>
  <span>Multi-line<br />title</span>
</h1>
_x000D_
_x000D_
_x000D_

How to call a JavaScript function within an HTML body

Just to clarify things, you don't/can't "execute it within the HTML body".

You can modify the contents of the HTML using javascript.

You decide at what point you want the javascript to be executed.

For example, here is the contents of a html file, including javascript, that does what you want.

<html>
  <head>
    <script>
    // The next line document.addEventListener....
    // tells the browser to execute the javascript in the function after
    // the DOMContentLoaded event is complete, i.e. the browser has
    // finished loading the full webpage
    document.addEventListener("DOMContentLoaded", function(event) { 
      var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below  $500.00" ];
      var col2 = ["None", "None", "$8.00"];
      var TheInnerHTML ="";
      for (var j = 0; j < col1.length; j++) {
        TheInnerHTML += "<tr><td>"+col1[j]+"</td><td>"+col2[j]+"</td></tr>";
    }
    document.getElementById("TheBody").innerHTML = TheInnerHTML;});
    </script>
  </head>
  <body>
    <table>
    <thead>
      <tr>
        <th>Balance</th>
        <th>Fee</th>        
      </tr>
    </thead>
    <tbody id="TheBody">
    </tbody>
  </table>
</body>

Enjoy !

how to check if string contains '+' character

You need this instead:

if(s.contains("+"))

contains() method of String class does not take regular expression as a parameter, it takes normal text.


EDIT:

String s = "ddjdjdj+kfkfkf";

if(s.contains("+"))
{
    String parts[] = s.split("\\+");
    System.out.print(parts[0]);
}

OUTPUT:

ddjdjdj

Receiving "Attempted import error:" in react app

import { combineReducers } from '../../store/reducers';

should be

import combineReducers from '../../store/reducers';

since it's a default export, and not a named export.

There's a good breakdown of the differences between the two here.

C++: what regex library should I use?

C++ has a builtin regex library since TR1. AFAIK Boost's regex library is very compatible with it and can be used as a replacement, if your standard library doesn't provide TR1.

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

How to parse/format dates with LocalDateTime? (Java 8)

All the answers are good. The java8+ have these patterns for parsing and formatting timezone: V, z, O, X, x, Z.

Here's they are, for parsing, according to rules from the documentation :

   Symbol  Meaning                     Presentation      Examples
   ------  -------                     ------------      -------
   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;

But how about formatting? Here's a sample for a date (assuming ZonedDateTime) that show these patters behavior for different formatting patters:

// The helper function:
static void printInPattern(ZonedDateTime dt, String pattern) {
    System.out.println(pattern + ": " + dt.format(DateTimeFormatter.ofPattern(pattern)));
}        

// The date:
String strDate = "2020-11-03 16:40:44 America/Los_Angeles";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzzz");
ZonedDateTime dt = ZonedDateTime.parse(strDate, format);
// 2020-11-03T16:40:44-08:00[America/Los_Angeles]

// Rules:
// printInPattern(dt, "V");     // exception!
printInPattern(dt, "VV");       // America/Los_Angeles
// printInPattern(dt, "VVV");   // exception!
// printInPattern(dt, "VVVV");  // exception!
printInPattern(dt, "z");        // PST
printInPattern(dt, "zz");       // PST
printInPattern(dt, "zzz");      // PST
printInPattern(dt, "zzzz");     // Pacific Standard Time
printInPattern(dt, "O");        // GMT-8
// printInPattern(dt, "OO");    // exception!
// printInPattern(dt, "OO0");   // exception!
printInPattern(dt, "OOOO");     // GMT-08:00
printInPattern(dt, "X");        // -08
printInPattern(dt, "XX");       // -0800
printInPattern(dt, "XXX");      // -08:00
printInPattern(dt, "XXXX");     // -0800
printInPattern(dt, "XXXXX");    // -08:00
printInPattern(dt, "x");        // -08
printInPattern(dt, "xx");       // -0800
printInPattern(dt, "xxx");      // -08:00
printInPattern(dt, "xxxx");     // -0800
printInPattern(dt, "xxxxx");    // -08:00
printInPattern(dt, "Z");        // -0800
printInPattern(dt, "ZZ");       // -0800
printInPattern(dt, "ZZZ");      // -0800
printInPattern(dt, "ZZZZ");     // GMT-08:00
printInPattern(dt, "ZZZZZ");    // -08:00

In the case of positive offset the + sign character is used everywhere(where there is - now) and never omitted.

This well works for new java.time types. If you're about to use these for java.util.Date or java.util.Calendar - not all going to work as those types are broken(and so marked as deprecated, please don't use them)

Double Iteration in List Comprehension

Additionally, you could use just the same variable for the member of the input list which is currently accessed and for the element inside this member. However, this might even make it more (list) incomprehensible.

input = [[1, 2], [3, 4]]
[x for x in input for x in x]

First for x in input is evaluated, leading to one member list of the input, then, Python walks through the second part for x in x during which the x-value is overwritten by the current element it is accessing, then the first x defines what we want to return.

How can I put a ListView into a ScrollView without it collapsing?

We could not use two scrolling simulteniuosly.We will have get total length of ListView and expand listview with the total height .Then we can add ListView in ScrollView directly or using LinearLayout because ScrollView have directly one child . copy setListViewHeightBasedOnChildren(lv) method in your code and expand listview then you can use listview inside scrollview. \layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
 <ScrollView

        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
         android:background="#1D1D1D"
        android:orientation="vertical"
        android:scrollbars="none" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#1D1D1D"
            android:orientation="vertical" >

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="40dip"
                android:background="#333"
                android:gravity="center_vertical"
                android:paddingLeft="8dip"
                android:text="First ListView"
                android:textColor="#C7C7C7"
                android:textSize="20sp" />

            <ListView
                android:id="@+id/first_listview"
                android:layout_width="260dp"
                android:layout_height="wrap_content"
                android:divider="#00000000"
               android:listSelector="#ff0000"
                android:scrollbars="none" />

               <TextView
                android:layout_width="fill_parent"
                android:layout_height="40dip"
                android:background="#333"
                android:gravity="center_vertical"
                android:paddingLeft="8dip"
                android:text="Second ListView"
                android:textColor="#C7C7C7"
                android:textSize="20sp" />

            <ListView
                android:id="@+id/secondList"
                android:layout_width="260dp"
                android:layout_height="wrap_content"
                android:divider="#00000000"
                android:listSelector="#ffcc00"
                android:scrollbars="none" />
  </LinearLayout>
  </ScrollView>

   </LinearLayout>

onCreate method in Activity class:

 import java.util.ArrayList;
  import android.app.Activity;
 import android.os.Bundle;
 import android.view.Menu;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ListAdapter;
  import android.widget.ListView;

   public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview_inside_scrollview);
    ListView list_first=(ListView) findViewById(R.id.first_listview);
    ListView list_second=(ListView) findViewById(R.id.secondList);
    ArrayList<String> list=new ArrayList<String>();
    for(int x=0;x<30;x++)
    {
        list.add("Item "+x);
    }

       ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), 
          android.R.layout.simple_list_item_1,list);               
      list_first.setAdapter(adapter);

     setListViewHeightBasedOnChildren(list_first);

      list_second.setAdapter(adapter);

    setListViewHeightBasedOnChildren(list_second);
   }



   public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
      }

How to switch to the new browser window, which opens after click on the button?

 main you can do :

 String mainTab = page.goToNewTab ();
 //do what you want
 page.backToMainPage(mainTab);  

 What you need to have in order to use the main   

        private static Set<String> windows;

            //get all open windows 
            //return current window
            public String initWindows() {
                windows = new HashSet<String>();
                driver.getWindowHandles().stream().forEach(n ->   windows.add(n));
                return driver.getWindowHandle();
            }

            public String getNewWindow() {
                List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
                        .collect(Collectors.toList());
                logger.info(newWindow.get(0));
                return newWindow.get(0);
            }


            public String goToNewTab() {
                String startWindow = driver.initWindows();
                driver.findElement(By.cssSelector("XX")).click();
                String newWindow = driver.getNewWindow();
                driver.switchTo().window(newWindow);
                return startWindow;
            }

            public void backToMainPage(String startWindow) {
                driver.close();
                driver.switchTo().window(startWindow);
            }

default select option as blank

There is no HTML solution. By the HTML 4.01 spec, browser behavior is undefined if none of the option elements has the selected attribute, and what browsers do in practice is that they make the first option pre-selected.

As a workaround, you could replace the select element by a set of input type=radio elements (with the same name attribute). This creates a control of the same kind though with different appearance and user interface. If none of the input type=radio elements has the checked attribute, none of them is initially selected in most modern browsers.

How to create cross-domain request?

It is nothing you can do in the client side. I added @CrossOrigin in the controller in the server side and it works.

@RestController
@CrossOrigin(origins = "*")
public class MyController

Please refer to docs.

Lin

Trim a string based on the string length

str==null ? str : str.substring(0, Math.min(str.length(), 10))

or,

str==null ? "" : str.substring(0, Math.min(str.length(), 10))

Works with null.

JavaScript: Global variables after Ajax requests

AJAX stands for Asynchronous JavaScript and XML. Thus, the post to the server happens out-of-sync with the rest of the function. Try some code like this instead (it just breaks the shorthand $.post out into the longer $.ajax call and adds the async option).

var it_works = false;

$.ajax({
  type: 'POST',
  async: false,
  url: "some_file.php",
  data: "",
  success: function() {it_works = true;}
});

alert(it_works);

Hope this helps!

How to download a file over HTTP?

This may be a little late, But I saw pabloG's code and couldn't help adding a os.system('cls') to make it look AWESOME! Check it out :

    import urllib2,os

    url = "http://download.thinkbroadband.com/10MB.zip"

    file_name = url.split('/')[-1]
    u = urllib2.urlopen(url)
    f = open(file_name, 'wb')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)
    os.system('cls')
    file_size_dl = 0
    block_sz = 8192
    while True:
        buffer = u.read(block_sz)
        if not buffer:
            break

        file_size_dl += len(buffer)
        f.write(buffer)
        status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
        status = status + chr(8)*(len(status)+1)
        print status,

    f.close()

If running in an environment other than Windows, you will have to use something other then 'cls'. In MAC OS X and Linux it should be 'clear'.

Annotations from javax.validation.constraints not working

If you are using lombok then, you can use @NonNull annotation insted. or Just add the javax.validation dependency in pom.xml file.

How to select rows for a specific date, ignoring time in SQL Server

select * from sales where salesDate between '11/11/2010' and '12/11/2010' --if using dd/mm/yyyy

The more correct way to do it:

DECLARE @myDate datetime
SET @myDate = '11/11/2010'
select * from sales where salesDate>=@myDate and salesDate<dateadd(dd,1,@myDate)

If only the date is specified, it means total midnight. If you want to make sure intervals don't overlap, switch the between with a pair of >= and <

you can do it within one single statement, but it's just that the value is used twice.

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

I would check that the file is not empty first:

import os

scores = {} # scores is an empty dict already

if os.path.getsize(target) > 0:      
    with open(target, "rb") as f:
        unpickler = pickle.Unpickler(f)
        # if file is not empty scores will be equal
        # to the value unpickled
        scores = unpickler.load()

Also open(target, 'a').close() is doing nothing in your code and you don't need to use ;.

How to split a long array into smaller arrays, with JavaScript

As a supplement to @jyore's answer, and in case you still want to keep the original array:

var originalArray = [1,2,3,4,5,6,7,8];

var splitArray = function (arr, size) {

  var arr2 = arr.slice(0),
      arrays = [];

  while (arr2.length > 0) {
      arrays.push(arr2.splice(0, size));
  }

  return arrays;
}

splitArray(originalArray, 2);
// originalArray is still = [1,2,3,4,5,6,7,8];

How to modify a specified commit?

To get a non-interactive command, put a script with this content in your PATH:

#!/bin/sh
#
# git-fixup
# Use staged changes to modify a specified commit
set -e
cmt=$(git rev-parse $1)
git commit --fixup="$cmt"
GIT_EDITOR=true git rebase -i --autosquash "$cmt~1"

Use it by staging your changes (with git add) and then run git fixup <commit-to-modify>. Of course, it will still be interactive if you get conflicts.

How do I import .sql files into SQLite 3?

Use sqlite3 database.sqlite3 < db.sql. You'll need to make sure that your files contain valid SQL for SQLite.

Why does the arrow (->) operator in C exist?

C also does a good job at not making anything ambiguous.

Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.

How to install wget in macOS?

For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.

  1. Install Xcode

  2. Build OpenSSL

    Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.

    Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".

  3. Build wget

    Go to wget directory, configure:

    ./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
    

    wget should configure and found OpenSSL, then make:

    make
    

    wget made out. Install wget:

    make install
    

    Or just copy wget to where you want.

  4. Configure cert

    You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:

    New way:

    If you machine doesn't have "/usr/local/ssl/" dir, first make it.

    ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
    

    Old way:

    security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
    security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
    

    Then put cert.pem to: "/usr/local/ssl/cert.pem"

    DONE: It should be all right now.

asp.net: How can I remove an item from a dropdownlist?

Try this code.

If you can add any item and set value in dropdown then try it.

 dropdown1.Items.Insert(0, new ListItem("---All---", "0"));

You can Removed Item in dropdown then try it.

 ListItem removeItem = dropdown1.Items.FindByText("--Please Select--");
 dropdown1.Items.Remove(removeItem);

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

How to select only 1 row from oracle sql?

This syntax is available in Oracle 12c:

select * from some_table fetch first 1 row only;
select * from some_table fetch first 1 rows only;
select * from some_table fetch first 10 row only;
select * from some_table fetch first 10 rows only;

^^I just wanted to demonstrate that either row or rows (plural) can be used regardless of the plurality of the desired number of rows.)

What is the behavior of integer division?

Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.

From the ANSI C draft (3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

So watch out with negative numbers when you are stuck with a C89 compiler.

It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.

What's the use of session.flush() in Hibernate

With this method you evoke the flush process. This process synchronizes the state of your database with state of your session by detecting state changes and executing the respective SQL statements.

How are booleans formatted in Strings in Python?

You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

Without any SMTP server sending mail,use this code for sending mail....

click below for mail sending code

Click here

listen guys first you can do this less secure your gmail account after send mail with your gmail account

You can use this php.ini setting

;smtp = smtp.gmail.com
;smtp-port = 25
;sendmail_from = my gmail is here

And sendmail.ini settings

smtp_server = smtp.gmail.com
smtp_port = 465
smtp_ssl = auto
auth_username = my gmail is here
auth_password = password
hostname = localhost

you can try this changes and i hope this code sent mail....

Get only part of an Array in Java?

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

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

Reading specific columns from a text file in python

You have a space delimited file, so use the module designed for reading delimited values files, csv.

import csv

with open('path/to/file.txt') as inf:
    reader = csv.reader(inf, delimiter=" ")
    second_col = list(zip(*reader))[1]
    # In Python2, you can omit the `list(...)` cast

The zip(*iterable) pattern is useful for converting rows to columns or vice versa. If you're reading a file row-wise...

>>> testdata = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]]

>>> for line in testdata:
...     print(line)

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

...but need columns, you can pass each row to the zip function

>>> testdata_columns = zip(*testdata)
# this is equivalent to zip([1,2,3], [4,5,6], [7,8,9])

>>> for line in testdata_columns:
...     print(line)

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

How to log PostgreSQL queries?

You also need add these lines in PostgreSQL and restart the server:

log_directory = 'pg_log'                    
log_filename = 'postgresql-dateformat.log'
log_statement = 'all'
logging_collector = on

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.

Remove Unnamed columns in pandas dataframe

The pandas.DataFrame.dropna function removes missing values (e.g. NaN, NaT).

For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.

df.dropna(how='all', axis='columns')

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

How to convert an Array to a Set in Java

In Eclipse Collections, the following will work:

Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);

Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();

Note: I am a committer for Eclipse Collections

CSS - How to Style a Selected Radio Buttons Label?

If you really want to put the checkboxes inside the label, try adding an extra span tag, eg.

HTML

<div class="radio-toolbar">
 <label><input type="radio" value="all" checked><span>All</span></label>
 <label><input type="radio" value="false"><span>Open</span></label>
 <label><input type="radio" value="true"><span>Archived</span></label>
</div>

CSS

.radio-toolbar input[type="radio"]:checked ~ * { 
    background:pink !important;
}

That will set the backgrounds for all siblings of the selected radio button.

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

I had the same issue but I can solve this issue by cleaning the cookies and cache from my browser (ctrl+shift+R). Also, you must ensure that your access token is active.

Hope this will help you to solve your problem.

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

SimpleDateFormat

sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
String dateString=sdf.format(date);

It will give the output 28/09/2013 09:57:19 as you expected.

For complete program click here

Can pm2 run an 'npm start' script

pm2 start ./bin/www

can running

if you wanna multiple server deploy you can do that. instead of pm2 start npm -- start

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

How might I extract the property values of a JavaScript object into an array?

ES2017 using Object.values:

_x000D_
_x000D_
const dataObject = {_x000D_
    object1: {_x000D_
        id: 1,_x000D_
        name: "Fred"_x000D_
    },_x000D_
    object2: {_x000D_
        id: 2,_x000D_
        name: "Wilma"_x000D_
    },_x000D_
    object3: {_x000D_
        id: 3,_x000D_
        name: "Pebbles"_x000D_
    }_x000D_
};_x000D_
_x000D_
const valuesOnly = Object.values(dataObject);_x000D_
_x000D_
console.log(valuesOnly)
_x000D_
_x000D_
_x000D_

How to know if .keyup() is a character key (jQuery)

If you only need to exclude out enter, escape and spacebar keys, you can do the following:

$("#text1").keyup(function(event) {
if (event.keyCode != '13' && event.keyCode != '27' && event.keyCode != '32') {
     alert('test');
   }
});

See it actions here.

You can refer to the complete list of keycode here for your further modification.

Failed to load resource: net::ERR_INSECURE_RESPONSE

Your resource probably use a self-signed SSL certificate over HTTPS protocol. Chromium, so Google Chrome block by default this kind of resource considered unsecure.

You can bypass this this way :

  • Assuming your frame's URL is https://www.domain.com, open a new tab in chrome and go to https://www.domain.com.
  • Chrome will ask you to accept the SSL certificate. Accept it.
  • Then, if you reload your page with your frame, you could see that now it works

The problem as you can guess, is that each visitor of your website has to do this task to access your frame.

You can notice that chrome will block your URL for each navigation session, while chrome can memorise for ever that you trust this domain.

If your frame can be accessed by HTTP rather than HTTPS, I suggest you to use it, so this problem will be solved.

How do I use the built in password reset/change views with my own templates

If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.

The b-list has a good introduction to context processors.

Edit (I seem to have been confused about what the actual question was):

You'll notice that password_reset takes a named parameter called template_name:

def password_reset(request, is_admin_site=False, 
            template_name='registration/password_reset_form.html',
            email_template_name='registration/password_reset_email.html',
            password_reset_form=PasswordResetForm, 
            token_generator=default_token_generator,
            post_reset_redirect=None):

Check password_reset for more information.

... thus, with a urls.py like:

from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset

urlpatterns = patterns('',
     (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
     ...
)

django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.

In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.

How to set the height and the width of a textfield in Java?

There's a way which maybe not perfect, but can meet your requirement. The main point here is use a special dimension to restrict the height. But at the same time, width actually is free, as the max width is big enough.

package test;
import java.awt.*;
import javax.swing.*;

public final class TestFrame extends Frame{
    public TestFrame(){
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.setPreferredSize(new Dimension(500, 200));
        p.setMaximumSize(new Dimension(10000, 200));
        p.add(new JLabel("TEST: "));

        JPanel p1 = new JPanel();
        p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
        p1.setMaximumSize(new Dimension(10000, 200));
        p1.add(new JTextField(50));

        p.add(p1);

        this.setLayout(new BorderLayout());
        this.add(p, BorderLayout.CENTER);
    }
    //TODO: GUI CREATE
}

Compare one String with multiple values in one expression

Just use var-args and write your own static method:

public static boolean compareWithMany(String first, String next, String ... rest)
{
    if(first.equalsIgnoreCase(next))
        return true;
    for(int i = 0; i < rest.length; i++)
    {
        if(first.equalsIgnoreCase(rest[i]))
            return true;
    }
    return false;
}

public static void main(String[] args)
{
    final String str = "val1";
    System.out.println(compareWithMany(str, "val1", "val2", "val3"));
}

In Python, how do you convert seconds since epoch to a `datetime` object?

For those that want it ISO 8601 compliant, since the other solutions do not have the T separator nor the time offset (except Meistro's answer):

from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00

Note, I use fromtimestamp because if I used utcfromtimestamp I would need to chain on .astimezone(...) anyway to get the offset.

If you don't want to go all the way to microseconds you can choose a different unit with the isoformat() method.

Read pdf files with php

Not exactly php, but you could exec a program from php to convert the pdf to a temporary html file and then parse the resulting file with php. I've done something similar for a project of mine and this is the program I used:

PdfToHtml

The resulting HTML wraps text elements in < div > tags with absolute position coordinates. It seems like this is exactly what you are trying to do.

Opening a .ipynb.txt File

Try the following steps:

  1. Download the file open it in the Juypter Notebook.
  2. Go to File -> Rename and remove the .txt extension from the end; so now the file name has just .ipynb extension.
  3. Now reopen it from the Juypter Notebook.

HTML/CSS: how to put text both right and left aligned in a paragraph

enter image description here

If the texts has different sizes and they must be underlined this is the solution:

<table>
  <tr>
    <td class='left'>January</td>
    <td class='right'>2014</td>
  </tr>
</table>

css:

table{
    width: 100%;
    border-bottom: 2px solid black;
    /*this is the size of the small text's baseline over part  (˜25px*3/4)*/
    line-height: 19.5px; 
}
table td{
    vertical-align: baseline;
}
.left{
    font-family: Arial;
    font-size: 40px;
    text-align: left;

}
.right{
    font-size: 25px;
    text-align: right;
}

demo here

Blocking device rotation on mobile web pages

seems weird that no one proposed the CSS media query solution:

@media screen and (orientation: portrait) {
  ...
}

and the option to use a specific style sheet:

<link rel="stylesheet" type="text/css" href="css/style_p.css" media="screen and (orientation: portrait)">

MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#orientation

How do I make a Windows batch script completely silent?

Copies a directory named html & all its contents to a destination directory in silent mode. If the destination directory is not present it will still create it.

@echo off
TITLE Copy Folder with Contents

set SOURCE=C:\labs
set DESTINATION=C:\Users\MyUser\Desktop\html

xcopy %SOURCE%\html\* %DESTINATION%\* /s /e /i /Y >NUL

  1. /S Copies directories and subdirectories except empty ones.

  2. /E Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.

  3. /I If destination does not exist and copying more than one file, assumes that destination must be a directory.

  4. /Y Suppresses prompting to confirm you want to overwrite an existing destination file.

How to fill Matrix with zeros in OpenCV?

How to fill Matrix with zeros in OpenCV?

To fill a pre-existing Mat object with zeros, you can use Mat::zeros()

Mat m1 = ...;
m1 = Mat::zeros(1, 1, CV_64F);

To intialize a Mat so that it contains only zeros, you can pass a scalar with value 0 to the constructor:

Mat m1 = Mat(1,1, CV_64F, 0.0);
//                        ^^^^double literal

The reason your version failed is that passing 0 as fourth argument matches the overload taking a void* better than the one taking a scalar.

How to download and save an image in Android

@Droidman post is pretty comprehensive. Volley works good with small data of few kbytes. When I tried to use the 'BasicImageDownloader.java' the Android Studio gave me warning that the AsyncTask class should to be static or there could be leaks. I used Volley in another test app and that kept crashing because of leaks so I am worried about using Volley for the image downloader (images can be few 100 kB).

I used Picasso and it worked well, there is small change (probably an update on Picasso) from what is posted above. Below code worked for me:

    public static void imageDownload(Context ctx, String url){
    Picasso.get().load(yourURL)
            .into(getTarget(url));
}
private static Target getTarget(final String url){

    Target target2 = new Target() {
        @Override
        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
            new Thread(new Runnable() {

                @Override
                public void run() {

                    File file = new File(localPath + "/"+"YourImageFile.jpg");
                    try {
                        file.createNewFile();
                        FileOutputStream ostream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
                        ostream.flush();
                        ostream.close();
                    } catch (IOException e) {
                        Log.e("IOException", e.getLocalizedMessage());
                    }
                }
            }).start();
        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    };
    return target;
}

:not(:empty) CSS selector is not working?

_x000D_
_x000D_
.floating-label-input {_x000D_
  position: relative;_x000D_
  height:60px;_x000D_
}_x000D_
.floating-label-input input {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  background: transparent;_x000D_
  border: 0 none;_x000D_
  outline: none;_x000D_
  vertical-align: middle;_x000D_
  font-size: 20px;_x000D_
  font-weight: bold;_x000D_
  padding-top: 10px;_x000D_
}_x000D_
.floating-label-input label {_x000D_
  position: absolute;_x000D_
  top: calc(50% - 5px);_x000D_
  font-size: 22px;_x000D_
  left: 0;_x000D_
  color: #000;_x000D_
  transition: all 0.3s;_x000D_
}_x000D_
.floating-label-input input:focus ~ label, .floating-label-input input:focus ~ label, .floating-label-input input:valid ~ label {_x000D_
  top: 0;_x000D_
  font-size: 15px;_x000D_
  color: #33bb55;_x000D_
}_x000D_
.floating-label-input .line {_x000D_
  position: absolute;_x000D_
  height: 1px;_x000D_
  width: 100%;_x000D_
  bottom: 0;_x000D_
  background: #000;_x000D_
  left: 0;_x000D_
}_x000D_
.floating-label-input .line:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  width: 0;_x000D_
  background: #33bb55;_x000D_
  height: 1px;_x000D_
  transition: all 0.5s;_x000D_
}_x000D_
.floating-label-input input:focus ~ .line:after, .floating-label-input input:focus ~ .line:after, .floating-label-input input:valid ~ .line:after {_x000D_
  width: 100%;_x000D_
}
_x000D_
<div class="floating-label-input">_x000D_
      <input type="text" id="id" required/>_x000D_
      <label for="id" >User ID</label>_x000D_
      <span class="line"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Laravel update model with unique validation rule for attribute

Laravel 5 compatible and generic way:

I just had the same problem and solved it in a generic way. If you create an item it uses the default rules, if you update an item it will check your rules for :unique and insert an exclude automatically (if needed).

Create a BaseModel class and let all your models inherit from it:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model {

    /**
     * The validation rules for this model
     *
     * @var array
     */
    protected static $rules = [];

    /**
     * Return model validation rules
     *
     * @return array
     */
    public static function getRules() {
        return static::$rules;
    }

    /**
     * Return model validation rules for an update
     * Add exception to :unique validations where necessary
     * That means: enforce unique if a unique field changed.
     * But relax unique if a unique field did not change
     *
     * @return array;
     */
    public function getUpdateRules() {
        $updateRules = [];
        foreach(self::getRules() as $field => $rule) {
            $newRule = [];
            // Split rule up into parts
            $ruleParts = explode('|',$rule);
            // Check each part for unique
            foreach($ruleParts as $part) {
                if(strpos($part,'unique:') === 0) {
                    // Check if field was unchanged
                    if ( ! $this->isDirty($field)) {
                        // Field did not change, make exception for this model
                        $part = $part . ',' . $field . ',' . $this->getAttribute($field) . ',' . $field;
                    }
                }
                // All other go directly back to the newRule Array
                $newRule[] = $part;
            }
            // Add newRule to updateRules
            $updateRules[$field] = join('|', $newRule);

        }
        return $updateRules;
    }
}    

You now define your rules in your model like you are used to:

protected static $rules = [
    'name' => 'required|alpha|unique:roles',
    'displayName' => 'required|alpha_dash',
    'permissions' => 'array',
];

And validate them in your Controller. If the model does not validate, it will automatically redirect back to the form with the corresponding validation errors. If no validation errors occurred it will continue to execute the code after it.

public function postCreate(Request $request)
{
    // Validate
    $this->validate($request, Role::getRules());
    // Validation successful -> create role
    Role::create($request->all());
    return redirect()->route('admin.role.index');
}

public function postEdit(Request $request, Role $role)
{
    // Validate
    $this->validate($request, $role->getUpdateRules());
    // Validation successful -> update role
    $role->update($request->input());
    return redirect()->route('admin.role.index');
}

That's it! :) Note that on creation we call Role::getRules() and on edit we call $role->getUpdateRules().

How do I convert NSInteger to NSString datatype?

Modern Objective-C

An NSInteger has the method stringValue that can be used even with a literal

NSString *integerAsString1 = [@12 stringValue];

NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];

Very simple. Isn't it?

Swift

var integerAsString = String(integer)

error: ‘NULL’ was not declared in this scope

NULL is not a keyword. It's an identifier defined in some standard headers. You can include

#include <cstddef>

To have it in scope, including some other basics, like std::size_t.

Make an html number input always display 2 decimal places

an inline solution combines Groot and Ivaylo suggestions in the format below:

onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"

Extract source code from .jar file

-Covert .jar file to .zip (In windows just change the extension) -Unzip the .zip folder -You will get complete .java files

Git workflow and rebase vs merge questions

Anyway, I was following my workflow on a recent branch, and when I tried to merge it back to master, it all went to hell. There were tons of conflicts with things that should have not mattered. The conflicts just made no sense to me. It took me a day to sort everything out, and eventually culminated in a forced push to the remote master, since my local master has all conflicts resolved, but the remote one still wasn't happy.

In neither your partner's nor your suggested workflows should you have come across conflicts that didn't make sense. Even if you had, if you are following the suggested workflows then after resolution a 'forced' push should not be required. It suggests that you haven't actually merged the branch to which you were pushing, but have had to push a branch that wasn't a descendent of the remote tip.

I think you need to look carefully at what happened. Could someone else have (deliberately or not) rewound the remote master branch between your creation of the local branch and the point at which you attempted to merge it back into the local branch?

Compared to many other version control systems I've found that using Git involves less fighting the tool and allows you to get to work on the problems that are fundamental to your source streams. Git doesn't perform magic, so conflicting changes cause conflicts, but it should make it easy to do the write thing by its tracking of commit parentage.

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

Is there a function to copy an array in C/C++?

You can use the memcpy(),

void * memcpy ( void * destination, const void * source, size_t num );

memcpy() copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination.

If the destination and source overlap, then you can use memmove().

void * memmove ( void * destination, const void * source, size_t num );

memmove() copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

Webdriver Screenshot

You can use below function for relative path as absolute path is not a good idea to add in script

Import

import sys, os

Use code as below :

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'Screenshots'+ os.sep)
driver.get_screenshot_as_file(screenshotpath+"testPngFunction.png")

make sure you create the folder where the .py file is present.

os.path.join also prevent you to run your script in cross-platform like: UNIX and windows. It will generate path separator as per OS at runtime. os.sep is similar like File.separtor in java

Import numpy on pycharm

In PyCharm go to

  1. File ? Settings, or use Ctrl + Alt + S
  2. < project name > ? Project Interpreter ? gear symbol ? Add Local
  3. navigate to C:\Miniconda3\envs\my_env\python.exe, where my_env is the environment you want to use

Alternatively, in step 3 use C:\Miniconda3\python.exe if you did not create any further environments (if you never invoked conda create -n my_env python=3).

You can get a list of your current environments with conda info -e and switch to one of them using activate my_env.

AssertNull should be used or AssertNotNull

I just want to add that if you want to write special text if It null than you make it like that

  Assert.assertNotNull("The object you enter return null", str1)

Call child method from parent

You can apply that logic very easily using your child component as a react custom hook.

How to implement it?

  • Your child returns a function.

  • Your child returns a JSON: {function, HTML, or other values} as the example.

In the example doesn't make sense to apply this logic but it is easy to see:

_x000D_
_x000D_
const {useState} = React;

//Parent
const Parent = () => {
  //custome hook
  const child = useChild();

  return (
    <div>
      {child.display}          
      <button onClick={child.alert}>
        Parent call child
      </button>
      {child.btn}
    </div>
  );
};

//Child
const useChild = () => {

  const [clickCount, setClick] = React.useState(0);
  
  {/* child button*/} 
  const btn = (
    <button
      onClick={() => {
        setClick(clickCount + 1);
      }}
    >
      Click me
    </button>
  );

  return {
    btn: btn,
    //function called from parent 
    alert: () => {
      alert("You clicked " + clickCount + " times");
    },
    display: <h1>{clickCount}</h1>
  };
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
_x000D_
_x000D_
_x000D_

How to use Bootstrap modal using the anchor tag for Register?

You will have to modify the below line:

<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>

modalRegister is the ID and hence requires a preceding # for ID reference in html.

So, the modified html code snippet would be as follows:

<li><a href="#" data-toggle="modal" data-target="#modalRegister">Register</a></li>

Get time in milliseconds using C#

The DateTime.Ticks property gets the number of ticks that represent the date and time.

10,000 Ticks is a millisecond (10,000,000 ticks per second).

Is there a way to catch the back button event in javascript?

onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.

Oracle Error ORA-06512

ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).

In a comment you said

"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"

Well, your code does this:

IF ((pNum < 12) OR (pNum > 14)) THEN     
    RAISE vSOME_EX;

That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?

ORA-06510: PL/SQL: unhandled user-defined exception

If so, all you need to do is add an exception block to handle the error. Perhaps:

PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
    vSOME_EX EXCEPTION;

BEGIN 
    IF ((pNum < 12) OR (pNum > 14)) THEN     
        RAISE vSOME_EX;
    ELSE  
        EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
    END IF;
exception
    when vsome_ex then
         raise_application_error(-20000
                                 , 'This is not a valid table:  M'||pNum||'GR');

END PX;

The documentation covers handling PL/SQL exceptions in depth.

figure of imshow() is too small

Update 2020

as requested by @baxxx, here is an update because random.rand is deprecated meanwhile.

This works with matplotlip 3.2.1:

from matplotlib import pyplot as plt
import random
import numpy as np

random = np.random.random ([8,90])

plt.figure(figsize = (20,2))
plt.imshow(random, interpolation='nearest')

This plots:

enter image description here

To change the random number, you can experiment with np.random.normal(0,1,(8,90)) (here mean = 0, standard deviation = 1).

Understanding REST: Verbs, error codes, and authentication

I noticed this question a couple of days late, but I feel that I can add some insight. I hope this can be helpful towards your RESTful venture.


Point 1: Am I understanding it right?

You understood right. That is a correct representation of a RESTful architecture. You may find the following matrix from Wikipedia very helpful in defining your nouns and verbs:


When dealing with a Collection URI like: http://example.com/resources/

  • GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.

  • PUT: Meaning defined as "replace the entire collection with another collection".

  • POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.

  • DELETE: Meaning defined as "delete the entire collection".


When dealing with a Member URI like: http://example.com/resources/7HOU57Y

  • GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.

  • PUT: Update the addressed member of the collection or create it with the specified ID.

  • POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.

  • DELETE: Delete the addressed member of the collection.


Point 2: I need more verbs

In general, when you think you need more verbs, it may actually mean that your resources need to be re-identified. Remember that in REST you are always acting on a resource, or on a collection of resources. What you choose as the resource is quite important for your API definition.

Activate/Deactivate Login: If you are creating a new session, then you may want to consider "the session" as the resource. To create a new session, use POST to http://example.com/sessions/ with the credentials in the body. To expire it use PUT or a DELETE (maybe depending on whether you intend to keep a session history) to http://example.com/sessions/SESSION_ID.

Change Password: This time the resource is "the user". You would need a PUT to http://example.com/users/USER_ID with the old and new passwords in the body. You are acting on "the user" resource, and a change password is simply an update request. It's quite similar to the UPDATE statement in a relational database.

My instinct would be to do a GET call to a URL like /api/users/1/activate_login

This goes against a very core REST principle: The correct usage of HTTP verbs. Any GET request should never leave any side effect.

For example, a GET request should never create a session on the database, return a cookie with a new Session ID, or leave any residue on the server. The GET verb is like the SELECT statement in a database engine. Remember that the response to any request with the GET verb should be cache-able when requested with the same parameters, just like when you request a static web page.


Point 3: How to return error messages and codes

Consider the 4xx or 5xx HTTP status codes as error categories. You can elaborate the error in the body.

Failed to Connect to Database: / Incorrect Database Login: In general you should use a 500 error for these types of errors. This is a server-side error. The client did nothing wrong. 500 errors are normally considered "retryable". i.e. the client can retry the same exact request, and expect it to succeed once the server's troubles are resolved. Specify the details in the body, so that the client will be able to provide some context to us humans.

The other category of errors would be the 4xx family, which in general indicate that the client did something wrong. In particular, this category of errors normally indicate to the client that there is no need to retry the request as it is, because it will continue to fail permanently. i.e. the client needs to change something before retrying this request. For example, "Resource not found" (HTTP 404) or "Malformed Request" (HTTP 400) errors would fall in this category.


Point 4: How to do authentication

As pointed out in point 1, instead of authenticating a user, you may want to think about creating a session. You will be returned a new "Session ID", along with the appropriate HTTP status code (200: Access Granted or 403: Access Denied).

You will then be asking your RESTful server: "Can you GET me the resource for this Session ID?".

There is no authenticated mode - REST is stateless: You create a session, you ask the server to give you resources using this Session ID as a parameter, and on logout you drop or expire the session.

How do I get the current location of an iframe?

You can use Ra-Ajax and have an iframe wrapped inside e.g. a Window control. Though in general terms I don't encourage people to use iframes (for anything)

Another alternative is to load the HTML on the server and send it directly into the Window as the content of a Label or something. Check out how this Ajax RSS parser is loading the RSS items in the source which can be downloaded here (Open Source - LGPL)

(Disclaimer; I work with Ra-Ajax...)

Maximum number of threads in a .NET app?

I would recommend running ThreadPool.GetMaxThreads method in debug

ThreadPool.GetMaxThreads(out int workerThreadsCount, out int ioThreadsCount);

Docs and examples: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool.getmaxthreads?view=netframework-4.8

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

I had this issue and the cause was actually a NullPointerException. But it was not presented to me as one!

my Output: screen was stuck for a very long period and ANR

My State : the layout xml file was included another layout, but referenced the included view without giving id in the attached layout. (i had two more similar implementations of the same child view, so the resource id was created with the given name)

Note : it was a Custom Dialog layout, so checking dialogs first may help a bit

Conclusion : There is some memory leak happened on searching the id of the child view.

Including external jar-files in a new jar-file build with Ant

I'm using NetBeans and needed a solution for this also. After googleling around and starting from Christopher's answer i managed to build a script that helps you easily do this in NetBeans. I'm putting the instructions here in case someone else will need them.

What you have to do is download one-jar. You can use the link from here: http://one-jar.sourceforge.net/index.php?page=getting-started&file=ant Extract the jar archive and look for one-jar\dist folder that contains one-jar-ant-task-.jar, one-jar-ant-task.xml and one-jar-boot-.jar. Extract them or copy them to a path that we will add to the script below, as the value of the property one-jar.dist.dir.

Just copy the following script at the end of your build.xml script (from your NetBeans project), just before /project tag, replace the value for one-jar.dist.dir with the correct path and run one-jar target.

For those of you that are unfamiliar with running targets, this tutorial might help: http://www.oracle.com/technetwork/articles/javase/index-139904.html . It also shows you how to place sources into one jar, but they are exploded, not compressed into jars.

<property name="one-jar.dist.dir" value="path\to\one-jar-ant"/>
<import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />

<target name="one-jar" depends="jar">
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<property name="src.dir"          value="src"/>
<property name="bin.dir"          value="bin"/>
<property name="build.dir"        value="build"/>
<property name="dist.dir"         value="dist"/>
<property name="external.lib.dir" value="${dist.dir}/lib"/>
<property name="classes.dir"      value="${build.dir}/classes"/>
<property name="jar.target.dir"   value="${build.dir}/jars"/>
<property name="final.jar"        value="${dist.dir}/${ant.project.name}.jar"/>
<property name="main.class"       value="${main.class}"/>

<path id="project.classpath">
    <fileset dir="${external.lib.dir}">
        <include name="*.jar"/>
    </fileset>
</path>

<mkdir dir="${bin.dir}"/>
<!-- <mkdir dir="${build.dir}"/> -->
<!-- <mkdir dir="${classes.dir}"/> -->
<mkdir dir="${jar.target.dir}"/>
<copy includeemptydirs="false" todir="${classes.dir}">
    <fileset dir="${src.dir}">
        <exclude name="**/*.launch"/>
        <exclude name="**/*.java"/>
    </fileset>
</copy>

<!-- <echo message="${ant.project.name}: ${ant.file}"/> -->
<javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
    <src path="${src.dir}"/>
    <classpath refid="project.classpath"/>   
</javac>

<delete file="${final.jar}" />
<one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
    <main>
        <fileset dir="${classes.dir}"/>
    </main>
    <lib>
        <fileset dir="${external.lib.dir}" />
    </lib>
</one-jar>

<delete dir="${jar.target.dir}"/>
<delete dir="${bin.dir}"/>
<delete dir="${external.lib.dir}"/>

</target>

Best of luck and don't forget to vote up if it helped you.

Component is part of the declaration of 2 modules

You may just try this solution ( for Ionic 3 )

In my case, this error happen when i call a page by using the following code

 this.navCtrl.push("Login"); // Bug

I just removed the quotes like the following and also imported that page on the top of the file which i used call the Login page

this.navCtrl.push(Login); // Correct

I can't explain the difference at this time since i'm a beginner level developer

Sending event when AngularJS finished loading

If you don't use ngRoute module, i.e. you don't have $viewContentLoaded event.

You can use another directive method:

    angular.module('someModule')
        .directive('someDirective', someDirective);

    someDirective.$inject = ['$rootScope', '$timeout']; //Inject services

    function someDirective($rootScope, $timeout){
        return {
            restrict: "A",
            priority: Number.MIN_SAFE_INTEGER, //Lowest priority
            link    : function(scope, element, attr){
                $timeout(
                    function(){
                        $rootScope.$emit("Some:event");
                    }
                );
            }
        };
    }

Accordingly to trusktr's answer it has lowest priority. Plus $timeout will cause Angular to run through an entire event loop before callback execution.

$rootScope used, because it allow to place directive in any scope of the application and notify only necessary listeners.

$rootScope.$emit will fire an event for all $rootScope.$on listeners only. The interesting part is that $rootScope.$broadcast will notify all $rootScope.$on as well as $scope.$on listeners Source

Do a "git export" (like "svn export")?

Doing it the easy way, this is a function for .bash_profile, it directly unzips the archive on current location, configure first your usual [url:path]. NOTE: With this function you avoid the clone operation, it gets directly from the remote repo.

gitss() {
    URL=[url:path]

    TMPFILE="`/bin/tempfile`"
    if [ "$1" = "" ]; then
        echo -e "Use: gitss repo [tree/commit]\n"
        return
    fi
    if [ "$2" = "" ]; then
        TREEISH="HEAD"
    else
        TREEISH="$2"
    fi
    echo "Getting $1/$TREEISH..."
    git archive --format=zip --remote=$URL/$1 $TREEISH > $TMPFILE && unzip $TMPFILE && echo -e "\nDone\n"
    rm $TMPFILE
}

Alias for .gitconfig, same configuration required (TAKE CARE executing the command inside .git projects, it ALWAYS jumps to the base dir previously as said here, until this is fixed I personally prefer the function

ss = !env GIT_TMPFILE="`/bin/tempfile`" sh -c 'git archive --format=zip --remote=[url:path]/$1 $2 \ > $GIT_TMPFILE && unzip $GIT_TMPFILE && rm $GIT_TMPFILE' -

possible EventEmitter memory leak detected

Put this in the first line of your server.js (or whatever contains your main Node.js app):

require('events').EventEmitter.prototype._maxListeners = 0;

and the error goes away :)

Pass Parameter to Gulp Task

It's a feature programs cannot stay without. You can try yargs.

npm install --save-dev yargs

You can use it like this:

gulp mytask --production --test 1234

In the code, for example:

var argv = require('yargs').argv;
var isProduction = (argv.production === undefined) ? false : true;

For your understanding:

> gulp watch
console.log(argv.production === undefined);  <-- true
console.log(argv.test === undefined);        <-- true

> gulp watch --production
console.log(argv.production === undefined);  <-- false
console.log(argv.production);                <-- true
console.log(argv.test === undefined);        <-- true
console.log(argv.test);                      <-- undefined

> gulp watch --production --test 1234
console.log(argv.production === undefined);  <-- false
console.log(argv.production);                <-- true
console.log(argv.test === undefined);        <-- false
console.log(argv.test);                      <-- 1234

Hope you can take it from here.

There's another plugin that you can use, minimist. There's another post where there's good examples for both yargs and minimist: (Is it possible to pass a flag to Gulp to have it run tasks in different ways?)

How to return a dictionary | Python


def query(id):
    for line in file:
        table = line.split(";")
        if id == int(table[0]):
             yield table
    
    

id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
  print("ID: " + id_)
  print("Name: " + name)
  print("City: " + city)
file.close()

Using yield..

Mod in Java produces negative numbers

The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.

You can find the positive value by doing this:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;

(obviously -1 or 2 can be whatever you want the numerator or denominator to be)

getActivity() returns null in Fragment function

Do as follows. I think it will be helpful to you.

private boolean isVisibleToUser = false;
private boolean isExecutedOnce = false;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_my, container, false);
    if (isVisibleToUser && !isExecutedOnce) {
        executeWithActivity(getActivity());
    }
    return root;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    this.isVisibleToUser = isVisibleToUser;
    if (isVisibleToUser && getActivity()!=null) {
        isExecutedOnce =true;
        executeWithActivity(getActivity());
    }
}


private void executeWithActivity(Activity activity){
    //Do what you have to do when page is loaded with activity

}

How to change Apache Tomcat web server port number

1) Locate server.xml in {Tomcat installation folder}\ conf \ 2) Find following similar statement

       <!-- Define a non-SSL HTTP/1.1 Connector on port 8180 -->
      <Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

For example

<Connector port="8181" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Edit and save the server.xml file. Restart Tomcat. Done

Further reference: http://www.mkyong.com/tomcat/how-to-change-tomcat-default-port/

How do you show animated GIFs on a Windows Form (c#)

Note that in Windows, you traditionally don't use animated Gifs, but little AVI animations: there is a Windows native control just to display them. There are even tools to convert animated Gifs to AVI (and vice-versa).

What does it mean: The serializable class does not declare a static final serialVersionUID field?

it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...)

That's not correct, and you will be unable to cite an authoriitative source for that claim. It should be changed whenever you make a change that is incompatible under the rules given in the Versioning of Serializable Objects section of the Object Serialization Specification, which specifically does not include additional fields or change of field order, and when you haven't provided readObject(), writeObject(), and/or readResolve() or /writeReplace() methods and/or a serializableFields declaration that could cope with the change.

Split value from one field to two

If your plan is to do this as part of a query, please don't do that (a). Seriously, it's a performance killer. There may be situations where you don't care about performance (such as one-off migration jobs to split the fields allowing better performance in future) but, if you're doing this regularly for anything other than a mickey-mouse database, you're wasting resources.

If you ever find yourself having to process only part of a column in some way, your DB design is flawed. It may well work okay on a home address book or recipe application or any of myriad other small databases but it will not be scalable to "real" systems.

Store the components of the name in separate columns. It's almost invariably a lot faster to join columns together with a simple concatenation (when you need the full name) than it is to split them apart with a character search.

If, for some reason you cannot split the field, at least put in the extra columns and use an insert/update trigger to populate them. While not 3NF, this will guarantee that the data is still consistent and will massively speed up your queries. You could also ensure that the extra columns are lower-cased (and indexed if you're searching on them) at the same time so as to not have to fiddle around with case issues.

And, if you cannot even add the columns and triggers, be aware (and make your client aware, if it's for a client) that it is not scalable.


(a) Of course, if your intent is to use this query to fix the schema so that the names are placed into separate columns in the table rather than the query, I'd consider that to be a valid use. But I reiterate, doing it in the query is not really a good idea.

PHP Redirect to another page after form submit

Right after @mail($email_to, $email_subject, $email_message, $headers);

header('Location: nextpage.php');

Note that you will never see 'Thanks for subscribing to our mailing list'

That should be on the next page, if you echo any text you will get an error because the headers would have been already created, if you want to redirect never return any text, not even a space!

how to display a javascript var in html body

Use document.write().

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    var number = 123;_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <h1>_x000D_
      the value for number is:_x000D_
      <script type="text/javascript">_x000D_
        document.write(number)_x000D_
      </script>_x000D_
    </h1>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How does java do modulus calculations with negative numbers?

Are you sure you are working in Java? 'cause Java gives -13 % 64 = -13 as expected. The sign of dividend!

HTML 5 Video "autoplay" not automatically starting in CHROME

Extremeandy has mentioned as of Chrome 66 autoplay video has been disabled.

After looking into this I found that muted videos are still able to be autoplayed. In my case the video didn't have any audio, but adding muted to the video tag has fixed it:

Hopefully this will help others also.

Execute multiple command lines with the same process using .NET

ProcessStartInfo pStartInfo = new ProcessStartInfo();
pStartInfo.FileName = "CMD";
pStartInfo.Arguments = @"/C mysql --user=root --password=sa casemanager && \. " + Environment.CurrentDirectory + @"\MySQL\CaseManager.sql"
pStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pStartInfo);

The && is the way to tell the command shell that there is another command to execute.

How to select last one week data from today's date

  1. The query is correct

2A. As far as last seven days have much less rows than whole table an index can help

2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size

How do I download a binary file over HTTP?

I know that this is an old question, but Google threw me here and I think I found a simpler answer.

In Railscasts #179, Ryan Bates used the Ruby standard class OpenURI to do much of what was asked like this:

(Warning: untested code. You might need to change/tweak it.)

require 'open-uri'

File.open("/my/local/path/sample.flv", "wb") do |saved_file|
  # the following "open" is provided by open-uri
  open("http://somedomain.net/flv/sample/sample.flv", "rb") do |read_file|
    saved_file.write(read_file.read)
  end
end

TypeError: $.ajax(...) is not a function?

This is too late for an answer but this response may be helpful for future readers.

I would like to share a scenario where, say there are multiple html files(one base html and multiple sub-HTMLs) and $.ajax is being used in one of the sub-HTMLs.

Suppose in the sub-HTML, js is included via URL "https://code.jquery.com/jquery-3.5.0.js" and in the base/parent HTML, via URL -"https://code.jquery.com/jquery-3.1.1.slim.min.js", then the slim version of JS will be used across all pages which use this sub-HTML as well as the base HTML mentioned above.

This is especially true in case of using bootstrap framework which loads js using "https://code.jquery.com/jquery-3.1.1.slim.min.js".

So to resolve the problem, need to ensure that in all pages, js is included via URL "https://code.jquery.com/jquery-3.5.0.js" or whatever is the latest URL containing all JQuery libraries.

Thanks to Lily H. for pointing me towards this answer.

Loading custom functions in PowerShell

I kept using this all this time

Import-module .\build_functions.ps1 -Force

How to know the git username and email saved during configuration?

If you want to check or set the user name and email you can use the below command

Check user name

git config user.name

Set user name

git config user.name "your_name"

Check your email

git config user.email

Set/change your email

git config user.email "[email protected]"

List/see all configuration

git config --list

Multidimensional arrays in Swift

Your original logic for creating the matrix is indeed correct, and it even works in Swift 2. The problem is that in the print loop, you have the row and column variables reversed. If you change it to:

for row in 0...2 {
  for column in 0...2 {
    print("column: \(column) row: \(row) value:\(array[column][row])")

  }
}

you will get the correct results. Hope this helps!

How to get the unique ID of an object which overrides hashCode()?

I came up with this solution which works in my case where I have objects created on multiple threads and are serializable:

public abstract class ObjBase implements Serializable
    private static final long serialVersionUID = 1L;
    private static final AtomicLong atomicRefId = new AtomicLong();

    // transient field is not serialized
    private transient long refId;

    // default constructor will be called on base class even during deserialization
    public ObjBase() {
       refId = atomicRefId.incrementAndGet()
    }

    public long getRefId() {
        return refId;
    }
}

How to import a JSON file in ECMAScript 6?

Adding to the other answers, in Node.js it is possible to use require to read JSON files even inside ES modules. I found this to be especially useful when reading files inside other packages, because it takes advantage of Node's own module resolution strategy to locate the file.

require in an ES module must be first created with createRequire.

Here is a complete example:

import { createRequire } from 'module';

const require = createRequire(import.meta.url);
const packageJson = require('typescript/package.json');
console.log(`You have TypeScript version ${packageJson.version} installed.`);

In a project with TypeScript installed, the code above will read and print the TypeScript version number from package.json.

Getting path relative to the current working directory?

If you don't mind the slashes being switched, you could [ab]use Uri:

Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath = 
Uri.UnescapeDataString(
    folder.MakeRelativeUri(file)
        .ToString()
        .Replace('/', Path.DirectorySeparatorChar)
    );

As a function/method:

string GetRelativePath(string filespec, string folder)
{
    Uri pathUri = new Uri(filespec);
    // Folders must end in a slash
    if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
    {
        folder += Path.DirectorySeparatorChar;
    }
    Uri folderUri = new Uri(folder);
    return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}

How to query MongoDB with "like"?

Just in case, someone is looking for a sql LIKE kind of query for a key that holds an Array of Strings instead of a String, here it is:

db.users.find({"name": {$in: [/.*m.*/]}})

'printf' vs. 'cout' in C++

With primitives, it probably doesn't matter entirely which one you use. I say where it gets usefulness is when you want to output complex objects.

For example, if you have a class,

#include <iostream>
#include <cstdlib>

using namespace std;

class Something
{
public:
        Something(int x, int y, int z) : a(x), b(y), c(z) { }
        int a;
        int b;
        int c;

        friend ostream& operator<<(ostream&, const Something&);
};

ostream& operator<<(ostream& o, const Something& s)
{
        o << s.a << ", " << s.b << ", " << s.c;
        return o;
}

int main(void)
{
        Something s(3, 2, 1);

        // output with printf
        printf("%i, %i, %i\n", s.a, s.b, s.c);

        // output with cout
        cout << s << endl;

        return 0;
}

Now the above might not seem all that great, but let's suppose you have to output this in multiple places in your code. Not only that, let's say you add a field "int d." With cout, you only have to change it in once place. However, with printf, you'd have to change it in possibly a lot of places and not only that, you have to remind yourself which ones to output.

With that said, with cout, you can reduce a lot of times spent with maintenance of your code and not only that if you re-use the object "Something" in a new application, you don't really have to worry about output.

Convert Dictionary to JSON in Swift

Swift 5:

extension Dictionary {
    
    /// Convert Dictionary to JSON string
    /// - Throws: exception if dictionary cannot be converted to JSON data or when data cannot be converted to UTF8 string
    /// - Returns: JSON string
    func toJson() throws -> String {
        let data = try JSONSerialization.data(withJSONObject: self)
        if let string = String(data: data, encoding: .utf8) {
            return string
        }
        throw NSError(domain: "Dictionary", code: 1, userInfo: ["message": "Data cannot be converted to .utf8 string"])
    }
}

Cannot make a static reference to the non-static method

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

class Test {
     string somedata = "99";
     string getText() { return somedata; } 
     static string TTT = "0";
}

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

What are the values?

Well

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?