Programs & Examples On #Sieve of eratosthenes

Sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to a specified integer.

Program to find prime numbers

Very similar - from an exercise to implement Sieve of Eratosthenes in C#:

public class PrimeFinder
{
    readonly List<long> _primes = new List<long>();

    public PrimeFinder(long seed)
    {
        CalcPrimes(seed);
    }

    public List<long> Primes { get { return _primes; } }

    private void CalcPrimes(long maxValue)
    {
        for (int checkValue = 3; checkValue <= maxValue; checkValue += 2)
        {
            if (IsPrime(checkValue))
            {
                _primes.Add(checkValue);
            }
        }
    }

    private bool IsPrime(long checkValue)
    {
        bool isPrime = true;

        foreach (long prime in _primes)
        {
            if ((checkValue % prime) == 0 && prime <= Math.Sqrt(checkValue))
            {
                isPrime = false;
                break;
            }
        }
        return isPrime;
    }
}

Sieve of Eratosthenes - Finding Primes Python

My implementation:

import math
n = 100
marked = {}
for i in range(2, int(math.sqrt(n))):
    if not marked.get(i):
        for x in range(i * i, n, i):
            marked[x] = True

for i in range(2, n):
    if not marked.get(i):
        print i

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

I got this error running from VS. Turned out I'd opened a solution without running Visual Studio as admin. Closing Visual studio down and running it again as admin then rebuilding solved this for me.

Hope that helps someone.

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

$date = "2014-04-01 12:00:00";

preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$date, $matches);

print_r($matches);

$matches will be:

Array ( 
   [0] => 2014-04-01 12:00:00 
   [1] => 2014 
   [2] => 04 
   [3] => 01 
   [4] => 12 
   [5] => 00 
   [6] => 00
)

An easy way to break up a datetime formated string.

How to use moment.js library in angular 2 typescript app?

Not sure if this is still an issue for people, however... Using SystemJS and MomentJS as library, this solved it for me

/*
 * Import Custom Components
 */
import * as moment from 'moment/moment'; // please use path to moment.js file, extension is set in system.config

// under systemjs, moment is actually exported as the default export, so we account for that
const momentConstructor: (value?: any) => moment.Moment = (<any>moment).default || moment;

Works fine from there for me.

Why use Gradle instead of Ant or Maven?

Gradle put the fun back into building/assembling software. I used ant to build software my entire career and I have always considered the actual "buildit" part of the dev work being a necessary evil. A few months back our company grew tired of not using a binary repo (aka checking in jars into the vcs) and I was given the task to investigate this. Started with ivy since it could be bolted on top of ant, didn't have much luck getting my built artifacts published like I wanted. I went for maven and hacked away with xml, worked splendid for some simple helper libs but I ran into serious problems trying to bundle applications ready for deploy. Hassled quite a while googling plugins and reading forums and wound up downloading trillions of support jars for various plugins which I had a hard time using. Finally I went for gradle (getting quite bitter at this point, and annoyed that "It shouldn't be THIS hard!")

But from day one my mood started to improve. I was getting somewhere. Took me like two hours to migrate my first ant module and the build file was basically nothing. Easily fitted one screen. The big "wow" was: build scripts in xml, how stupid is that? the fact that declaring one dependency takes ONE row is very appealing to me -> you can easily see all dependencies for a certain project on one page. From then on I been on a constant roll, for every problem I faced so far there is a simple and elegant solution. I think these are the reasons:

  • groovy is very intuitive for java developers
  • documentation is great to awesome
  • the flexibility is endless

Now I spend my days trying to think up new features to add to our build process. How sick is that?

Oracle: how to UPSERT (update or insert into a table?)

None of the answers given so far is safe in the face of concurrent accesses, as pointed out in Tim Sylvester's comment, and will raise exceptions in case of races. To fix that, the insert/update combo must be wrapped in some kind of loop statement, so that in case of an exception the whole thing is retried.

As an example, here's how Grommit's code can be wrapped in a loop to make it safe when run concurrently:

PROCEDURE MyProc (
 ...
) IS
BEGIN
 LOOP
  BEGIN
    MERGE INTO Employee USING dual ON ( "id"=2097153 )
      WHEN MATCHED THEN UPDATE SET "last"="smith" , "name"="john"
      WHEN NOT MATCHED THEN INSERT ("id","last","name") 
        VALUES ( 2097153,"smith", "john" );
    EXIT; -- success? -> exit loop
  EXCEPTION
    WHEN NO_DATA_FOUND THEN -- the entry was concurrently deleted
      NULL; -- exception? -> no op, i.e. continue looping
    WHEN DUP_VAL_ON_INDEX THEN -- an entry was concurrently inserted
      NULL; -- exception? -> no op, i.e. continue looping
  END;
 END LOOP;
END; 

N.B. In transaction mode SERIALIZABLE, which I don't recommend btw, you might run into ORA-08177: can't serialize access for this transaction exceptions instead.

How to Deserialize XML document

Here's a working version. I changed the XmlElementAttribute labels to XmlElement because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the reader.ReadToEnd(); (that function reads the whole stream and returns a string, so the Deserialize() function couldn't use the reader anymore...the position was at the end of the stream). I also took a few liberties with the naming :).

Here are the classes:

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement("StockNumber")]
    public string StockNumber { get; set; }

    [System.Xml.Serialization.XmlElement("Make")]
    public string Make { get; set; }

    [System.Xml.Serialization.XmlElement("Model")]
    public string Model { get; set; }
}


[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
    [XmlArray("Cars")]
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }
}

The Deserialize function:

CarCollection cars = null;
string path = "cars.xml";

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

And the slightly tweaked xml (I needed to add a new element to wrap <Cars>...Net is picky about deserializing arrays):

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

jQuery Loop through each div

Just as we refer to scrolling class

$( ".scrolling" ).each( function(){
    var img = $( "img", this );
    $(this).width( img.width() * img.length * 1.2 ) 
})

window.open(url, '_blank'); not working on iMac/Safari

window.location.assign(url) this fixs the window.open(url) issue in ios devices

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

How can I download a specific Maven artifact in one command line?

To copy artifact in specified location use copy instead of get.

mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.2:copy \
  -DrepoUrl=someRepositoryUrl \
  -Dartifact="com.acme:foo:RELEASE:jar" -Dmdep.stripVersion -DoutputDirectory=/tmp/

Remove all occurrences of char from string

Using

public String replaceAll(String regex, String replacement)

will work.

Usage would be str.replace("X", "");.

Executing

"Xlakjsdf Xxx".replaceAll("X", "");

returns:

lakjsdf xx

How can I update my ADT in Eclipse?

Reason to that is with the new update, they changed the URL for the Android Developer Tools update site to require HTTPS. If you are updating ADT, make sure you use HTTPS in the URL for the Android Developer Tools update site.

Merging cells in Excel using Apache POI

syntax is:

sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

Example:

sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));

Here the cell 0 to cell 5 will be merged of the 4th row.

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Difference between matches() and find() in Java Regex

matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.

How to remove all numbers from string?

Use some regex like [0-9] or \d:

$words = preg_replace('/\d+/', '', $words );

You might want to read the preg_replace() documentation as this is directly shown there.

C#: Dynamic runtime cast

Slight modification on @JRodd version to support objects coming from Json (JObject)

public static dynamic ToDynamic(this object value)
    {
        IDictionary<string, object> expando = new ExpandoObject();

        //Get the type of object 
        Type t = value.GetType();

        //If is Dynamic Expando object
        if (t.Equals(typeof(ExpandoObject)))
        {
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
                expando.Add(property.Name, property.GetValue(value));
        }
        //If coming from Json object
        else if (t.Equals(typeof(JObject)))
        {
            foreach (JProperty property in (JToken)value)
                expando.Add(property.Name, property.Value);
        }
        else //Try converting a regular object
        {
            string str = JsonConvert.SerializeObject(value);
            ExpandoObject obj = JsonConvert.DeserializeObject<ExpandoObject>(str);

            return obj;
        }

       

        return expando as ExpandoObject;
    }

Auto populate columns in one sheet from another sheet

Use the 'EntireColumn' property, that's what it is there for. C# snippet, but should give you a good indication of how to do this:

string rangeQuery = "A1:A1";

Range range = workSheet.get_Range(rangeQuery, Type.Missing);

range = range.EntireColumn;

Correct path for img on React.js

Some older answers din't work, others are good but won't explain the theme, in summary:

If image is in 'public' directory

Example: \public\charts\a.png

In html:

<img id="imglogo" src="/charts/logo.svg" />

In JavaScript:

Create image to new img, dynamically:

var img1 = document.createElement("img");  
img1.src = 'charts/a.png';  

Set image to existing img with id as 'img1', dynamically:

document.getElementById('img1').src = 'charts/a.png';

If image is in 'src' directory:

Example: \src\logo.svg

In JavaScript:

import logo from './logo.svg';  
img1.src = logo;  

In jsx:

<img src={logo} /> 

In Unix, how do you remove everything in the current directory and below it?

Will delete all files/directories below the current one.

find -mindepth 1 -delete

If you want to do the same with another directory whose name you have, you can just name that

find <name-of-directory> -mindepth 1 -delete

If you want to remove not only the sub-directories and files of it, but also the directory itself, omit -mindepth 1. Do it without the -delete to get a list of the things that will be removed.

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

SQLite: How do I save the result of a query as a CSV file?

To include column names to your csv file you can do the following:

sqlite> .headers on
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

To verify the changes that you have made you can run this command:

sqlite> .show

Output:

echo: off   
explain: off   
headers: on   
mode: csv   
nullvalue: ""  
output: stdout  
separator: "|"   
stats: off   
width: 22 18 

How do I create a Java string from the contents of a file?

This one uses the method RandomAccessFile.readFully, it seems to be available from JDK 1.0 !

public static String readFileContent(String filename, Charset charset) throws IOException {
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(filename, "r");
        byte[] buffer = new byte[(int)raf.length()];
        raf.readFully(buffer);
        return new String(buffer, charset);
    } finally {
        closeStream(raf);
    }
} 


private static void closeStream(Closeable c) {
    if (c != null) {
        try {
            c.close();
        } catch (IOException ex) {
            // do nothing
        }
    }
}

Binding a Button's visibility to a bool value in ViewModel

In View:

<Button
 Height="50" Width="50"
 Style="{StaticResource MyButtonStyle}"
 Command="{Binding SmallDisp}" CommandParameter="{Binding}" 
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>

In view Model:

public _advancedFormat = Visibility.visible (whatever you start with)

public Visibility AdvancedFormat
{
 get{return _advancedFormat;}
 set{
   _advancedFormat = value;
   //raise property changed here
}

You will need to have a property changed event

 protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
    { 
        PropertyChanged.Raise(this, e); 
    } 

    protected void OnPropertyChanged(string propertyName) 
    { 
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 
    } 

This is how they use Model-view-viewmodel

But since you want it binded to a boolean, You will need some converter. Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

The solution needs to add these headers to the server response.

'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT'

If you have access to the server, you can add them and this will solve your problem

OR

You can try concatentaing this in front of the url:

https://cors-anywhere.herokuapp.com/

What is the default text size on Android?

You can find standard sizes for everything in Google's style guide.

Here are the values they use for for buttons:

Buttons

English: Medium 14sp, all caps

Dense: Medium 15sp, all caps

Tall: Bold 15sp

installing urllib in Python3.6

urllib is a standard library, you do not have to install it. Simply import urllib

How do I concatenate two text files in PowerShell?

You can do something like:

get-content input_file1 > output_file
get-content input_file2 >> output_file

Where > is an alias for "out-file", and >> is an alias for "out-file -append".

Create ul and li elements in javascript.

Try out below code snippet:

 var list = [];
 var text;

function update() {
    console.log(list);    

    for (var i = 0; i < list.length; i++) {
       console.log( i );
       var letters;
       var ul = document.getElementById("list");
       var li = document.createElement("li");

       li.appendChild(document.createTextNode(list[i]));
       ul.appendChild(li);

       letters += "<li>"  + list[i] + "</li>";
    }

 document.getElementById("list").innerHTML = letters;

}

function myFunction() {
    text = prompt("enter TODO");  
    list.push(text);
    update();
}   

select2 changing items dynamically

Try using the trigger property for this:

$('select').select2().trigger('change');

How do I accomplish an if/else in mustache.js?

This is how you do if/else in Mustache (perfectly supported):

{{#repo}}
  <b>{{name}}</b>
{{/repo}}
{{^repo}}
  No repos :(
{{/repo}}

Or in your case:

{{#author}}
  {{#avatar}}
    <img src="{{avatar}}"/>
  {{/avatar}}
  {{^avatar}}
    <img src="/images/default_avatar.png" height="75" width="75" />
  {{/avatar}}
{{/author}}

Look for inverted sections in the docs: https://github.com/janl/mustache.js

Can't Autowire @Repository annotated interface in Spring Boot

I had the same issues with Repository not being found. So what I did was to move everything into 1 package. And this worked meaning that there was nothing wrong with my code. I moved the Repos & Entities into another package and added the following to SpringApplication class.

@EnableJpaRepositories("com...jpa")
@EntityScan("com...jpa")

After that, I moved the Service (interface & implementation) to another package and added the following to SpringApplication class.

@ComponentScan("com...service")

This solved my issues.

Cannot construct instance of - Jackson

You cannot instantiate an abstract class, Jackson neither. You should give Jackson information on how to instantiate MyAbstractClass with a concrete type.

See this answer on stackoverflow: Jackson JSON library: how to instantiate a class that contains abstract fields

And maybe also see Jackson Polymorphic Deserialization

Pandas group-by and sum

Also you can use agg function,

df.groupby(['Name', 'Fruit'])['Number'].agg('sum')

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

If You Are Able to Edit the Offending Stylesheet

If the user-agent stylesheet's style is causing problems for the browser it's supposed to fix, then you could try removing the offending style and testing that to ensure it doesn't have any unexpected adverse effects elsewhere.

If it doesn't, use the modified stylesheet. Fixing browser quirks is what these sheets are for - they fix issues, they aren't supposed to introduce new ones.

If You Are Not Able to Edit the Offending Stylesheet

If you're unable to edit the stylesheet that contains the offending line, you may consider using the !important keyword.

An example:

.override {
    border: 1px solid #000 !important;
}

.a_class {
    border: 2px solid red;
}

And the HTML:

<p class="a_class">content will have 2px red border</p>
<p class="override a_class">content will have 1px black border</p>

Live example

Try to use !important only where you really have to - if you can reorganize your styles such that you don't need it, this would be preferable.

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

It should look like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')  # Last I checked this was necessary.
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

This works for me using Python 3.6, I'm sure it'll work for 2.7 too.

Update 2018-10-26: These days you can just do this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

Updating records codeigniter

In codeigniter doc if you update specific field just do this

$data = array(
    'yourfieldname' => value,
    'name' => $name,
    'date' => $date
);

$this->db->where('yourfieldname', yourfieldvalue);
$this->db->update('yourtablename', $data);

Getting current directory in .NET web application

Use this code:

 HttpContext.Current.Server.MapPath("~")

Detailed Reference:

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

Server.MapPath(null) and Server.MapPath("") will produce this effect too.

Shell - Write variable contents to a file

All of the above work, but also have to work around a problem (escapes and special characters) that doesn't need to occur in the first place: Special characters when the variable is expanded by the shell. Just don't do that (variable expansion) in the first place. Use the variable directly, without expansion.

Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.

Use this:

printenv var >file

That means, in case of the OP question:

printenv var >"$destfile"

Note: variable names are case sensitive.

Download a file by jQuery.Ajax

I struggled with this issue for a long time. Finally an elegant external library suggested here helped me out.

How to remove the border highlight on an input text element

None of the solutions worked for me in Firefox.

The following solution changes the border style on focus for Firefox and sets the outline to none for other browsers.

I've effectively made the focus border go from a 3px blue glow to a border style that matches the text area border. Here's some border styles:

Dashed border (border 2px dashed red): Dashed border. border 2px dashed red

No border! (border 0px):
No border. border:0px

Textarea border (border 1px solid gray): Textarea border. border 1px solid gray

Here is the code:

_x000D_
_x000D_
input:focus, textarea:focus {_x000D_
    outline: none; /** For Safari, etc **/_x000D_
    border:1px solid gray; /** For Firefox **/_x000D_
}_x000D_
_x000D_
#textarea  {_x000D_
  position:absolute;_x000D_
  top:10px;_x000D_
  left:10px;_x000D_
  right:10px;_x000D_
  width:calc(100% - 20px);_x000D_
  height:160px;_x000D_
  display:inline-block;_x000D_
  margin-top:-0.2em;_x000D_
}
_x000D_
<textarea id="textarea">yo</textarea>
_x000D_
_x000D_
_x000D_

selected value get from db into dropdown select box option using php mysql error

USING POD

<?php
$username = "root";
$password = "";
$db = "db_name";

$dns = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
    $conn = new PDO($dns,$username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "select * from mine where username = ? ";

    $stmt1 = $conn->prepare($sql);
    $stmt1 -> execute(array($_POST['user']));
    $all = $stmt1->fetchAll(); ?>

    <div class="controls">
        <select  data-rel="chosen"  name="degree_id" id="selectError">

                 <?php foreach($all as $nt) { echo "<option value =$nt[id]>$nt[name]</option>";}?>
        </select>

    </div>

C++ int float casting

When doing integer division, the result will always be a integer unless one or more of the operands are a float. Just type cast one/both of the operands to a float and the compiler will do the conversion. Type casting is used when you want the arithmetic to perform as it should so the result will be the correct data type.

float m = static_cast<float>(a.y - b.y) / (a.x - b.x);

Flutter.io Android License Status Unknown

I found this solution for having to use JDK 8 (you need an account to download now!) - use the embedded OpenJDK that comes with Android Studio:

Add this to your ~/.profile or similar:

# Use the JDK embedded with Android Studio for command-line builds
export JAVA_HOME='/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home'

Command-line builds via gradlew, and any other well-behaved script, will then use the version of the SDK that ships with Android Studio 2.2+.

*My Mac was still using the default Java 7.

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

Do not use the command prompt in the IDE. Run the command prompt from windows as an administrator. I'm sure this will solve the problem. If not, uninstall pip and reinstall the latest one directly.

Android: Reverse geocoding - getFromLocation

The following code snippet is doing it for me (lat and lng are doubles declared above this bit):

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

Swift - iOS - Dates and times in different format

extension String {

    func convertDatetring_TopreferredFormat(currentFormat: String, toFormat : String) ->  String {
        let dateFormator = DateFormatter()
        dateFormator.dateFormat = currentFormat
        let resultDate = dateFormator.date(from: self)
        dateFormator.dateFormat = toFormat
        return dateFormator.string(from: resultDate!)
    }

}

Call from your view controller file as below.

"your_date_string".convertDatetring_TopreferredFormat(currentFormat: "yyyy-MM-dd HH:mm:ss.s", toFormat: "dd-MMM-yyyy h:mm a")

How to subtract X days from a date using Java calendar?

Eli Courtwright second solution is wrong, it should be:

Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
date.setTime(c.getTime().getTime());

Change the On/Off text of a toggle button Android

Yes you can change the on / off button

    android:textOn="Light ON"
    android:textOff="Light OFF"

Refer for more

http://androidcoding.in/2016/09/11/android-tutorial-toggle-button

First Heroku deploy failed `error code=H10`

I want to register here what was my solution for this error which was a simple file not updated to Github.

I have a full stack project, and my files are structured both root directory for backend and client for the frontend (I am using React.js). All came down to the fact that I was mistakenly pushing the client folder only to Github and all my changes which had an error (missing a comma in a object's instance in my index.js) was not updated in the backend side. Since this Heroku fetches all updates from Github Repository, I couldn't access my server and the error persisted. Then all I had to do was to commit and push to the root directory and update all the changes of the project and everything came back to work again.

Back to previous page with header( "Location: " ); in PHP

Just try this in Javascript:

 $previous = "javascript:history.go(-1)";

Or you can try it in PHP:

if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];
}

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

What is the convention in JSON for empty vs. null?

There is the question whether we want to differentiate between cases:

  1. "phone" : "" = the value is empty

  2. "phone" : null = the value for "phone" was not set yet

If we want differentiate I would use null for this. Otherwise we would need to add a new field like "isAssigned" or so. This is an old Database issue.

How to pass values arguments to modal.show() function in Bootstrap

Use

$(document).ready(function() {
    $('#createFormId').on('show.bs.modal', function(event) {
        $("#cafeId").val($(event.relatedTarget).data('id'));
    });
});

Image re-size to 50% of original size in HTML

We can do this by css3 too. Try this:

.halfsize {
    -moz-transform:scale(0.5);
    -webkit-transform:scale(0.5);
    transform:scale(0.5);
}

<img class="halfsize" src="image4.jpg">
  • subjected to browser compatibility

receiving json and deserializing as List of object at spring mvc controller

For me below code worked, first sending json string with proper headers

$.ajax({
        type: "POST",
        url : 'save',
        data : JSON.stringify(valObject),
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success : function(resp){
            console.log(resp);
        },
        error : function(resp){
            console.log(resp);
        }
    });

And then on Spring side -

@RequestMapping(value = "/save", 
                method = RequestMethod.POST,
                consumes="application/json")
public @ResponseBody String  save(@RequestBody ArrayList<KeyValue> keyValList) {
    //Saving call goes here
    return "";
}

Here KeyValue is simple pojo that corresponds to your JSON structure also you can add produces as you wish, I am simply returning string.

My json object is like this -

[{"storedKey":"vc","storedValue":"1","clientId":"1","locationId":"1"},
 {"storedKey":"vr","storedValue":"","clientId":"1","locationId":"1"}]

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

It is not strange for me that none of the solutions above came up, but I saw how the igd installation removed the new version and installed the old one, for the solution I downloaded this archive:https://pypi.org/project/igd/#files

and changed the recommended version of the new version: 'lxml==4.3.0' in setup.py It works!

Detect encoding and make everything UTF-8

A really nice way to implement an isUTF8-function can be found on php.net:

function isUTF8($string) {
    return (utf8_encode(utf8_decode($string)) == $string);
}

Preventing form resubmission

Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:

Prevent Back button from showing POST confirmation alert

Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.

Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

Follow the below steps,

1). Open your php.ini file via sublime through path 
    /etc/php/7.2/apache2/php.ini

2). find display_errors in that file

3). Un-comment these lines of code
      display_errors
      Default Value: On
      Development Value: On
      Production Value: Off

      display_startup_errors
      Default Value: Off
      Development Value: On
      Production Value: Off

      error_reporting
      Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
      Development Value: E_ALL
      Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

      html_errors
      Default Value: On
      Development Value: On
      Production value: On

4). Save the file and then type the following command in the terminal
     sudo service apache2 restart


your errors are now showing in the browser

What is the C# equivalent of NaN or IsNumeric?

In addition to the previous correct answers it is probably worth pointing out that "Not a Number" (NaN) in its general usage is not equivalent to a string that cannot be evaluated as a numeric value. NaN is usually understood as a numeric value used to represent the result of an "impossible" calculation - where the result is undefined. In this respect I would say the Javascript usage is slightly misleading. In C# NaN is defined as a property of the single and double numeric types and is used to refer explicitly to the result of diving zero by zero. Other languages use it to represent different "impossible" values.

Change <select>'s option and trigger events with JavaScript

You can fire the event manually after changing the selected option on the onclick event doing: document.getElementById("sel").onchange();

Laravel 4: how to run a raw SQL?

You can also use DB::unprepared for ALTER TABLE queries.

DB::unprepared is meant to be used for queries like CREATE TRIGGER. But essentially it executes raw sql queries directly. (without using PDO prepared statements)

https://github.com/laravel/framework/pull/54

specifying goal in pom.xml

  1. Go to Terminal
  2. Do mvn clean install

When to use dynamic vs. static libraries

Static libraries increase the size of the code in your binary. They're always loaded and whatever version of the code you compiled with is the version of the code that will run.

Dynamic libraries are stored and versioned separately. It's possible for a version of the dynamic library to be loaded that wasn't the original one that shipped with your code if the update is considered binary compatible with the original version.

Additionally dynamic libraries aren't necessarily loaded -- they're usually loaded when first called -- and can be shared among components that use the same library (multiple data loads, one code load).

Dynamic libraries were considered to be the better approach most of the time, but originally they had a major flaw (google DLL hell), which has all but been eliminated by more recent Windows OSes (Windows XP in particular).

How to change the style of a DatePicker in android?

Try this. It's the easiest & most efficient way

<style name="datepicker" parent="Theme.AppCompat.Light.Dialog">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/primary</item>
</style>

Assembly code vs Machine code vs Object code?

Machine code is binary (1's and 0's) code that can be executed directly by the CPU. If you open a machine code file in a text editor you would see garbage, including unprintable characters (no, not those unprintable characters ;) ).

Object code is a portion of machine code not yet linked into a complete program. It's the machine code for one particular library or module that will make up the completed product. It may also contain placeholders or offsets not found in the machine code of a completed program. The linker will use these placeholders and offsets to connect everything together.

Assembly code is plain-text and (somewhat) human read-able source code that mostly has a direct 1:1 analog with machine instructions. This is accomplished using mnemonics for the actual instructions, registers, or other resources. Examples include JMP and MULT for the CPU's jump and multiplication instructions. Unlike machine code, the CPU does not understand assembly code. You convert assembly code to machine code with the use of an assembler or a compiler, though we usually think of compilers in association with high-level programming language that are abstracted further from the CPU instructions.


Building a complete program involves writing source code for the program in either assembly or a higher level language like C++. The source code is assembled (for assembly code) or compiled (for higher level languages) to object code, and individual modules are linked together to become the machine code for the final program. In the case of very simple programs the linking step may not be needed. In other cases, such as with an IDE (integrated development environment) the linker and compiler may be invoked together. In other cases, a complicated make script or solution file may be used to tell the environment how to build the final application.

There are also interpreted languages that behave differently. Interpreted languages rely on the machine code of a special interpreter program. At the basic level, an interpreter parses the source code and immediately converts the commands to new machine code and executes them. Modern interpreters are now much more complicated: evaluating whole sections of source code at a time, caching and optimizing where possible, and handling complex memory management tasks.

One final type of program involves the use of a runtime-environment or virtual machine. In this situation, a program is first pre-compiled to a lower-level intermediate language or byte code. The byte code is then loaded by the virtual machine, which just-in-time compiles it to native code. The advantage here is the virtual machine can take advantage of optimizations available at the time the program runs and for that specific environment. A compiler belongs to the developer, and therefore must produce relatively generic (less-optimized) machine code that could run in many places. The runtime environment or virtual machine, however, is located on the end user's computer and therefore can take advantage of all the features provided by that system.

Deleting folders in python recursively

For Linux users, you can simply run the shell command in a pythonic way

import os
os.system("rm -r /home/user/folder1  /home/user/folder2  ...")

If facing any issue then instead of rm -r use rm -rf but remember f will delete the directory forcefully.

Where rm stands for remove, -r for recursively and -rf for recursively + forcefully.

Note: It doesn't matter either the directories are empty or not, they'll get deleted.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

I think you can create a simple SQL query:

$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);

and then you can use it normally.

How to get Printer Info in .NET?

As dowski suggested, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.

using System.Management;

...

string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
    try
    {
        foreach (ManagementObject printer in coll)
        {
            foreach (PropertyData property in printer.Properties)
            {
                Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
            }
        }
    }
    catch (ManagementException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Fastest way to determine if record exists

Nothing can beat -

SELECT TOP 1 1 FROM products WHERE id = 'some value';

You don't need to count to know if there is a data in table. And don't use alias when not necessary.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

I was getting the same issue "Cannot open git-upload-pack" in eclipse Juno while trying to clone ('Git Repository Exploring' perspective). https://[username]@[hostName]:[portNumber]/scm/TestRepo.git

Solution : Issue got solved after adding "-Dhttps.protocols=TLSv1" to the eclipse.ini file.

Possible Reason for Error : Some servers does not support TLSv1.2, or TLSv1.1, they might support only TLSv1.0. Java 8 default TLS protocol is 1.2 whereas it is 1.0 with Java 7. For an unknown reason, when Egit connects to the server, it does not fallback to TLSv1.1 after TLS1.2 fails to establish the connection. Don't know if it's an Egit or a Java 8 issue Courtesy : https://www.eclipse.org/forums/index.php/t/1065782/

how to use php DateTime() function in Laravel 5

DateTime is not a function, but the class.

When you just reference a class like new DateTime() PHP searches for the class in your current namespace. However the DateTime class obviously doesn't exists in your controllers namespace but rather in root namespace.

You can either reference it in the root namespace by prepending a backslash:

$now = new \DateTime();

Or add an import statement at the top:

use DateTime;

$now = new DateTime();

Add 10 seconds to a Date

Just for the performance maniacs among us.

getTime

var d = new Date('2014-01-01 10:11:55');
d = new Date(d.getTime() + 10000);

5,196,949 Ops/sec, fastest


setSeconds

var d = new Date('2014-01-01 10:11:55');
d.setSeconds(d.getSeconds() + 10);

2,936,604 Ops/sec, 43% slower


moment.js

var d = new moment('2014-01-01 10:11:55');
d = d.add(10, 'seconds');

22,549 Ops/sec, 100% slower


So maybe its the least human readable (not that bad) but the fastest way of going :)

jspref online tests

How do I programmatically get the GUID of an application in .NET 2.0

You should be able to read the GUID attribute of the assembly via reflection. This will get the GUID for the current assembly

Assembly asm = Assembly.GetExecutingAssembly();
var attribs = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
Console.WriteLine((attribs[0] as GuidAttribute).Value);

You can replace the GuidAttribute with other attributes as well, if you want to read things like AssemblyTitle, AssemblyVersion, etc.

You can also load another assembly (Assembly.LoadFrom and all) instead of getting the current assembly - if you need to read these attributes of external assemblies (for example, when loading a plugin).

Where do I get servlet-api.jar from?

Grab it from here

Just choose required version and click 'Binary'. e.g direct link to version 2.5

What is the difference between a heuristic and an algorithm?

An algorithm is the description of an automated solution to a problem. What the algorithm does is precisely defined. The solution could or could not be the best possible one but you know from the start what kind of result you will get. You implement the algorithm using some programming language to get (a part of) a program.

Now, some problems are hard and you may not be able to get an acceptable solution in an acceptable time. In such cases you often can get a not too bad solution much faster, by applying some arbitrary choices (educated guesses): that's a heuristic.

A heuristic is still a kind of an algorithm, but one that will not explore all possible states of the problem, or will begin by exploring the most likely ones.

Typical examples are from games. When writing a chess game program you could imagine trying every possible move at some depth level and applying some evaluation function to the board. A heuristic would exclude full branches that begin with obviously bad moves.

In some cases you're not searching for the best solution, but for any solution fitting some constraint. A good heuristic would help to find a solution in a short time, but may also fail to find any if the only solutions are in the states it chose not to try.

Check if string contains only whitespace

To check if a string is just a spaces or newline

Use this simple code

mystr = "      \n  \r  \t   "
if not mystr.strip(): # The String Is Only Spaces!
    print("\n[!] Invalid String !!!")
    exit(1)
mystr = mystr.strip()
print("\n[*] Your String Is: "+mystr)

How to get the current taxonomy term ID (not the slug) in WordPress?

It's the term slug you want.Looks like you can get the id like this if that's what you need:

function get_term_link( $term, $taxonomy = '' ) {
    global $wp_rewrite;

    if ( !is_object($term) ) {
        if ( is_int( $term ) ) {
            $term = get_term( $term, $taxonomy );
        } else {
            $term = get_term_by( 'slug', $term, $taxonomy );
        }
    }

How to get the directory of the currently running file?

dir, err := os.Getwd()
    if err != nil {
        fmt.Println(err)
    }

this is for golang version: go version go1.13.7 linux/amd64

works for me, for go run main.go. If I run go build -o fileName, and put the final executable in some other folder, then that path is given while running the executable.

"Missing return statement" within if / for / while

If you put return statement in if, while or for statement then it may or may not return value. If it will not go inside these statement then also that method should return some value ( that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.

But if you write if / else block and each one of them is having return in it then compiler knows that either if or else will get execute and method will return a value. So this time compiler will not force you.

if(condition)
{
 return;
}
else
{
 return;
}

How to use background thread in swift?

Grand Central Dispatch is used to handle multitasking in our iOS apps.

You can use this code

// Using time interval

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
    print("Hello World")
}

// Background thread
queue.sync {
     for i in 0..<10 {
          print("Hello", i)
     }
}

// Main thread
for i in 20..<30 {
     print("Hello", i)
}

More information use this link : https://www.programminghub.us/2018/07/integrate-dispatcher-in-swift.html

How can I extract a predetermined range of lines from a text file on Unix?

Using ed:

ed -s infile <<<'16224,16482p'

-s suppresses diagnostic output; the actual commands are in a here-string. Specifically, 16224,16482p runs the p (print) command on the desired line address range.

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

JavaScript OOP in NodeJS: how?

This is an example that works out of the box. If you want less "hacky", you should use inheritance library or such.

Well in a file animal.js you would write:

var method = Animal.prototype;

function Animal(age) {
    this._age = age;
}

method.getAge = function() {
    return this._age;
};

module.exports = Animal;

To use it in other file:

var Animal = require("./animal.js");

var john = new Animal(3);

If you want a "sub class" then inside mouse.js:

var _super = require("./animal.js").prototype,
    method = Mouse.prototype = Object.create( _super );

method.constructor = Mouse;

function Mouse() {
    _super.constructor.apply( this, arguments );
}
//Pointless override to show super calls
//note that for performance (e.g. inlining the below is impossible)
//you should do
//method.$getAge = _super.getAge;
//and then use this.$getAge() instead of super()
method.getAge = function() {
    return _super.getAge.call(this);
};

module.exports = Mouse;

Also you can consider "Method borrowing" instead of vertical inheritance. You don't need to inherit from a "class" to use its method on your class. For instance:

 var method = List.prototype;
 function List() {

 }

 method.add = Array.prototype.push;

 ...

 var a = new List();
 a.add(3);
 console.log(a[0]) //3;

Does Go have "if x in" construct similar to Python?

Just had similar question and decided to try out some of the suggestions in this thread.

I've benchmarked best and worst case scenarios of 3 types of lookup:

  • using a map
  • using a list
  • using a switch statement

here's the function code:

func belongsToMap(lookup string) bool {
list := map[string]bool{
    "900898296857": true,
    "900898302052": true,
    "900898296492": true,
    "900898296850": true,
    "900898296703": true,
    "900898296633": true,
    "900898296613": true,
    "900898296615": true,
    "900898296620": true,
    "900898296636": true,
}
if _, ok := list[lookup]; ok {
    return true
} else {
    return false
}
}


func belongsToList(lookup string) bool {
list := []string{
    "900898296857",
    "900898302052",
    "900898296492",
    "900898296850",
    "900898296703",
    "900898296633",
    "900898296613",
    "900898296615",
    "900898296620",
    "900898296636",
}
for _, val := range list {
    if val == lookup {
        return true
    }
}
return false
}

func belongsToSwitch(lookup string) bool {
switch lookup {
case
    "900898296857",
    "900898302052",
    "900898296492",
    "900898296850",
    "900898296703",
    "900898296633",
    "900898296613",
    "900898296615",
    "900898296620",
    "900898296636":
    return true
}
return false
}

best case scenarios pick the first item in lists, worst case ones use nonexistant value.

here are the results:

BenchmarkBelongsToMapWorstCase-4 2000000 787 ns/op BenchmarkBelongsToSwitchWorstCase-4 2000000000 0.35 ns/op BenchmarkBelongsToListWorstCase-4 100000000 14.7 ns/op BenchmarkBelongsToMapBestCase-4 2000000 683 ns/op BenchmarkBelongsToSwitchBestCase-4 100000000 10.6 ns/op BenchmarkBelongsToListBestCase-4 100000000 10.4 ns/op

Switch wins all the way, worst case is surpassingly quicker than best case. Maps are the worst and list is closer to switch.

So the moral is: If you have a static, reasonably small list, switch statement is the way to go.

Android custom dropdown/popup menu

Update: To create a popup menu in android with Kotlin refer my answer here.

To create a popup menu in android with Java:

Create a layout file activity_main.xml under res/layout directory which contains only one button.

Filename: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:paddingBottom="@dimen/activity_vertical_margin"  
    android:paddingLeft="@dimen/activity_horizontal_margin"  
    android:paddingRight="@dimen/activity_horizontal_margin"  
    android:paddingTop="@dimen/activity_vertical_margin"  
    tools:context=".MainActivity" >  

    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="62dp"  
        android:layout_marginTop="50dp"  
        android:text="Show Popup" />  

</RelativeLayout>  

Create a file popup_menu.xml under res/menu directory

It contains three items as shown below.

Filename: poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >  

    <item  
        android:id="@+id/one"  
        android:title="One"/>  

    <item  
        android:id="@+id/two"  
        android:title="Two"/>  

    <item  
        android:id="@+id/three"  
        android:title="Three"/>  

</menu>  

MainActivity class which displays the popup menu on button click.

Filename: MainActivity.java

public class MainActivity extends Activity {  
    private Button button1;  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                PopupMenu popup = new PopupMenu(MainActivity.this, button1);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                    .inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                            MainActivity.this,
                            "You Clicked : " + item.getTitle(),
                            Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }
        }); //closing the setOnClickListener method
    }
}

To add programmatically:

PopupMenu menu = new PopupMenu(this, view);

menu.getMenu().add("One");
menu.getMenu().add("Two");
menu.getMenu().add("Three");

menu.show();

Follow this link for creating menu programmatically.

get client time zone from browser

No. There is no single reliable way and there will never be. Did you really think you could trust the client?

WhatsApp API (java/python)

Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.

jQuery.each - Getting li elements inside an ul

First I think you need to fix your lists, as the first node of a <ul> must be a <li> (stackoverflow ref). Once that is setup you can do this:

// note this array has outer scope
var phrases = [];

$('.phrase').each(function(){
        // this is inner scope, in reference to the .phrase element
        var phrase = '';
        $(this).find('li').each(function(){
            // cache jquery var
            var current = $(this);
            // check if our current li has children (sub elements)
            // if it does, skip it
            // ps, you can work with this by seeing if the first child
            // is a UL with blank inside and odd your custom BLANK text
            if(current.children().size() > 0) {return true;}
            // add current text to our current phrase
            phrase += current.text();
        });
        // now that our current phrase is completely build we add it to our outer array
        phrases.push(phrase);
    });
    // note the comma in the alert shows separate phrases
    alert(phrases);

Working jsfiddle.

One thing is if you get the .text() of an upper level li you will get all sub level text with it.

Keeping an array will allow for many multiple phrases to be extracted.


EDIT:

This should work better with an empty UL with no LI:

// outer scope
var phrases = [];

$('.phrase').each(function(){
    // inner scope
    var phrase = '';
    $(this).find('li').each(function(){
        // cache jquery object
        var current = $(this);
        // check for sub levels
        if(current.children().size() > 0) {
            // check is sublevel is just empty UL
            var emptyULtest = current.children().eq(0); 
            if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
                phrase += ' -BLANK- '; //custom blank text
                return true;   
            } else {
             // else it is an actual sublevel with li's
             return true;   
            }
        }
        // if it gets to here it is actual li
        phrase += current.text();
    });
    phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);

What are these ^M's that keep showing up in my files in emacs?

I ran into this issue a while back. The ^M represents a Carriage Return, and searching on Ctrl-Q Ctrl-M (This creates a literal ^M) will allow you get a handle on this character within Emacs. I did something along these lines:

M-x replace-string [ENTER] C-q C-m [ENTER] \n [ENTER]

How to receive JSON as an MVC 5 action method parameter

Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.

To solve your requirement, here is the working solution -

First create your ViewModels in following way. PersonModel can have list of RoleModels.

public class PersonModel
{
    public List<RoleModel> Roles { get; set; }
    public string Name { get; set; }
}

public class RoleModel
{
    public string RoleName { get; set;}
    public string Description { get; set;}
}

Then have a index action which will be serving basic index view -

public ActionResult Index()
{
    return View();
}

Index view will be having following JQuery AJAX POST operation -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $('#click1').click(function (e) {

            var jsonObject = {
                "Name" : "Rami",
                "Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]
            };

            $.ajax({
                url: "@Url.Action("AddUser")",
                type: "POST",
                data: JSON.stringify(jsonObject),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (response) {
                    alert(response.responseText);
            },
                success: function (response) {
                    alert(response);
                }
            });

        });
    });
</script>

<input type="button" value="click1" id="click1" />

Index action posts to AddUser action -

[HttpPost]
public ActionResult AddUser(PersonModel model)
{
    if (model != null)
    {
        return Json("Success");
    }
    else
    {
        return Json("An Error Has occoured");
    }
}

So now when the post happens you can get all the posted data in the model parameter of action.

Update:

For asp.net core, to get JSON data as your action parameter you should add the [FromBody] attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController] attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)

enter image description here

What causes a TCP/IP reset (RST) flag to be sent?

A 'router' could be doing anything - particularly NAT, which might involve any amount of bug-ridden messing with traffic...

One reason a device will send a RST is in response to receiving a packet for a closed socket.

It's hard to give a firm but general answer, because every possible perversion has been visited on TCP since its inception, and all sorts of people might be inserting RSTs in an attempt to block traffic. (Some 'national firewalls' work like this, for example.)

How do you remove duplicates from a list whilst preserving order?

Here you have some alternatives: http://www.peterbe.com/plog/uniqifiers-benchmark

Fastest one:

def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

Why assign seen.add to seen_add instead of just calling seen.add? Python is a dynamic language, and resolving seen.add each iteration is more costly than resolving a local variable. seen.add could have changed between iterations, and the runtime isn't smart enough to rule that out. To play it safe, it has to check the object each time.

If you plan on using this function a lot on the same dataset, perhaps you would be better off with an ordered set: http://code.activestate.com/recipes/528878/

O(1) insertion, deletion and member-check per operation.

(Small additional note: seen.add() always returns None, so the or above is there only as a way to attempt a set update, and not as an integral part of the logical test.)

How to index into a dictionary?

oh, that's a tough one. What you have here, basically, is two values for each item. Then you are trying to call them with a number as the key. Unfortunately, one of your values is already set as the key!

Try this:

colors = {1: ["blue", "5"], 2: ["red", "6"], 3: ["yellow", "8"]}

Now you can call the keys by number as if they are indexed like a list. You can also reference the color and number by their position within the list.

For example,

colors[1][0]
// returns 'blue'

colors[3][1]
// returns '8'

Of course, you will have to come up with another way of keeping track of what location each color is in. Maybe you can have another dictionary that stores each color's key as it's value.

colors_key = {'blue': 1, 'red': 6, 'yllow': 8}

Then, you will be able to also look up the colors key if you need to.

colors[colors_key['blue']][0] will return 'blue'

Something like that.

And then, while you're at it, you can make a dict with the number values as keys so that you can always use them to look up your colors, you know, if you need.

values = {5: [1, 'blue'], 6: [2, 'red'], 8: [3, 'yellow']}

Then, (colors[colors_key[values[5][1]]][0]) will return 'blue'.

Or you could use a list of lists.

Good luck!

Is there way to use two PHP versions in XAMPP?

Why switch between PHP versions when you can use multiple PHP version at a same time with a single xampp installation? With a single xampp installation, you have 2 options:

  1. Run an older PHP version for only the directory of your old project: This will serve the purpose most of the time, you may have one or two old projects that you intend to run with older PHP version. Just configure xampp to run older PHP version only for those project directories.

  2. Run an older PHP version on a separate port of xampp: Sometimes you may be upgrading and old project to latest PHP version when you need to run the same project on new and older PHP version back and forth. Then you can set an older PHP version on a different port (say 8056) so when you go to http://localhost/any_project/ xampp runs PHP 7 and when you go to http://localhost:8056/any_project/ xampp runs PHP 5.6.

  3. Run an older PHP version on a virtualhost: You can create a virtualhost like localhost56 to run PHP 5.6 while you can use PHP 7 on localhost.

Lets set it up.

Step 1: Download PHP

So you have PHP 7 running under xampp, you want to add an older PHP version to it, say PHP 5.6. Download the nts (Non Thread Safe) version of PHP zip archive from php.net (see archive for older versions) and extract the files under c:\xampp\php56. The thread safe version does not include php-cgi.exe.

Step 2: Configure php.ini

Open c:\xampp\php56\php.ini file in notepad. If the file does not exist copy php.ini-development to php.ini and open it in notepad. Then uncomment the following line:

extension_dir = "ext"

Step 3: Configure apache

Open xampp control panel, click config button for apache, and click Apache (httpd-xampp.conf). A text file will open up put the following settings at the bottom of the file:

ScriptAlias /php56 "C:/xampp/php56"
Action application/x-httpd-php56-cgi /php56/php-cgi.exe
<Directory "C:/xampp/php56">
    AllowOverride None
    Options None
    Require all denied
    <Files "php-cgi.exe">
        Require all granted
    </Files>
</Directory>

Note: You can add more versions of PHP to your xampp installation following step 1 to 3 if you want.

Step 4 (option 1): [Add Directories to run specific PHP version]

Now you can set directories that will run in PHP 5.6. Just add the following at the bottom of the config file (httpd-xampp.conf from Step 3) to set directories.

<Directory "C:\xampp\htdocs\my_old_project1">
    <FilesMatch "\.php$">
        SetHandler application/x-httpd-php56-cgi
    </FilesMatch>
</Directory>

<Directory "C:\xampp\htdocs\my_old_project2">
    <FilesMatch "\.php$">
        SetHandler application/x-httpd-php56-cgi
    </FilesMatch>
</Directory>

Step 4 (option 2): [Run older PHP version on a separate port]

Now to to set PHP v5.6 to port 8056 add the following code to the bottom of the config file (httpd-xampp.conf from Step 3).

Listen 8056
<VirtualHost *:8056>
    <FilesMatch "\.php$">
        SetHandler application/x-httpd-php56-cgi
    </FilesMatch>
</VirtualHost>

Step 4 (option 3): [Run an older PHP version on a virtualhost]

To create a virtualhost (localhost56) on a directory (htdocs56) to use PHP v5.6 on http://localhost56, create directory htdocs56 at your desired location and add localhost56 to your hosts file (see how), then add the following code to the bottom of the config file (httpd-xampp.conf from Step 3).

<VirtualHost localhost56:80>
    DocumentRoot "C:\xampp\htdocs56"
    ServerName localhost56
    <Directory "C:\xampp\htdocs56">
        Require all granted    
    </Directory>
    <FilesMatch "\.php$">
        SetHandler application/x-httpd-php56-cgi
    </FilesMatch>
</VirtualHost>

Finish: Save and Restart Apache

Save and close the config file, Restart apache from xampp control panel. If you went for option 2 you can see the additional port(8056) listed in your xampp control panel.

enter image description here

Update for Error:
malformed header from script 'php-cgi.exe': Bad header

If you encounter the above error, open httpd-xampp.conf again and comment out the following line with a leading # (hash character).

SetEnv PHPRC "\\path\\to\\xampp\\php"

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

If for whatever reason you cannot have the files hosted from a webserver and still need some sort of way of loading partials, you can resort to using the ngTemplate directive.

This way, you can include your markup inside script tags in your index.html file and not have to include the markup as part of the actual directive.

Add this to your index.html

<script type='text/ng-template' id='tpl-productColour'>
 <div class="list-group-item">
    <h3>Hello <em class="pull-right">Brother</em></h3>
</div>
</script>

Then, in your directive:

app.directive('productColor', function() {
      return {
          restrict: 'E', //Element Directive
          //template: 'tpl-productColour'
          templateUrl: 'tpl-productColour'
      };
   }
  );

Controlling Spacing Between Table Cells

Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.

_x000D_
_x000D_
table.test td {
  background-color: lime;
  margin: 12px 12px 12px 12px;
  padding: 12px 12px 12px 12px;
}

table.test {
  border-collapse: separate;
  border-spacing: 10px;
  *border-collapse: expression('separate', cellSpacing='10px');
}
_x000D_
<table class="test">
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Deleting array elements in JavaScript - delete vs splice

delete acts like a non real world situation, it just removes the item, but the array length stays the same:

example from node terminal:

> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]

Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1

function(arr,arrIndex){
    return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}

What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.

Here is an example using the function above as a node module, seeing the terminal will be useful:

> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4 
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3

please note that this will not work one array with dupes in it, because indexOf("c") will just get the first occurance, and only splice out and remove the first "c" it finds.

Angular checkbox and ng-click

The order of execution of ng-click and ng-model is different with angular 1.2 vs 1.6

You must test, with 1.2 and 1.6,

for example, with angular 1.2, ng-click get execute before ng-model, with angular 1.6, ng-model maybe get excute before ng-click.

so you get 'true checked' / 'false uncheck' value maybe not you expect

Vue.js dynamic images not working

Tried all of the answers here but what worked for me on Vue2 is like this.

<div class="col-lg-2" v-for="pic in pics">
   <img :src="require(`../assets/${pic.imagePath}.png`)" :alt="pic.picName">
</div>

SSL: CERTIFICATE_VERIFY_FAILED with Python3

When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert

To fix remove urllib3-1.25.3 and install urllib3-1.24.3

pip3 uninstall urllib3

pip3 install urllib3==1.24.3

Tested on Linux MacOS and Window$

How to set Java environment path in Ubuntu

To Set JAVA_HOME / PATH for a single user, Login to your account and open .bash_profile file

$ vi ~/.bash_profile

Set JAVA_HOME as follows using syntax export JAVA_HOME=<path-to-java>. If your path is set to /usr/java/jdk1.5.0_07/bin/java, set it as follows:

export JAVA_HOME=/usr/java/jdk1.5.0_07/bin/java

Set PATH as follows:

export PATH=$PATH:/usr/java/jdk1.5.0_07/bin

Feel free to replace /usr/java/jdk1.5.0_07 as per your setup. Save and close the file. Just logout and login back to see new changes. Alternatively, type the following command to activate the new path settings immediately:

$ source ~/.bash_profile

OR

$ . ~/.bash_profile

Verify new settings:

$ echo $JAVA_HOME
$ echo $PATH

Tip: Use the following command to find out exact path to which java executable under UNIX / Linux:

$ which java

Please note that the file ~/.bashrc is similar, with the exception that ~/.bash_profile runs only for Bash login shells and .bashrc runs for every new Bash shell.

To Set JAVA_HOME / PATH for all user, You need to setup global config in /etc/profile OR /etc/bash.bashrc file for all users:

# vi /etc/profile

Next setup PATH / JAVA_PATH variables as follows:

export PATH=$PATH:/usr/java/jdk1.5.0_07/bin
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin

Save and close the file. Once again you need to type the following command to activate the path settings immediately:

# source /etc/profile

OR

# . /etc/profile

Python division

In python cv2 not updated the division calculation. so, you must include from __future__ import division in first line of the program.

TypeError: a bytes-like object is required, not 'str' in python and CSV

just change wb to w

outfile=open('./immates.csv','wb')

to

outfile=open('./immates.csv','w')

C++ Returning reference to local variable

A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.

Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.

Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.

It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!

How to query all the GraphQL type fields without writing a long query?

I guess the only way to do this is by utilizing reusable fragments:

fragment UserFragment on Users {
    id
    username
    count
} 

FetchUsers {
    users(id: "2") {
        ...UserFragment
    }
}

Incrementing a variable inside a Bash loop

while read -r country _; do
  if [[ $country = 'US' ]]; then
    ((USCOUNTER++))
    echo "US counter $USCOUNTER"
  fi
done < "$FILE"

Why does git revert complain about a missing -m option?

Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of

$ git lola
*   2582152 (HEAD, master) Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

Note: git lola is a non-standard but useful alias.

No dice with git revert:

$ git revert HEAD
fatal: Commit 2582152... is a merge but no -m option was given.

Charles Bailey gave an excellent answer as usual. Using git revert as in

$ git revert --no-edit -m 1 HEAD
[master e900aad] Revert "Merge branch 'otherguy'"
 0 files changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 bar

effectively deletes bar and produces a history of

$ git lola
* e900aad (HEAD, master) Revert "Merge branch 'otherguy'"
*   2582152 Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

But I suspect you want to throw away the merge commit:

$ git reset --hard HEAD^
HEAD is now at b7e7176 baz

$ git lola
* b7e7176 (HEAD, master) baz
| * c7256de (otherguy) bar
|/  
* 9968f79 foo

As documented in the git rev-parse manual

<rev>^, e.g. HEAD^, v1.5.1^0
A suffix ^ to a revision parameter means the first parent of that commit object. ^<n> means the n-th parent (i.e. <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when <rev> is the object name of a tag object that refers to a commit object.

so before invoking git reset, HEAD^ (or HEAD^1) was b7e7176 and HEAD^2 was c7256de, i.e., respectively the first and second parents of the merge commit.

Be careful with git reset --hard because it can destroy work.

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

No idea if it is useful to anyone but here is a variant that would make TypeScript happy:

export function getBrowser() {

 // Opera 8.0+
    if ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0) {
        return 'opera';
    }

    // Firefox 1.0+
    if (typeof window["InstallTrigger"] !== 'undefined') {
        return 'firefox';
    }

    // Safari 3.0+ "[object HTMLElementConstructor]" 
    if (/constructor/i.test(window["HTMLElement"]) || (function(p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof window["safari"] !== 'undefined' && window["safari"].pushNotification))) {
        return 'safari';
    }

    // Internet Explorer 6-11
    if (/*@cc_on!@*/false || !!document["documentMode"]) {
        return 'ie';
    }

    // Edge 20+
    if (!(/*@cc_on!@*/false || !!document["documentMode"]) && !!window["StyleMedia"]) {
        return 'edge';
    }

    // Chrome 1+
    if (!!window["chrome"] && !!window["chrome"].webstore) {
        return 'chrome';
    }

    // Blink engine detection
    if (((!!window["chrome"] && !!window["chrome"].webstore) || ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0)) && !!window["CSS"]) {
        return 'blink';
    }
}

Sending POST parameters with Postman doesn't work, but sending GET parameters does

Check your content-type in the header. I was having issue with this sending raw JSON and my content-type as application/json in the POSTMAN header.

my php was seeing jack all in the request post. It wasn't until i change the content-type to application/x-www-form-urlencoded with the JSON in the RAW textarea and its type as JSON, did my PHP app start to see the post data. not what i expected when deal with raw json but its now working for what i need.

postman POST request

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.

How to make unicode string with python3

As a workaround, I've been using this:

# Fix Python 2.x.
try:
    UNICODE_EXISTS = bool(type(unicode))
except NameError:
    unicode = lambda s: str(s)

How to create a unique index on a NULL column?

Pretty sure you can't do that, as it violates the purpose of uniques.

However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html

How to programmatically close a JFrame

If you do not want your application to terminate when a JFrame is closed, use: setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

instead of: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

From the documentation:

DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.

HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.

DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.

EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.

might still be useful: You can use setVisible(false) on your JFrame if you want to display the same frame again. Otherwise call dispose() to remove all of the native screen resources.

copied from Peter Lang

https://stackoverflow.com/a/1944474/3782247

C++ undefined reference to defined function

Though previous posters covered your particular error, you can get 'Undefined reference' linker errors when attempting to compile C code with g++, if you don't tell the compiler to use C linkage.

For example you should do this in your C header files:

extern "C" {

...

void myfunc(int param);

...

}

To make 'myfunc' available in C++ programs.

If you still also want to use this from C, wrap the extern "C" { and } in #ifdef __cplusplus preprocessor conditionals, like

#ifdef __cplusplus
extern "C" {
#endif

This way, the extern block will just be “skipped” when using a C compiler.

Deny access to one specific folder in .htaccess

Creating index.php, index.html, index.htm is not secure. Becuse, anyone can get access on your files within specified directory by guessing files name. E.g.: http://yoursite.com/includes/file.dat So, recommended method is creating a .htaccess file to deny all visitors ;). Have fun !!

Sublime Text 2 multiple line edit

Windows: I prefer Alt+F3 to search a string and change all instances of search string at once.

http://www.sublimetext.com/docs/selection

Cannot run emulator in Android Studio

Hey there just ran into the same issue you did, the 3rd link down in google brought me to this bit of code that throws the error,

if (kernelFile == NULL) {
        kernelFile = avdInfo_getKernelPath(avd);
        if (kernelFile == NULL) {
            derror( "This AVD's configuration is missing a kernel file!!" );
            const char* sdkRootDir = getenv("ANDROID_SDK_ROOT");
            if (sdkRootDir) {
                derror( "ANDROID_SDK_ROOT is defined (%s) but cannot find kernel file in "
                        "%s" PATH_SEP "system-images" PATH_SEP
                        " sub directories", sdkRootDir, sdkRootDir);
            } else {
                derror( "ANDROID_SDK_ROOT is undefined");
            }
            exit(2);

to which the person wrote:

"/* If the kernel image name ends in "-armv7", then change the cpu * type automatically. This is a poor man's approach to configuration * management, but should allow us to get past building ARMv7 * system images with dex preopt pass"

So I went back in and downloaded the x86 intel atom version for my desired API level and was able to get the emulator up without the error. Hope it helps you too.....

Change language of Visual Studio 2017 RC

You can only install a language pack at install time in VS 2017 RC. To install RC with a different language:

  1. Open the Visual Studio Installer.
  2. Find an addition under "Available" and click Install
  3. Click on the "Language packs" tab and select a language

enter image description here

You can have multiple instances of VS 2017 side by side so this shouldn't interfere with your other installation.

Disclosure: I work on Visual Studio at Microsoft.

Windows Forms - Enter keypress activates submit button?

If you set your Form's AcceptButton property to one of the Buttons on the Form, you'll get that behaviour by default.

Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event. You can check for the Enter key and take the necessary action.

Ruby: Easiest Way to Filter Hash Keys?

Edit to original answer: Even though this is answer (as of the time of this comment) is the selected answer, the original version of this answer is outdated.

I'm adding an update here to help others avoid getting sidetracked by this answer like I did.

As the other answer mentions, Ruby >= 2.5 added the Hash#slice method which was previously only available in Rails.

Example:

> { one: 1, two: 2, three: 3 }.slice(:one, :two)
=> {:one=>1, :two=>2}

End of edit. What follows is the original answer which I guess will be useful if you're on Ruby < 2.5 without Rails, although I imagine that case is pretty uncommon at this point.


If you're using Ruby, you can use the select method. You'll need to convert the key from a Symbol to a String to do the regexp match. This will give you a new Hash with just the choices in it.

choices = params.select { |key, value| key.to_s.match(/^choice\d+/) }

or you can use delete_if and modify the existing Hash e.g.

params.delete_if { |key, value| !key.to_s.match(/choice\d+/) }

or if it is just the keys and not the values you want then you can do:

params.keys.select { |key| key.to_s.match(/^choice\d+/) }

and this will give the just an Array of the keys e.g. [:choice1, :choice2, :choice3]

Print to the same line and not a new line?

This works for me, hacked it once to see if it is possible, but never actually used in my program (GUI is so much nicer):

import time
f = '%4i %%'
len_to_clear = len(f)+1
clear = '\x08'* len_to_clear
print 'Progress in percent:'+' '*(len_to_clear),
for i in range(123):
    print clear+f % (i*100//123),
    time.sleep(0.4)
raw_input('\nDone')

Find UNC path of a network drive?

$CurrentFolder = "H:\Documents"
$Query = "Select * from Win32_NetworkConnection where LocalName = '" + $CurrentFolder.Substring( 0, 2 ) + "'"
( Get-WmiObject -Query $Query ).RemoteName

OR

$CurrentFolder = "H:\Documents"
$Tst = $CurrentFolder.Substring( 0, 2 )
( Get-WmiObject -Query "Select * from Win32_NetworkConnection where LocalName = '$Tst'" ).RemoteName

How do I display todays date on SSRS report?

Just simple use

=Format(today(), "dd/MM/yyyy")

will solve your problem.

What is use of c_str function In c++

It's used to make std::string interoperable with C code that requires a null terminated char*.

Error while trying to run project: Unable to start program. Cannot find the file specified

Reset the diagnostics and the static analysis under the, for example, Properties -> FORTRAN -> diagnostics. Particular be careful the 'Level of Static Security Analysis' and set it none. Good luck!

Converting Date and Time To Unix Timestamp

Seems like getTime is not function on above answer.

Date.parse(currentDate)/1000

Http 415 Unsupported Media type error with JSON

Some times Charset Metada breaks the json while sending in the request. Better, not use charset=utf8 in the request type.

How to install pip3 on Windows?

On Windows pip3 should be in the Scripts path of your Python installation:

C:\path\to\python\Scripts\pip3

Use:

where python

to find out where your Python executable(s) is/are located. The result should look like this:

C:\path\to\python\python.exe

or:

C:\path\to\python\python3.exe

You can check if pip3 works with this absolute path:

C:\path\to\python\Scripts\pip3

if yes, add C:\path\to\python\Scripts to your environmental variable PATH .

Printing without newline (print 'a',) prints a space, how to remove?

Python 3.x:

for i in range(20):
    print('a', end='')

Python 2.6 or 2.7:

from __future__ import print_function
for i in xrange(20):
    print('a', end='')

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

After submitting a POST form open a new window showing the result

If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Above answers are excellent. You can look at the following full code example so that you could exactly know how to use

_x000D_
_x000D_
   var app = angular.module('hyperCrudApp', []);_x000D_
_x000D_
   app.controller('usersCtrl', function($scope, $http) {_x000D_
     $http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {_x000D_
        console.log(response.data)_x000D_
_x000D_
         $scope.users = response.data;_x000D_
          $scope.setKey = function (userId){_x000D_
              alert(userId)_x000D_
              if(localStorage){_x000D_
                localStorage.setItem("userId", userId)_x000D_
              } else {_x000D_
                alert("No support of localStorage")_x000D_
                return_x000D_
              }_x000D_
          }//function closed  _x000D_
     });_x000D_
   });
_x000D_
      #header{_x000D_
       color: green;_x000D_
       font-weight: bold;_x000D_
      }
_x000D_
  <!DOCTYPE html>_x000D_
  <html>_x000D_
  <head>_x000D_
    <title>HyperCrud</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
    <!-- NAVBAR STARTS -->_x000D_
      <nav class="navbar navbar-default navbar-fixed-top">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">HyperCrud</a>_x000D_
          </div>_x000D_
          <div id="navbar" class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="/">Home</a></li>_x000D_
              <li><a href="/about/">About</a></li>_x000D_
              <li><a href="/contact/">Contact</a></li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps<span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="/qAlarm/details/">qAlarm &raquo;</a></li>_x000D_
                  <li><a href="/YtEdit/details/">YtEdit &raquo;</a></li>_x000D_
                  <li><a href="/GWeather/details/">GWeather &raquo;</a></li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li><a href="/WadStore/details/">WadStore &raquo;</a></li>_x000D_
                  <li><a href="/chatsAll/details/">chatsAll</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="/login/">Login</a></li>_x000D_
              <li><a href="/register/">Register</a></li>_x000D_
              <li><a href="/services/">Services<span class="sr-only">(current)</span></a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
      <!--NAVBAR ENDS-->_x000D_
  <br>_x000D_
  <br>_x000D_
_x000D_
  <div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">_x000D_
    <div class="row">_x000D_
     <div class="col-sm-12 col-md-12">_x000D_
      <center>_x000D_
        <h1 id="header"> Users </h1>_x000D_
      </center>_x000D_
     </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="row" >_x000D_
        <!--ITERATING USERS LIST-->_x000D_
      <div class="col-sm-6 col-md-4" ng-repeat="user in users">_x000D_
        <div class="thumbnail">_x000D_
          <center>_x000D_
           <img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">_x000D_
           <hr>_x000D_
          </center>_x000D_
          <div class="caption">_x000D_
           <center>_x000D_
             <h3>{{user.name}}</h3>_x000D_
             <p>{{user.email}}</p>_x000D_
             <p>+91 {{user.phone}}</p>_x000D_
             <p>{{user.address.city}}</p>_x000D_
            </center>_x000D_
          </div>_x000D_
            <div class="caption">_x000D_
                <a href="/users/delete/{{user.id}}/" role="button" class="btn btn-danger btn-block" ng-click="setKey(user.id)">DELETE</a>_x000D_
                <a href="/users/update/{{user.id}}/" role="button" class="btn btn-success btn-block" ng-click="setKey(user.id)">UPDATE</a>_x000D_
            </div>_x000D_
        </div>_x000D_
      </div>_x000D_
_x000D_
        <div class="col-sm-6 col-md-4">_x000D_
          <div class="thumbnail">_x000D_
            <a href="/regiser/">_x000D_
             <img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
    </div>_x000D_
      <!--ROW ENDS-->_x000D_
  </div>_x000D_
_x000D_
_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

How to use the priority queue STL for objects?

You would write a comparator class, for example:

struct CompareAge {
    bool operator()(Person const & p1, Person const & p2) {
        // return "true" if "p1" is ordered before "p2", for example:
        return p1.age < p2.age;
    }
};

and use that as the comparator argument:

priority_queue<Person, vector<Person>, CompareAge>

Using greater gives the opposite ordering to the default less, meaning that the queue will give you the lowest value rather than the highest.

Batch files: List all files in a directory with relative paths

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

@echo off
set mypath=
call :treeProcess
goto :eof

:treeProcess
setlocal
for %%f in (*.txt) do echo %mypath%%%f
for /D %%d in (*) do (
    set mypath=%mypath%%%d\
    cd %%d
    call :treeProcess
    cd ..
)
endlocal
exit /b

How to set -source 1.7 in Android Studio and Gradle

Latest Android Studio 1.4.

Click File->Project Structure->SDK Location->JDK Location.

You could also set individual module JDK Version compatibility by going to the Module (below the SDK Location), and edit the Source Compatibility accordingly. (note, this only applies to Android Module).

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

How to kill all active and inactive oracle sessions for user

BEGIN
  FOR r IN (select sid,serial# from v$session where username='user')
  LOOP
      EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid  || ',' || r.serial# || '''';
  END LOOP;
END;
/

It works for me.

Read Post Data submitted to ASP.Net Form

NameValueCollection nvclc = Request.Form;
string   uName= nvclc ["txtUserName"];
string   pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);

convert UIImage to NSData

NSData *imageData = UIImagePNGRepresentation(myImage.image);

Super-simple example of C# observer/observable with delegates

    /**********************Simple Example ***********************/    

class Program
        {
            static void Main(string[] args)
            {
                Parent p = new Parent();
            }
        }

        ////////////////////////////////////////////

        public delegate void DelegateName(string data);

        class Child
        {
            public event DelegateName delegateName;

            public void call()
            {
                delegateName("Narottam");
            }
        }

        ///////////////////////////////////////////

        class Parent
        {
            public Parent()
            {
                Child c = new Child();
                c.delegateName += new DelegateName(print);
                //or like this
                //c.delegateName += print;
                c.call();
            }

            public void print(string name)
            {
                Console.WriteLine("yes we got the name : " + name);
            }
        }

How to get second-highest salary employees in a table

SELECT *,DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
INTO #tmp1
FROM Employees

SELECT * FROM #tmp1 WHERE Rnk = 2
DROP TABLE #tmp1


SELECT Name,SALARY
FROM  Employees
WHERE  Salary = (SELECT MIN(Salary)
             FROM   (SELECT DISTINCT TOP (2) Salary
                     FROM   Employees
                     ORDER  BY Salary DESC) T);

How can I use an array of function pointers?

This "answer" is more of an addendum to VonC's answer; just noting that the syntax can be simplified via a typedef, and aggregate initialization can be used:

typedef int FUNC(int, int);

FUNC sum, subtract, mul, div;
FUNC *p[4] = { sum, subtract, mul, div };

int main(void)
{
    int result;
    int i = 2, j = 3, op = 2;  // 2: mul

    result = p[op](i, j);   // = 6
}

// maybe even in another file
int sum(int a, int b) { return a+b; }
int subtract(int a, int b) { return a-b; }
int mul(int a, int b) { return a*b; }
int div(int a, int b) { return a/b; }

Setting a WebRequest's body data

With HttpWebRequest.GetRequestStream

Code example from http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

From one of my own code:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}

How to check if object has any properties in JavaScript?

Very late answer, but this is how you could handle it with prototypes.

Array.prototype.Any = function(func) {
    return this.some(func || function(x) { return x });
}

Object.prototype.IsAny = function() {
    return Object.keys(this).Any();
}

Facebook API error 191

I fixed this by passing the redirect url to the FacebookRedirectLoginHelper::getAccessToken() in my callback function:

Changing from

try {
        $accessToken = $helper->getAccessToken();
}
...

to

try {
        $accessToken = $helper->getAccessToken($fbRedirectUrl);
}
...

I am developing on a vagrant box, and it seems FacebookRedirectLoginHelper::getCurrentUrl() had issues generating a valid url.

Polygon Drawing and Getting Coordinates with Google Map API v3

try this

In your controller use

> $scope.onMapOverlayCompleted = onMapOverlayCompleted;
> 
>  function onMapOverlayCompleted(e) {
> 
>                 e.overlay.getPath().getArray().forEach(function (position) {
>                     console.log('lat', position.lat());
>                     console.log('lng', position.lng());
>                 });
> 
>  }

**In Your html page , include drawning manaer** 


    <ng-map id="geofence-map" zoom="8" center="current" default-style="true" class="map-layout map-area"
                        tilt="45"
                        heading="90">

                    <drawing-manager
                            on-overlaycomplete="onMapOverlayCompleted()"
                            drawing-control-options="{position: 'TOP_CENTER',drawingModes:['polygon','circle']}"
                            drawingControl="true"
                            drawingMode="null"
                            markerOptions="{icon:'www.example.com/icon'}"
                            rectangleOptions="{fillColor:'#B43115'}"
                            circleOptions="{fillColor: '#F05635',fillOpacity: 0.50,strokeWeight: 5,clickable: false,zIndex: 1,editable: true}">
                    </drawing-manager>
    </ng-map>

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

Where does PHP's error log reside in XAMPP?

Look in your configuration file and search for the error_log setting. Or use phpinfo() to find this setting.

How do I shut down a python simpleHTTPserver?

You are simply sending signals to the processes. kill is a command to send those signals.

The keyboard command Ctrl+C sends a SIGINT, kill -9 sends a SIGKILL, and kill -15 sends a SIGTERM.

What signal do you want to send to your server to end it?

C++ getters/setters coding style

I think the C++11 approach would be more like this now.

#include <string>
#include <iostream>
#include <functional>

template<typename T>
class LambdaSetter {
public:
    LambdaSetter() :
        getter([&]() -> T { return m_value; }),
        setter([&](T value) { m_value = value; }),
        m_value()
    {}

    T operator()() { return getter(); }
    void operator()(T value) { setter(value); }

    LambdaSetter operator=(T rhs)
    {
        setter(rhs);
        return *this;
    }

    T operator=(LambdaSetter rhs)
    {
        return rhs.getter();
    }

    operator T()
    { 
        return getter();
    }


    void SetGetter(std::function<T()> func) { getter = func; }
    void SetSetter(std::function<void(T)> func) { setter = func; }

    T& GetRawData() { return m_value; }

private:
    T m_value;
    std::function<const T()> getter;
    std::function<void(T)> setter;

    template <typename TT>
    friend std::ostream & operator<<(std::ostream &os, const LambdaSetter<TT>& p);

    template <typename TT>
    friend std::istream & operator>>(std::istream &is, const LambdaSetter<TT>& p);
};

template <typename T>
std::ostream & operator<<(std::ostream &os, const LambdaSetter<T>& p)
{
    os << p.getter();
    return os;
}

template <typename TT>
std::istream & operator>>(std::istream &is, const LambdaSetter<TT>& p)
{
    TT value;
    is >> value;
    p.setter(value);
    return is;
}


class foo {
public:
    foo()
    {
        myString.SetGetter([&]() -> std::string { 
            myString.GetRawData() = "Hello";
            return myString.GetRawData();
        });
        myString2.SetSetter([&](std::string value) -> void { 
            myString2.GetRawData() = (value + "!"); 
        });
    }


    LambdaSetter<std::string> myString;
    LambdaSetter<std::string> myString2;
};

int _tmain(int argc, _TCHAR* argv[])
{
    foo f;
    std::string hi = f.myString;

    f.myString2 = "world";

    std::cout << hi << " " << f.myString2 << std::endl;

    std::cin >> f.myString2;

    std::cout << hi << " " << f.myString2 << std::endl;

    return 0;
}

I tested this in Visual Studio 2013. Unfortunately in order to use the underlying storage inside the LambdaSetter I needed to provide a "GetRawData" public accessor which can lead to broken encapsulation, but you can either leave it out and provide your own storage container for T or just ensure that the only time you use "GetRawData" is when you are writing a custom getter/setter method.

Copy a variable's value into another

For strings or input values you could simply use this:

var a = $('#some_hidden_var').val(),
b = a.substr(0);

Multiple github accounts on the same computer?

Personal Directory .gitconfig using a personal access token

If you do not want to modify your host file, use SSH keys, or setup a .gitconfig for each repo, then you may use a personal .gitconfig that you basically include from the root level config. Given an OSX directory structure like

# root level git config
~/.gitconfig

# your personal repos under some folder like
../personal/
../home/
~/Dropbox/

Add a .gitconfig in your personal folder, such as ~/Dropbox/.gitconfig

[user]
    email = [email protected]
    name = First Last
[credential]
    username = PersonalGithubUsername
    helper = osxkeychain

In your root level .gitconfig add an includeIf section to source your personal config whenever you are in your personal directory. Any settings there will override the root config as long as the includeIf comes after the settings you want to override.

[user]
    email = [email protected]
    name = "First Last"
[credential]
    helper = osxkeychain
[includeIf "gitdir:~/Dropbox/**"]
    path = ~/Dropbox/.gitconfig

Try pushing to your personal repo or pulling from your private repo

git push
# prompts for password

When prompted enter either your personal password or, better yet, your personal access token that you have created in your account developer settings. Enter that token as your password.

Assuming you are already using git-credential-osxkeychain, your personal credentials should be stored in your keychain, so two github entries will show up, but with different accounts.

OSX keychain 2 entires for Github

How to use OrderBy with findAll in Spring Data

Yes you can sort using query method in Spring Data.

Ex:ascending order or descending order by using the value of the id field.

Code:

  public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public findAllByOrderByIdAsc();   
}

alternative solution:

    @Repository
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDAO studentDao;

    @Override
    public List<Student> findAll() {
        return studentDao.findAll(orderByIdAsc());
    }
private Sort orderByIdAsc() {
    return new Sort(Sort.Direction.ASC, "id")
                .and(new Sort(Sort.Direction.ASC, "name"));
}
}

Spring Data Sorting: Sorting

What are good message queue options for nodejs?

kue is the only message queue you would ever need

Field 'id' doesn't have a default value?

I landed this question in 2019. MY problem was updating table1 with table2 ignoring the variables with different name in both tables. I was getting the same error as mentioned in question: Error Code: 1364. Field 'id' doesn't have a default value in mysql. Here is how solved it:

Table 1 Schema : id ( unique & auto increment)| name | profile | Age Table 2 Schema: motherage| father| name| profile

This solved my error: INSERT IGNORE INTO table2 (name,profile) SELECT name, profile FROM table1

How do you save/store objects in SharedPreferences on Android?

If you want to store the whole Object that you get in response, It can achieve by doing something like,

First Create a method that converts your JSON into a string in your util class as below.

 public static <T> T fromJson(String jsonString, Class<T> theClass) {
    return new Gson().fromJson(jsonString, theClass);
}

Then In Shared Preferences Class Do something like,

 public void storeLoginResponse(yourResponseClass objName) {

    String loginJSON = UtilClass.toJson(customer);
    if (!TextUtils.isEmpty(customerJSON)) {
        editor.putString(AppConst.PREF_CUSTOMER, customerJSON);
        editor.commit();
    }
}

and then create a method for getPreferences

public Customer getCustomerDetails() {
    String customerDetail = pref.getString(AppConst.PREF_CUSTOMER, null);
    if (!TextUtils.isEmpty(customerDetail)) {
        return GSONConverter.fromJson(customerDetail, Customer.class);
    } else {
        return new Customer();
    }
}

Then Just call the First method when you get response and second when you need to get data from share preferences like

String token = SharedPrefHelper.get().getCustomerDetails().getAccessToken();

that's all.

Hope it will help you.

Happy Coding();

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

What is the difference between partitioning and bucketing a table in Hive ?

Hive Partitioning:

Partition divides large amount of data into multiple slices based on value of a table column(s).

Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.

Pros:

  1. Distribute execution load horizontally
  2. Faster execution of queries in case of partition with low volume of data. e.g. Get the population from "Vatican city" returns very fast instead of searching entire population of world.

Cons:

  1. Possibility of too many small partition creations - too many directories.
  2. Effective for low volume data for a given partition. But some queries like group by on high volume of data still take long time to execute. e.g. Grouping of population of China will take long time compared to grouping of population in Vatican city. Partition is not solving responsiveness problem in case of data skewing towards a particular partition value.

Hive Bucketing:

Bucketing decomposes data into more manageable or equal parts.

With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.

Pros

  1. Due to equal volumes of data in each partition, joins at Map side will be quicker.
  2. Faster query response like partitioning

Cons

  1. You can define number of buckets during table creation but loading of equal volume of data has to be done manually by programmers.

How to AUTO_INCREMENT in db2?

You're looking for is called an IDENTITY column:

create table student (
   sid integer not null GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
  ,sname varchar(30)
  ,PRIMARY KEY (sid)
);

A sequence is another option for doing this, but you need to determine which one is proper for your particular situation. Read this for more information comparing sequences to identity columns.

How can I get the number of records affected by a stored procedure?

WARNING: @@ROWCOUNT may return bogus data if the table being altered has triggers attached to it!

The @@ROWCOUNT will return the number of records affected by the TRIGGER, not the actual statement!

How to make a edittext box in a dialog

Use Activtiy Context

Replace this

  final EditText input = new EditText(this);

By

  final EditText input = new EditText(MainActivity.this);  
  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
  input.setLayoutParams(lp);
  alertDialog.setView(input); // uncomment this line

How to insert an item into a key/value pair object?

List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
    new KeyValuePair<string, string>("Key1", "Value1"),
    new KeyValuePair<string, string>("Key2", "Value2"),
    new KeyValuePair<string, string>("Key3", "Value3"),
};

kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));

Using this code:

foreach (KeyValuePair<string, string> kvp in kvpList)
{
    Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}

the expected output should be:

Key: New Key 1 Value: New Value 1
Key: Key 1 Value: Value 1
Key: Key 2 Value: Value 2
Key: Key 3 Value: Value 3

The same will work with a KeyValuePair or whatever other type you want to use..

Edit -

To lookup by the key, you can do the following:

var result = stringList.Where(s => s == "Lookup");

You could do this with a KeyValuePair by doing the following:

var result = kvpList.Where (kvp => kvp.Value == "Lookup");

Last edit -

Made the answer specific to KeyValuePair rather than string.

How to convert string to float?

double x;

char *s;

s = " -2309.12E-15";

x = atof(s);     /* x = -2309.12E-15 */

printf("x = %4.4f\n",x);

Create a GUID in Java

It depends what kind of UUID you want.

  • The standard Java UUID class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID instances from long, byte[] or String representations, and provide some appropriate accessors.)

  • The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.

For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.

How to check radio button is checked using JQuery?

Taking some answers one step further - if you do the following you can check if any element within the radio group has been checked:

if ($('input[name="yourRadioNames"]:checked').val()){ (checked) or if (!$('input[name="yourRadioNames"]:checked').val()){ (not checked)

SOAP Action WSDL

I have come across exactly the same problem when trying to write a client for the National Rail SOAP service with Perl.

The problem was caused because the Perl module that I'm using 'SOAP::Lite' inserts a '#' in the SOAPAction header ...

SOAPAction: "http://thalesgroup.com/RTTI/2008-02-20/ldb/#GetDepartureBoard"

This is not interpreted correctly by .NET servers. I found this out from Example 3-19 in O'Reilly's Programming Web Services with SOAP . The solution was given below in section 3-20, namely you need to explicitly specify the format of the header with the 'on_action' method.

print SOAP::Lite
  -> uri('urn:Example1')
  -> on_action(sub{sprintf '%s/%s', @_ })
  -> proxy('http://localhost:8080/helloworld/example1.asmx')
  -> sayHello($name)
  -> result . "\n\n";

My guess is that soapclient.com is using SOAP::Lite behind the scenes and so are hitting the same problem when talking to National Rail.

The solution is to write your own client so that you have control over the format of the SOAPAction header ... but you've probably done that already.

Wireshark vs Firebug vs Fiddler - pros and cons?

The benefit of WireShark is that it could possibly show you errors in levels below the HTTP protocol. Fiddler will show you errors in the HTTP protocol.

If you think the problem is somewhere in the HTTP request issued by the browser, or you are just looking for more information in regards to what the server is responding with, or how long it is taking to respond, Fiddler should do.

If you suspect something may be wrong in the TCP/IP protocol used by your browser and the server (or in other layers below that), go with WireShark.

Fastest way to add an Item to an Array

Not very clean but it works :)

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4

arr = arr.Concat({newItem}).ToArray

jQuery UI: Datepicker set year range dropdown to 100 years

I did this:

var dateToday = new Date();
var yrRange = dateToday.getFullYear() + ":" + (dateToday.getFullYear() + 50);
and then
yearRange : yrRange

where 50 is the range from current year.

Forking / Multi-Threaded Processes | Bash

I don't like using wait because it gets blocked until the process exits, which is not ideal when there are multiple process to wait on as I can't get a status update until the current process is done. I prefer to use a combination of kill -0 and sleep to this.

Given an array of pids to wait on, I use the below waitPids() function to get a continuous feedback on what pids are still pending to finish.

declare -a pids
waitPids() {
    while [ ${#pids[@]} -ne 0 ]; do
        echo "Waiting for pids: ${pids[@]}"
        local range=$(eval echo {0..$((${#pids[@]}-1))})
        local i
        for i in $range; do
            if ! kill -0 ${pids[$i]} 2> /dev/null; then
                echo "Done -- ${pids[$i]}"
                unset pids[$i]
            fi
        done
        pids=("${pids[@]}") # Expunge nulls created by unset.
        sleep 1
    done
    echo "Done!"
}

When I start a process in the background, I add its pid immediately to the pids array by using this below utility function:

addPid() {
    local desc=$1
    local pid=$2
    echo "$desc -- $pid"
    pids=(${pids[@]} $pid)
}

Here is a sample that shows how to use:

for i in {2..5}; do
    sleep $i &
    addPid "Sleep for $i" $!
done
waitPids

And here is how the feedback looks:

Sleep for 2 -- 36271
Sleep for 3 -- 36272
Sleep for 4 -- 36273
Sleep for 5 -- 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Done -- 36271
Waiting for pids: 36272 36273 36274
Done -- 36272
Waiting for pids: 36273 36274
Done -- 36273
Waiting for pids: 36274
Done -- 36274
Done!

Installation error: INSTALL_FAILED_OLDER_SDK

This error occurs when the sdk-version installed on your device (real or virtual device) is smaller than android:minSdkVersion in your android manifest.

You either have to decrease your android:minSdkVersion or you have to specify a higher api-version for your AVD.

Keep in mind, that it is not always trivial to decrease android:minSdkVersion as you have to make sure, your app cares about the actual installed API and uses the correct methods:

AsyncTask<String, Object, String> task = new AsyncTask<String, Object, String>() {
    @Override
    protected Boolean doInBackground(String... params) {
        if (params == null) return "";
        StringBuilder b = new StringBuilder();
        for (String p : params) {
             b.append(p);
        }
        return b.toString();
    }
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"Hello", " ", "world!");
} else {
    task.execute("Hello", " ", "world!");
}

Using the android-support-library and/or libraries like actionbar-sherlock will help you dealing especially with widgets of older versions.

How to check if a scope variable is undefined in AngularJS template?

If foo is not a boolean variable then this would work (i.e. you want to show this when that variable has some data):

<p ng-show="!foo">Show this if $scope.foo is undefined</p>

And vise-versa:

<p ng-show="foo">Show this if $scope.foo is defined</p>

Quickest way to compare two generic lists for differences

Not for this Problem, but here's some code to compare lists for equal and not! identical objects:

public class EquatableList<T> : List<T>, IEquatable<EquatableList<T>> where    T : IEquatable<T>

/// <summary>
/// True, if this contains element with equal property-values
/// </summary>
/// <param name="element">element of Type T</param>
/// <returns>True, if this contains element</returns>
public new Boolean Contains(T element)
{
    return this.Any(t => t.Equals(element));
}

/// <summary>
/// True, if list is equal to this
/// </summary>
/// <param name="list">list</param>
/// <returns>True, if instance equals list</returns>
public Boolean Equals(EquatableList<T> list)
{
    if (list == null) return false;
    return this.All(list.Contains) && list.All(this.Contains);
}

How to get Tensorflow tensor dimensions (shape) as int values?

for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:

rows, columns = map(lambda i: i.value, tensor.get_shape())

python request with authentication (access_token)

Have you tried the uncurl package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl. Your curl request returns:

>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"

requests.get("https://website.com/id",
    headers={
        "Authorization": "access_token myToken"
    },
    cookies={},
)

GitHub - List commits by author

Just add ?author=<emailaddress> or ?author=<githubUserName> to the url when viewing the "commits" section of a repo.

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Take a look at this WPF metro-styled window with optional glowing borders.

This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.

Supports Windows all the way back to XP (.NET4).

How to refresh token with Google API client?

I used the example by smartcodes with the current version of the Google API, but that one didn't work. I think his API is too outdated.

So, I just wrote my own version, based on one of the API examples... It outputs access token, request token, token type, ID token, expiration time and creation time as strings

If your client credentials and developer key are correct, this code should work out of the box.

<?php
// Call set_include_path() as needed to point to your client library.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();

$client = new Google_Client();
$client->setApplicationName("Get Token");
// Visit https://code.google.com/apis/console?api=plus to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$oauth2 = new Google_Oauth2Service($client);

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    return;
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
    unset($_SESSION['token']);
    $client->revokeToken();
}
?>
<!doctype html>
<html>
    <head><meta charset="utf-8"></head>
    <body>
        <header><h1>Get Token</h1></header>
        <?php
        if ($client->getAccessToken()) {
            $_SESSION['token'] = $client->getAccessToken();
            $token = json_decode($_SESSION['token']);
            echo "Access Token = " . $token->access_token . '<br/>';
            echo "Refresh Token = " . $token->refresh_token . '<br/>';
            echo "Token type = " . $token->token_type . '<br/>';
            echo "Expires in = " . $token->expires_in . '<br/>';
            echo "ID Token = " . $token->id_token . '<br/>';
            echo "Created = " . $token->created . '<br/>';
            echo "<a class='logout' href='?logout'>Logout</a>";
        } else {
            $authUrl = $client->createAuthUrl();
            print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }
        ?>
    </body>
</html>

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

VS 2017 Git Local Commit DB.lock error on every commit

My automatically generated .gitignore file contained /.vs instead of .vs/. Fixing this typo fixed the problem!

Simplest SOAP example

Thomas:

JSON is preferred for front end use because we have easy lookups. Therefore you have no XML to deal with. SOAP is a pain without using a library because of this. Somebody mentioned SOAPClient, which is a good library, we started with it for our project. However it had some limitations and we had to rewrite large chunks of it. It's been released as SOAPjs and supports passing complex objects to the server, and includes some sample proxy code to consume services from other domains.

How to import a class from default package

From the Java language spec:

It is a compile time error to import a type from the unnamed package.

You'll have to access the class via reflection or some other indirect method.

Executing <script> elements inserted with .innerHTML

Try function eval().

data.newScript = '<script type="text/javascript">//my script...</script>'
var element = document.getElementById('elementToRefresh');
element.innerHTML = data.newScript;
eval(element.firstChild.innerHTML);

This is a real example from a project that i am developing. Thanks to this post

In bash, how to store a return value in a variable?

Something like this could be used, and still maintaining meanings of return (to return control signals) and echo (to return information) and logging statements (to print debug/info messages).

v_verbose=1
v_verbose_f=""         # verbose file name
FLAG_BGPID=""

e_verbose() {
        if [[ $v_verbose -ge 0 ]]; then
                v_verbose_f=$(tempfile)
                tail -f $v_verbose_f &
                FLAG_BGPID="$!"
        fi
}

d_verbose() {
        if [[ x"$FLAG_BGPID" != "x" ]]; then
                kill $FLAG_BGPID > /dev/null
                FLAG_BGPID=""
                rm -f $v_verbose_f > /dev/null
        fi
}

init() {
        e_verbose

        trap cleanup SIGINT SIGQUIT SIGKILL SIGSTOP SIGTERM SIGHUP SIGTSTP
}

cleanup() {
        d_verbose
}

init

fun1() {
    echo "got $1" >> $v_verbose_f
    echo "got $2" >> $v_verbose_f
    echo "$(( $1 + $2 ))"
    return 0
}

a=$(fun1 10 20)
if [[ $? -eq 0 ]]; then
    echo ">>sum: $a"
else
    echo "error: $?"
fi
cleanup

In here, I'm redirecting debug messages to separate file, that is watched by tail, and if there is any changes then printing the change, trap is used to make sure that background process always ends.

This behavior can also be achieved using redirection to /dev/stderr, But difference can be seen at the time of piping output of one command to input of other command.

Create a Path from String in Java7

If possible I would suggest creating the Path directly from the path elements:

Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\\dir1\\dir2\\dir3"

How do I find the date a video (.AVI .MP4) was actually recorded?

There doesn't seem to be a well defined standard for video metadata (compared to photos and audio files, which have EXIF and ID3/etc. respectively)

Some tags exists like e.g. Title, Composer etc. You can see those if you select a movie file in Windows 7 (perhaps earlier versions also) explorer or right click and view properties. I have not found a tag for recording date unfortunately - the closest thing available is Year (integer) :-(

Programatically, you can read and write most of these tags in .NET using Taglib Sharp from the mono project. Source and binaries are available on the banshee FTP server. It has a pretty impressive list of formats it supports (but still, make sure you catch exceptions when trying to read or write tags - it will throw whenever it finds a file it cannot understand, something which happened to me several times for my modest collection of home recordings.)

To read tags:

using (var f = TagLib.File.Create(@"c:\Path\To\MyVideo.mp4"))
{
    if (f.Tag != null)
    {
        string title = f.Tag.Title;
        Size resolution = new Size(f.Properties.VideoWidth, f.Properties.VideoHeight);
        int year = f.Tag.Year;
        // etc.
    }
}

And similarly, to write metadata back to the file:

using (var f = TagLib.File.Create(@"c:\Path\To\MyVideo.mp4"))
{
    f.Tag.Title = "My Awesome Movie";
    f.Tag.Year = (uint)2011;
    f.Save();
}

How to delete cookies on an ASP.NET website

Unfortunately, for me, setting "Expires" did not always work. The cookie was unaffected.

This code did work for me:

HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

where "ASP.NET_SessionId" is the name of the cookie. This does not really delete the cookie, but overrides it with a blank cookie, which was close enough for me.

How to find the Number of CPU Cores via .NET/C#?

WMI queries are slow, so try to Select only the desired members instead of using Select *.

The following query takes 3.4s:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())

While this one takes 0.122s:

foreach (var item in new System.Management.ManagementObjectSearcher("Select NumberOfCores from Win32_Processor").Get())

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

Hi you can try viewing this jsFiddle.

I used this code:

var day = $(this).datepicker('getDate').getDate();  
var month = $(this).datepicker('getDate').getMonth();  
var year = $(this).datepicker('getDate').getYear();  

I hope this helps.

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

If you are using maven then you can add the tomcat7-maven-plugin to your pom.xml and it shall run fine. This plugin will run the project on Tomcat servlet container version 7.0.47 which supports JDK 1.8.

    <plugins>
    <plugin>
     <groupId>org.apache.tomcat.maven</groupId>
     <artifactId>tomcat7-maven-plugin</artifactId>
     <version>2.2</version>
     <configuration>
<!-- Include context file for Datasource configuration -->
     <contextFile>./src/main/webapp/META-INF/context.xml</contextFile>
    <port>8080</port>
     </configuration>
     <dependencies>
<!-- Include jdbc driver dependency if using datasource (in my case oracle) -->
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.4.0</version>
    </dependency>
  </dependencies>
    </plugin>
    </plugins>

Hope this is useful! Thanks

Connection to SQL Server Works Sometimes

Try a simple SQL Server restart first before doing anything drastic. Might fix it. It did for me

jQuery UI tabs. How to select a tab based on its id not based on index

Note: Due to changes made to jQuery 1.9 and jQuery UI, this answer is no longer the correct one. Please see @stankovski's answer below.

You need to find the tab's index first (which is just its position in a list) and then specifically select the tab using jQuery UI's provided select event (tabs->select).

var index = $('#tabs ul').index($('#tabId'));
$('#tabs ul').tabs('select', index);

Update: BTW - I do realize that this is (ultimately) still selecting by index. But, it doesn't require that you know the specific position of the tabs (particularly when they are dynamically generated as asked in the question).

uncaught syntaxerror unexpected token U JSON

This answer can be a possible solution from many. This answer is for the people who are facing this error while working with File Upload..

We were using middleware for token based encryption - decryption and we encountered same error.

Following was our code in route file:

  router.route("/uploadVideoMessage")
  .post(
    middleware.checkToken,
    upload.single("video_file"),
    videoMessageController.uploadVideoMessage
  );

here we were calling middleware before upload function and that was causing the error. So when we changed it to this, it worked.

router.route("/uploadVideoMessage")
  .post(
    upload.single("video_file"),
    middleware.checkToken,
    videoMessageController.uploadVideoMessage
  );

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

For more explanation read THIS LINK, it is option of Babel compiler that commands to not include superfluous whitespace characters and line terminators. some times ago its threshold was 100KB but now is 500KB.

I proffer you disable this option in your development environment, with this code in .babelrc file.

{
    "env": {
      "development" : {
        "compact": false
      }
    }
}

For production environment Babel use the default config which is auto.

Error: Segmentation fault (core dumped)

In my case I imported pyxlsd module before module wich works with db Mysql. After I did put Mysql module first(upper in code) it became to work like a clock. Think there was some namespace issue.