Programs & Examples On #Gwt tablayoutpanel

The GWT TabLayoutPanel component

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This happened to me when using java sdk. The problem was for me was i wasnt using the session token from assumed role.

Working code example ( in kotlin )

        val identityUserPoolProviderClient = AWSCognitoIdentityProviderClientBuilder
            .standard()
            .withCredentials(AWSStaticCredentialsProvider(BasicSessionCredentials("accessKeyId", ""secretAccessKey, "sessionToken")))
            .build()

OpenCV with Network Cameras

I just do it like this:

CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");

Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL

opencv_ffmpeg200d.dll

The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.

hth

Si

How can I configure my makefile for debug and release builds?

Completing the answers from earlier... You need to reference the variables you define info in your commands...

DEBUG ?= 1
ifeq (DEBUG, 1)
    CFLAGS =-g3 -gdwarf2 -DDEBUG
else
    CFLAGS=-DNDEBUG
endif

CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)

all: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

CommandParser.tab.o: CommandParser.y
    bison -d CommandParser.y
    $(CXX) -c CommandParser.tab.c

Command.o: Command.cpp
    $(CXX) -c Command.cpp

clean:
    rm -f CommandParser.tab.* CommandParser.yy.* output *.o

Using Pipes within ngModel on INPUT Elements in Angular

You can't use Template expression operators(pipe, save navigator) within template statement:

(ngModelChange)="Template statements"

(ngModelChange)="item.value | useMyPipeToFormatThatValue=$event"

https://angular.io/guide/template-syntax#template-statements

Like template expressions, template statements use a language that looks like JavaScript. The template statement parser differs from the template expression parser and specifically supports both basic assignment (=) and chaining expressions (with ; or ,).

However, certain JavaScript syntax is not allowed:

  • new
  • increment and decrement operators, ++ and --
  • operator assignment, such as += and -=
  • the bitwise operators | and &
  • the template expression operators

So you should write it as follows:

<input [ngModel]="item.value | useMyPipeToFormatThatValue" 
      (ngModelChange)="item.value=$event" name="inputField" type="text" />

Plunker Example

How can I define colors as variables in CSS?

Do not use css3 variables due to support.

I would do the following if you want a pure css solution.

  1. Use color classes with semenatic names.

    .bg-primary   { background: #880000; }
    
    .bg-secondary { background: #008800; }
    
    .bg-accent    { background: #F5F5F5; }
    
  2. Separate the structure from the skin (OOCSS)

    /* Instead of */
    
    h1 { 
        font-size: 2rem;
        line-height: 1.5rem;
        color: #8000;
    }
    
    /* use this */
    
    h1 { 
        font-size: 2rem;
        line-height: 1.5rem;
    }
    
    .bg-primary {
        background: #880000;
    }
    
    /* This will allow you to reuse colors in your design */
    
  3. Put these inside a separate css file to change as needed.

How to call jQuery function onclick?

Try this:

HTML:

<input type="submit" value="submit" name="submit" onclick="myfunction()">

jQuery:

<script type="text/javascript">
 function myfunction() 
 {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
 }
</script>

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

sql delete statement where date is greater than 30 days

Instead of converting to varchar to get just the day (convert(varchar(8), [Date], 112)), I prefer keeping it a datetime field and making it only the date (without the time).

SELECT * FROM Results 
WHERE CONVERT(date, [Date]) >= CONVERT(date, GETDATE())

XSD - how to allow elements in any order any number of times?

But from what I understand xs:choice still only allows single element selection. Hence setting the MaxOccurs to unbounded like this should only mean that "any one" of the child elements can appear multiple times. Is this accurate?

No. The choice happens individually for every "repetition" of xs:choice that occurs due to maxOccurs="unbounded". Therefore, the code that you have posted is correct, and will actually do what you want as written.

How to read AppSettings values from a .json file in ASP.NET Core

You can try below code. This is working for me.

public class Settings
{
    private static IHttpContextAccessor _HttpContextAccessor;

    public Settings(IHttpContextAccessor httpContextAccessor)
    {
        _HttpContextAccessor = httpContextAccessor;
    }

    public static void Configure(IHttpContextAccessor httpContextAccessor)
    {
        _HttpContextAccessor = httpContextAccessor;
    }

    public static IConfigurationBuilder Getbuilder()
    {
        var builder = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("appsettings.json");
        return builder;
    }

    public static string GetAppSetting(string key)
    {
        //return Convert.ToString(ConfigurationManager.AppSettings[key]);
        var builder = Getbuilder();
        var GetAppStringData = builder.Build().GetValue<string>("AppSettings:" + key);
        return GetAppStringData;
    }

    public static string GetConnectionString(string key="DefaultName")
    {
        var builder = Getbuilder();
        var ConnectionString = builder.Build().GetValue<string>("ConnectionStrings:"+key);
        return ConnectionString;
    }
}

Here I have created one class to get connection string and app settings.

I Startup.cs file you need to register class as below.

public class Startup
{

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
        Settings.Configure(httpContextAccessor);
    }
}

C# event with custom arguments

I might be late in the game, but how about:

public event Action<MyEvent> EventTriggered = delegate { }; 

private void Trigger(MyEvent e) 
{ 
     EventTriggered(e);
} 

Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.

I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.

Centering Bootstrap input fields

Try to use this code:

.col-lg-3 {
  width: 100%;
}
.input-group {
   width: 200px; // for exemple
   margin: 0 auto;
}

if it didn't work use !important

How do I turn off autocommit for a MySQL client?

Do you mean the mysql text console? Then:

START TRANSACTION;
  ...
  your queries.
  ...
COMMIT;

Is what I recommend.

However if you want to avoid typing this each time you need to run this sort of query, add the following to the [mysqld] section of your my.cnf file.

init_connect='set autocommit=0'

This would set autocommit to be off for every client though.

Put spacing between divs in a horizontal row?

A possible idea would be to:

  1. delete the width: 25%; float:left; from the style of your divs
  2. wrap each of the four colored divs in a div that has style="width: 25%; float:left;"

The advantage with this approach is that all four columns will have equal width and the gap between them will always be 5px * 2.

Here's what it looks like:

_x000D_
_x000D_
.cellContainer {_x000D_
  width: 25%;_x000D_
  float: left;_x000D_
}
_x000D_
<div style="width:100%; height: 200px; background-color: grey;">_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: red;">A</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: orange;">B</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: green;">C</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: blue;">D</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I find the size of a struct?

I assume you mean struct and not strict, but on a 32-bit system it'll be either 5 or 8 bytes, depending on if the compiler is padding the struct.

scp or sftp copy multiple files with single command

scp uses ssh for data transfer with the same authentication and provides the same security as ssh.

A best practise here is to implement "SSH KEYS AND PUBLIC KEY AUTHENTICATION". With this, you can write your scripts without worring about authentication. Simple as that.

See WHAT IS SSH-KEYGEN

How to pass an object from one activity to another on Android

Create two methods in your custom Class like this

public class Qabir {

    private int age;
    private String name;

    Qabir(){
    }

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

    // method for sending object
    public String toJSON(){
        return "{age:" + age + ",name:\"" +name +"\"}";
    }

    // method for get back original object
    public void initilizeWithJSONString(String jsonString){

        JSONObject json;        
        try {
            json =new JSONObject(jsonString );
            age=json.getInt("age");
            name=json.getString("name");
        } catch (JSONException e) {
            e.printStackTrace();
        } 
    }
}

Now in your sender Activity do like this

Qabir q= new Qabir(22,"KQ");    
Intent in=new Intent(this,SubActivity.class);
in.putExtra("obj", q.toJSON());
startActivity( in);

And in your receiver Activity

Qabir q =new Qabir();
q.initilizeWithJSONString(getIntent().getStringExtra("obj"));

What is time_t ultimately a typedef to?

Under Visual Studio 2008, it defaults to an __int64 unless you define _USE_32BIT_TIME_T. You're better off just pretending that you don't know what it's defined as, since it can (and will) change from platform to platform.

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Disable scrolling on `<input type=number>`

function fixNumericScrolling() {
$$( "input[type=number]" ).addEvent( "mousewheel", function(e) {
    stopAll(e);     
} );
}

function stopAll(e) {
if( typeof( e.preventDefault               ) != "undefined" ) e.preventDefault();
if( typeof( e.stopImmediatePropagation     ) != "undefined" ) e.stopImmediatePropagation();
if( typeof( event ) != "undefined" ) {
    if( typeof( event.preventDefault           ) != "undefined" ) event.preventDefault();
    if( typeof( event.stopImmediatePropagation ) != "undefined" ) event.stopImmediatePropagation();
}

return false;
}

How to start color picker on Mac OS?

You can call up the color picker from any Cocoa application (TextEdit, Mail, Keynote, Pages, etc.) by hitting Shift-Command-C

The following article explains more about using Mac OS's Color Picker.

http://www.macworld.com/article/46746/2005/09/colorpickersecrets.html

Can I run HTML files directly from GitHub, instead of just viewing their source?

i wanted to edit html and js in github and have a preview. i wanted to do it in github to have instant commits and saves.

tried rawgithub.com but rawgithub.com was not realtime (it's cache refreshes once a minute).

so i quickly developed my own solution:

node.js solution for this: https://github.com/shimondoodkin/rawgithub

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

public class JSElementLocator {

    @Test
    public void locateElement() throws InterruptedException{
        WebDriver driver = WebDriverProducerFactory.getWebDriver("firefox");

        driver.get("https://www.google.co.in/");


        WebElement searchbox = null;

        Thread.sleep(1000);
        searchbox = (WebElement) (((JavascriptExecutor) driver).executeScript("return document.getElementById('lst-ib');", searchbox));
        searchbox.sendKeys("hello");
    }
}

Make sure you are using the right locator for it.

hide div tag on mobile view only?

Set the display property to none as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px in the media query with whatever the minimum px value is where your div should be visible.

#title_message {
    display: none;
}

@media screen and (min-width: 768px) {
    #title_message {
        clear: both;
        display: block;
        float: left;
        margin: 10px auto 5px 20px;
        width: 28%;
    }
}

How to store arrays in MySQL?

The proper way to do this is to use multiple tables and JOIN them in your queries.

For example:

CREATE TABLE person (
`id` INT NOT NULL PRIMARY KEY,
`name` VARCHAR(50)
);

CREATE TABLE fruits (
`fruit_name` VARCHAR(20) NOT NULL PRIMARY KEY,
`color` VARCHAR(20),
`price` INT
);

CREATE TABLE person_fruit (
`person_id` INT NOT NULL,
`fruit_name` VARCHAR(20) NOT NULL,
PRIMARY KEY(`person_id`, `fruit_name`)
);

The person_fruit table contains one row for each fruit a person is associated with and effectively links the person and fruits tables together, I.E.

1 | "banana"
1 | "apple"
1 | "orange"
2 | "straberry"
2 | "banana"
2 | "apple"

When you want to retrieve a person and all of their fruit you can do something like this:

SELECT p.*, f.*
FROM person p
INNER JOIN person_fruit pf
ON pf.person_id = p.id
INNER JOIN fruits f
ON f.fruit_name = pf.fruit_name

How to remove focus from single editText

Since I was in a widget and not in an activity I did:

`getRootView().clearFocus();

How do I install TensorFlow's tensorboard?

pip install tensorflow.tensorboard  # install tensorboard
pip show tensorflow.tensorboard
# Location: c:\users\<name>\appdata\roaming\python\python35\site-packages
# now just run tensorboard as:
python c:\users\<name>\appdata\roaming\python\python35\site-packages\tensorboard\main.py --logdir=<logidr>

What's the correct way to communicate between controllers in AngularJS?

The top answer here was a work around from an Angular problem which no longer exists (at least in versions >1.2.16 and "probably earlier") as @zumalifeguard has mentioned. But I'm left reading all these answers without an actual solution.

It seems to me that the answer now should be

  • use $broadcast from the $rootScope
  • listen using $on from the local $scope that needs to know about the event

So to publish

// EXAMPLE PUBLISHER
angular.module('test').controller('CtrlPublish', ['$rootScope', '$scope',
function ($rootScope, $scope) {

  $rootScope.$broadcast('topic', 'message');

}]);

And subscribe

// EXAMPLE SUBSCRIBER
angular.module('test').controller('ctrlSubscribe', ['$scope',
function ($scope) {

  $scope.$on('topic', function (event, arg) { 
    $scope.receiver = 'got your ' + arg;
  });

}]);

Plunkers

If you register the listener on the local $scope, it will be destroyed automatically by $destroy itself when the associated controller is removed.

How should I tackle --secure-file-priv in MySQL?

I had the same problem with 'secure-file-priv'. Commenting in the .ini file didn't work and neither did moving file in directory specified by 'secure-file-priv'.

Finally, as dbc suggested, making 'secure-file-priv' equal to an empty string worked. So if anyone is stuck after trying answers above, hopefully doing this will help.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,

CURLOPT_COOKIEFILE  => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',

/**
 * Or set header
 * CURLOPT_HTTPHEADER => [
       'Cookie: foo=bar;baz=foo',
   ]
 */
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

echo $response;

How to find the Center Coordinate of Rectangle?

We can calculate using mid point of line formula,

centre (x,y) =  new Point((boundRect.tl().x+boundRect.br().x)/2,(boundRect.tl().y+boundRect.br().y)/2)

Use grep --exclude/--include syntax to not grep through certain files

those scripts don't accomplish all the problem...Try this better:

du -ha | grep -i -o "\./.*" | grep -v "\.svn\|another_file\|another_folder" | xargs grep -i -n "$1"

this script is so better, because it uses "real" regular expressions to avoid directories from search. just separate folder or file names with "\|" on the grep -v

enjoy it! found on my linux shell! XD

Can I open a dropdownlist using jQuery

I was trying to find the same thing and got disappointed. I ended up changing the attribute size for the select box so it appears to open

$('#countries').attr('size',6);

and then when you're finished

$('#countries').attr('size',1);

UIButton title text color

swift 5 version:

By using default inbuilt color:

  1. button.setTitleColor(UIColor.green, for: .normal)

OR

You can use your custom color by using RGB method:

  1. button.setTitleColor(UIColor(displayP3Red: 0.0/255.0, green: 180.0/255.0, blue: 2.0/255.0, alpha: 1.0), for: .normal)

Directory-tree listing in Python

A recursive implementation

import os

def scan_dir(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)
        if os.path.isfile(path):
            print path
        else:
            scan_dir(path)

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

RookieRick is right, using DataGridTemplateColumn instead of DataGridComboBoxColumn gives a much simpler XAML.

Moreover, putting the CompanyItem list directly accessible from the GridItem allows you to get rid of the RelativeSource.

IMHO, this give you a very clean solution.

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
    <DataGrid.Resources>
        <DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
            <TextBlock Text="{Binding Company}" />
        </DataTemplate>
        <DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
            <ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" />
        <DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
                                CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
    </DataGrid.Columns>
</DataGrid>

View model:

public class GridItem
{
    public string Name { get; set; }
    public CompanyItem Company { get; set; }
    public IEnumerable<CompanyItem> CompanyList { get; set; }
}

public class CompanyItem
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString() { return Name; }
}

public class ViewModel
{
    readonly ObservableCollection<CompanyItem> companies;

    public ViewModel()
    {
        companies = new ObservableCollection<CompanyItem>{
            new CompanyItem { ID = 1, Name = "Company 1" },
            new CompanyItem { ID = 2, Name = "Company 2" }
        };

        GridItems = new ObservableCollection<GridItem> {
            new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
        };
    }

    public ObservableCollection<GridItem> GridItems { get; set; }
}

Only get hash value using md5sum (without filename)

For the sake of completeness a way with sed using regex and capture group:

md5=$(md5sum "${my_iso_file}" | sed -r 's:\\*([^ ]*).*:\1:')

The regulare expression is capturing everything in a group until a space is reached. To get capture group working you need to capture everything in sed. (More about sed and caputer groups here: https://stackoverflow.com/a/2778096/10926293)
As delimiter in sed i use colons because they are not valid in file paths and i don't have to escape the slashed in the filepath.

System.Data.SqlClient.SqlException: Login failed for user

I had similar experience and it took me time to solve the problem. Though, my own case was ASP.Net MVC Core and Core framework. Setting Trusted_Connection=False; solved my problem.

Inside appsettings.json file

"ConnectionStrings": {
    "DefaultConnection": "Server=servername; Database=databasename; User Id=userid; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true",
  },

Right click to select a row in a Datagridview and show a menu to delete it

private void dataGridView1_CellContextMenuStripNeeded(object sender, 
DataGridViewCellContextMenuStripNeededEventArgs e)
{            
    if (e.RowIndex != -1)
    {
        dataGridView1.ClearSelection();
        this.dataGridView1.Rows[e.RowIndex].Selected = true;
        e.ContextMenuStrip = contextMenuStrip1;
    }
}

How do I grep for all non-ASCII characters?

Instead of making assumptions about the byte range of non-ASCII characters, as most of the above solutions do, it's slightly better IMO to be explicit about the actual byte range of ASCII characters instead.

So the first solution for instance would become:

grep --color='auto' -P -n '[^\x00-\x7F]' file.xml

(which basically greps for any character outside of the hexadecimal ASCII range: from \x00 up to \x7F)

On Mountain Lion that won't work (due to the lack of PCRE support in BSD grep), but with pcre installed via Homebrew, the following will work just as well:

pcregrep --color='auto' -n '[^\x00-\x7F]' file.xml

Any pros or cons that anyone can think off?

How can I measure the similarity between two images?

I wonder (and I'm really just throwing the idea out there to be shot down) if something could be derived by subtracting one image from the other, and then compressing the resulting image as a jpeg of gif, and taking the file size as a measure of similarity.

If you had two identical images, you'd get a white box, which would compress really well. The more the images differed, the more complex it would be to represent, and hence the less compressible.

Probably not an ideal test, and probably much slower than necessary, but it might work as a quick and dirty implementation.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused

When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.

The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.

Link to the issue number on GitHub within a commit message

they have an nice write up about the new issues 2.0 on their blog https://github.blog/2011-04-09-issues-2-0-the-next-generation/

synonyms include

  • fixes #xxx
  • fixed #xxx
  • fix #xxx
  • closes #xxx
  • close #xxx
  • closed #xxx

using any of the keywords in a commit message will make your commit either mentioned or close an issue.

Is it not possible to define multiple constructors in Python?

Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.

def __init__(self, city="Berlin"):
  self.city = city

How to navigate through a vector using iterators? (C++)

In C++-11 you can do:

std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
   // access by value, the type of i is int
   std::cout << i << ' ';
}
std::cout << '\n';

See here for variations: https://en.cppreference.com/w/cpp/language/range-for

Changing the highlight color when selecting text in an HTML text input

Here is the rub:

    ::selection {
      background: #ffb7b7; /* WebKit/Blink Browsers /
    }
    ::-moz-selection {
      background: #ffb7b7; / Gecko Browsers */
    }
Within the selection selector, color and background are the only properties that work. What you can do for some extra flair, is change the selection color for different paragraphs or different sections of the page.

All I did was use different selection color for paragraphs with different classes:

    p.red::selection {
      background: #ffb7b7;
    }
    p.red::-moz-selection {
      background: #ffb7b7;
    }
    p.blue::selection {
      background: #a8d1ff;
    }
    p.blue::-moz-selection {
      background: #a8d1ff;
    }
    p.yellow::selection {
      background: #fff2a8;
    }
    p.yellow::-moz-selection {
      background: #fff2a8;
    }
Note how the selectors are not combined, even though >the style block is doing the same thing. It doesn't work if you combine them:

<pre>/* Combining like this WILL NOT WORK */
p.yellow::selection,
p.yellow::-moz-selection {
  background: #fff2a8;
}</pre>

That's because browsers ignore the entire selector if there is a part of it they don't understand or is invalid. There is some exceptions to this (IE 7?) but not in relation to these selectors.

DEMO

LINK WHERE INFO IS FROM

What is the bower (and npm) version syntax?

In a nutshell, the syntax for Bower version numbers (and NPM's) is called SemVer, which is short for 'Semantic Versioning'. You can find documentation for the detailed syntax of SemVer as used in Bower and NPM on the API for the semver parser within Node/npm. You can learn more about the underlying spec (which does not mention ~ or other syntax details) at semver.org.

There's a super-handy visual semver calculator you can play with, making all of this much easier to grok and test.

SemVer isn't just a syntax! It has some pretty interesting things to say about the right ways to publish API's, which will help to understand what the syntax means. Crucially:

Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.

So, your specific question about ~ relates to that Major.Minor.Patch schema. (As does the related caret operator ^.) You can use ~ to narrow the range of versions you're willing to accept to either:

  • subsequent patch-level changes to the same minor version ("bug fixes not affecting the API"), or:
  • subsequent minor-level changes to the same major version ("backwards compatible API additions/changes")

For example: to indicate you'll take any subsequent patch-level changes on the 1.2.x tree, starting with 1.2.0, but less than 1.3.0, you could use:

"angular": "~1.2"
  or:
"angular": "~1.2.0"

This also gets you the same results as using the .x syntax:

"angular": "1.2.x"

But, you can use the tilde/~ syntax to be even more specific: if you're only willing to accept patch-level changes starting with 1.2.4, but still less than 1.3.0, you'd use:

"angular": "~1.2.4"

Moving left, towards the major version, if you use...

"angular": "~1"

... it's the same as...

"angular": "1.x"
  or:
"angular": "^1.0.0"

...and matches any minor- or patch-level changes above 1.0.0, and less than 2.0:

Note that last variation above: it's called a 'caret range'. The caret looks an awful lot like a >, so you'd be excused for thinking it means "any version greater than 1.0.0". (I've certainly slipped on that.) Nope!

Caret ranges are basically used to say that you care only about the left-most significant digit - usually the major version - and that you'll permit any minor- or patch-level changes that don't affect that left-most digit. Yet, unlike a tilde range that specifies a major version, caret ranges let you specify a precise minor/patch starting point. So, while ^1.0.0 === ~1, a caret range such as ^1.2.3 lets you say you'll take any changes >=1.2.3 && <2.0.0. You couldn't do that with a tilde range.

That all seems confusing at first, when you look at it up-close. But zoom out for a sec, and think about it this way: the caret simply lets you say that you're most concerned about whatever significant digit is left-most. The tilde lets you say you're most concerned about whichever digit is right-most. The rest is detail.

It's the expressive power of the tilde and the caret that explains why people use them much more than the simpler .x syntax: they simply let you do more. That's why you'll see the tilde used often even where .x would serve. As an example, see npm itself: its own package.json file includes lots of dependencies in ~2.4.0 format, rather than the 2.4.x format it could use. By sticking to ~, the syntax is consistent all the way down a list of 70+ versioned dependencies, regardless of which beginning patch number is acceptable.

Anyway, there's still more to SemVer, but I won't try to detail it all here. Check it out on the node semver package's readme. And be sure to use the semantic versioning calculator while you're practicing and trying to get your head around how SemVer works.


RE: Non-Consecutive Version Numbers: OP's final question seems to be about specifying non-consecutive version numbers/ranges (if I have edited it fairly). Yes, you can do that, using the common double-pipe "or" operator: ||. Like so:

"angular": "1.2 <= 1.2.9 || >2.0.0"

System.out.println() shortcut on Intellij IDEA

In Idea 17eap:

sout: Prints

System.out.println();

soutm: Prints current class and method names to System.out

System.out.println("$CLASS_NAME$.$METHOD_NAME$");

soutp: Prints method parameter names and values to System.out

System.out.println($FORMAT$);

soutv: Prints a value to System.out

System.out.println("$EXPR_COPY$ = " + $EXPR$);

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

Convert HTML5 into standalone Android App

You could use PhoneGap.

http://phonegap.com/

http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

Key value pairs using JSON

var object = {
    key1 : {
        name : 'xxxxxx',
        value : '100.0'
    },
    key2 : {
        name : 'yyyyyyy',
        value : '200.0'
    },
    key3 : {
        name : 'zzzzzz',
        value : '500.0'
    },
}

If thats how your object looks and you want to loop each name and value then I would try and do something like.

$.each(object,function(key,innerjson){
    /*
        key would be key1,key2,key3
        innerjson would be the name and value **
    */

    //Alerts and logging of the variable.
    console.log(innerjson); //should show you the value    
    alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});

How to show Page Loading div until the page has finished loading?

I have another below simple solution for this which perfectly worked for me.

First of all, create a CSS with name Lockon class which is transparent overlay along with loading GIF as shown below

.LockOn {
    display: block;
    visibility: visible;
    position: absolute;
    z-index: 999;
    top: 0px;
    left: 0px;
    width: 105%;
    height: 105%;
    background-color:white;
    vertical-align:bottom;
    padding-top: 20%; 
    filter: alpha(opacity=75); 
    opacity: 0.75; 
    font-size:large;
    color:blue;
    font-style:italic;
    font-weight:400;
    background-image: url("../Common/loadingGIF.gif");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
}

Now we need to create our div with this class which cover entire page as an overlay whenever the page is getting loaded

<div id="coverScreen"  class="LockOn">
</div>

Now we need to hide this cover screen whenever the page is ready and so that we can restrict the user from clicking/firing any event until the page is ready

$(window).on('load', function () {
$("#coverScreen").hide();
});

Above solution will be fine whenever the page is loading.

Now the question is after the page is loaded, whenever we click a button or an event which will take a long time, we need to show this in the client click event as shown below

$("#ucNoteGrid_grdViewNotes_ctl01_btnPrint").click(function () {
$("#coverScreen").show();
});

That means when we click this print button (which will take a long time to give the report) it will show our cover screen with GIF which gives this result and once the page is ready above windows on load function will fire and which hide the cover screen once the screen is fully loaded.

Redirect Windows cmd stdout and stderr to a single file

Anders Lindahl's answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1 is specified AFTER the 1> redirect, otherwise it will not work.

REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt

Is it possible to disable scrolling on a ViewPager

The answer of slayton works fine. If you want to stop swiping like a monkey you can override a OnPageChangeListener with

@Override public void onPageScrollStateChanged(final int state) { 
        switch (state) { 
            case ViewPager.SCROLL_STATE_SETTLING: 
                mPager.setPagingEnabled(false); 
                break; 
            case ViewPager.SCROLL_STATE_IDLE: 
                mPager.setPagingEnabled(true); 
                break; 
        } 
    }

So you can only swipe side by side

What is a pre-revprop-change hook in SVN, and how do I create it?

Thanks #patmortech

And I added your code which "only the same user can change his code".

:: Only allow editing of the same user.
for /f "tokens=*" %%a in ( 
'"%VISUALSVN_SERVER%\bin\svnlook.exe" author -r %revision% %repository%') do ( 
set orgAuthor=%%a
)
if /I not "%userName%" == "%orgAuthor%" goto ERROR_SAME_USER

How to call loading function with React useEffect only once

we developed a module on GitHub that has hooks for fetching data so you can use it like this for your purpose:

import { useFetching } from "react-concurrent";

const app = () => {
  const { data, isLoading, error , refetch } = useFetching(() =>
    fetch("http://example.com"),
  );
};

You can fork that out, but any PRs are welcome. https://github.com/hosseinmd/react-concurrent#react-concurrent

jwt check if token expired

Sadly @Andrés Montoya answer has a flaw which is related to how he compares the obj. I found a solution here which should solve this:

const now = Date.now().valueOf() / 1000

if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}
if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}

Thanks to thejohnfreeman!

How to copy a directory structure but only include certain files (using windows batch files)

Similar to Paulius' solution, but the files you don't care about are not copied then deleted:

@echo OFF

:: Replace c:\temp with the directory where folder1 resides.
cd c:\temp

:: You can make this more generic by passing in args for the source and destination folders.
for /f "usebackq" %%I in (`dir /b /s /a:-d folder1`) do @echo %%~nxI | find /V "data.zip" | find /v "info.txt" >> exclude_list.txt
xcopy folder1 copy_of_folder1 /EXCLUDE:exclude_list.txt /E /I

a tag as a submit button?

in my opinion the easiest way would be somthing like this:

<?php>
echo '<a href="link.php?submit='.$value.'">Submit</a>';
</?>

within the "link.php" you can request the value like this:

$_REQUEST['submit']

What is the best way to get the count/length/size of an iterator?

Your code will give you an exception when you reach the end of the iterator. You could do:

int i = 0;
while(iterator.hasNext()) {
    i++;
    iterator.next();
}

If you had access to the underlying collection, you would be able to call coll.size()...

EDIT OK you have amended...

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

Try this. The scope of local variables defined by "template" directive.

<table>
  <template ngFor let-group="$implicit" [ngForOf]="groups">
    <tr>
      <td>
        <h2>{{group.name}}</h2>
      </td>
    </tr>
    <tr *ngFor="let item of group.items">
                <td>{{item}}</td>
            </tr>
  </template>
</table>

How do I check if a string is valid JSON in Python?

Example Python script returns a boolean if a string is valid json:

import json

def is_json(myjson):
  try:
    json_object = json.loads(myjson)
  except ValueError as e:
    return False
  return True

Which prints:

print is_json("{}")                          #prints True
print is_json("{asdf}")                      #prints False
print is_json('{ "age":100}')                #prints True
print is_json("{'age':100 }")                #prints False
print is_json("{\"age\":100 }")              #prints True
print is_json('{"age":100 }')                #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True

Convert a JSON string to a Python dictionary:

import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo'])    #prints bar

mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]

Convert a python object to JSON string:

foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo))           #prints {"gummy": "bear"}

If you want access to low-level parsing, don't roll your own, use an existing library: http://www.json.org/

Great tutorial on python JSON module: https://pymotw.com/2/json/

Is String JSON and show syntax errors and error messages:

sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json

Prints:

, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.

json_xs is capable of syntax checking, parsing, prittifying, encoding, decoding and more:

https://metacpan.org/pod/json_xs

Where can I find the default timeout settings for all browsers?

After the last Firefox update we had the same session timeout issue and the following setting helped to resolve it.

We can control it with network.http.response.timeout parameter.

  1. Open Firefox and type in ‘about:config’ in the address bar and press Enter.
  2. Click on the "I'll be careful, I promise!" button.
  3. Type ‘timeout’ in the search box and network.http.response.timeout parameter will be displayed.
  4. Double-click on the network.http.response.timeout parameter and enter the time value (it is in seconds) that you don't want your session not to timeout, in the box.

Draw on HTML5 Canvas using a mouse

Here is my very simple working canvas draw and erase.

https://jsfiddle.net/richardcwc/d2gxjdva/

_x000D_
_x000D_
//Canvas_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
//Variables_x000D_
var canvasx = $(canvas).offset().left;_x000D_
var canvasy = $(canvas).offset().top;_x000D_
var last_mousex = last_mousey = 0;_x000D_
var mousex = mousey = 0;_x000D_
var mousedown = false;_x000D_
var tooltype = 'draw';_x000D_
_x000D_
//Mousedown_x000D_
$(canvas).on('mousedown', function(e) {_x000D_
    last_mousex = mousex = parseInt(e.clientX-canvasx);_x000D_
 last_mousey = mousey = parseInt(e.clientY-canvasy);_x000D_
    mousedown = true;_x000D_
});_x000D_
_x000D_
//Mouseup_x000D_
$(canvas).on('mouseup', function(e) {_x000D_
    mousedown = false;_x000D_
});_x000D_
_x000D_
//Mousemove_x000D_
$(canvas).on('mousemove', function(e) {_x000D_
    mousex = parseInt(e.clientX-canvasx);_x000D_
    mousey = parseInt(e.clientY-canvasy);_x000D_
    if(mousedown) {_x000D_
        ctx.beginPath();_x000D_
        if(tooltype=='draw') {_x000D_
            ctx.globalCompositeOperation = 'source-over';_x000D_
            ctx.strokeStyle = 'black';_x000D_
            ctx.lineWidth = 3;_x000D_
        } else {_x000D_
            ctx.globalCompositeOperation = 'destination-out';_x000D_
            ctx.lineWidth = 10;_x000D_
        }_x000D_
        ctx.moveTo(last_mousex,last_mousey);_x000D_
        ctx.lineTo(mousex,mousey);_x000D_
        ctx.lineJoin = ctx.lineCap = 'round';_x000D_
        ctx.stroke();_x000D_
    }_x000D_
    last_mousex = mousex;_x000D_
    last_mousey = mousey;_x000D_
    //Output_x000D_
    $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);_x000D_
});_x000D_
_x000D_
//Use draw|erase_x000D_
use_tool = function(tool) {_x000D_
    tooltype = tool; //update_x000D_
}
_x000D_
canvas {_x000D_
    cursor: crosshair;_x000D_
    border: 1px solid #000000;_x000D_
}
_x000D_
<canvas id="canvas" width="800" height="500"></canvas>_x000D_
<input type="button" value="draw" onclick="use_tool('draw');" />_x000D_
<input type="button" value="erase" onclick="use_tool('erase');" />_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

C#: Printing all properties of an object

Based on the ObjectDumper of the LINQ samples I created a version that dumps each of the properties on its own line.

This Class Sample

namespace MyNamespace
{
    public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }
        public IList<Hobby> Hobbies { get; set; }
    }

    public class Hobby
    {
        public string Name { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
        public int ZipCode { get; set; }
        public string City { get; set; }    
    }
}

has an output of

{MyNamespace.User}
  FirstName: "Arnold"
  LastName: "Schwarzenegger"
  Address: { }
    {MyNamespace.Address}
      Street: "6834 Hollywood Blvd"
      ZipCode: 90028
      City: "Hollywood"
  Hobbies: ...
    {MyNamespace.Hobby}
      Name: "body building"

Here is the code.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

public class ObjectDumper
{
    private int _level;
    private readonly int _indentSize;
    private readonly StringBuilder _stringBuilder;
    private readonly List<int> _hashListOfFoundElements;

    private ObjectDumper(int indentSize)
    {
        _indentSize = indentSize;
        _stringBuilder = new StringBuilder();
        _hashListOfFoundElements = new List<int>();
    }

    public static string Dump(object element)
    {
        return Dump(element, 2);
    }

    public static string Dump(object element, int indentSize)
    {
        var instance = new ObjectDumper(indentSize);
        return instance.DumpElement(element);
    }

    private string DumpElement(object element)
    {
        if (element == null || element is ValueType || element is string)
        {
            Write(FormatValue(element));
        }
        else
        {
            var objectType = element.GetType();
            if (!typeof(IEnumerable).IsAssignableFrom(objectType))
            {
                Write("{{{0}}}", objectType.FullName);
                _hashListOfFoundElements.Add(element.GetHashCode());
                _level++;
            }

            var enumerableElement = element as IEnumerable;
            if (enumerableElement != null)
            {
                foreach (object item in enumerableElement)
                {
                    if (item is IEnumerable && !(item is string))
                    {
                        _level++;
                        DumpElement(item);
                        _level--;
                    }
                    else
                    {
                        if (!AlreadyTouched(item))
                            DumpElement(item);
                        else
                            Write("{{{0}}} <-- bidirectional reference found", item.GetType().FullName);
                    }
                }
            }
            else
            {
                MemberInfo[] members = element.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
                foreach (var memberInfo in members)
                {
                    var fieldInfo = memberInfo as FieldInfo;
                    var propertyInfo = memberInfo as PropertyInfo;

                    if (fieldInfo == null && propertyInfo == null)
                        continue;

                    var type = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType;
                    object value = fieldInfo != null
                                       ? fieldInfo.GetValue(element)
                                       : propertyInfo.GetValue(element, null);

                    if (type.IsValueType || type == typeof(string))
                    {
                        Write("{0}: {1}", memberInfo.Name, FormatValue(value));
                    }
                    else
                    {
                        var isEnumerable = typeof(IEnumerable).IsAssignableFrom(type);
                        Write("{0}: {1}", memberInfo.Name, isEnumerable ? "..." : "{ }");

                        var alreadyTouched = !isEnumerable && AlreadyTouched(value);
                        _level++;
                        if (!alreadyTouched)
                            DumpElement(value);
                        else
                            Write("{{{0}}} <-- bidirectional reference found", value.GetType().FullName);
                        _level--;
                    }
                }
            }

            if (!typeof(IEnumerable).IsAssignableFrom(objectType))
            {
                _level--;
            }
        }

        return _stringBuilder.ToString();
    }

    private bool AlreadyTouched(object value)
    {
        if (value == null)
            return false;

        var hash = value.GetHashCode();
        for (var i = 0; i < _hashListOfFoundElements.Count; i++)
        {
            if (_hashListOfFoundElements[i] == hash)
                return true;
        }
        return false;
    }

    private void Write(string value, params object[] args)
    {
        var space = new string(' ', _level * _indentSize);

        if (args != null)
            value = string.Format(value, args);

        _stringBuilder.AppendLine(space + value);
    }

    private string FormatValue(object o)
    {
        if (o == null)
            return ("null");

        if (o is DateTime)
            return (((DateTime)o).ToShortDateString());

        if (o is string)
            return string.Format("\"{0}\"", o);

        if (o is char && (char)o == '\0') 
            return string.Empty; 

        if (o is ValueType)
            return (o.ToString());

        if (o is IEnumerable)
            return ("...");

        return ("{ }");
    }
}

and you can use it like that:

var dump = ObjectDumper.Dump(user);

Edit

  • Bi - directional references are now stopped. Therefore the HashCode of an object is stored in a list.
  • AlreadyTouched fixed (see comments)
  • FormatValue fixed (see comments)

Git Bash won't run my python files?

This works great on win7

$ PATH=$PATH:/c/Python27/ $ python -V Python 2.7.12

Screenshot

How to SUM and SUBTRACT using SQL?

I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.

-- Loan Outstanding
    select  'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
    from
    (
        select 
            sum(laod.dr) as Unit,
            sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
            sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
            sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
        from loan_account_opening as lao
        inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
        where lao.organization = 3
        union
        select
            sum(lr.installment)*-1 as Unit,
            sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
            sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
            sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
        from loan_recovery as lr
        inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
        where lo.organization = 3
    ) as t3

Angular 5 Scroll to top on every Route click

If you face this problem in Angular 6, you can fix it by adding the parameter scrollPositionRestoration: 'enabled' to app-routing.module.ts 's RouterModule:

@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'enabled'
  })],
  exports: [RouterModule]
})

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

Cygwin uses persistent shared memory sections, which can on occasion become corrupted. The symptom of this is that some Cygwin programs begin to fail, but other applications are unaffected. Since these shared memory sections are persistent, often a system reboot is needed to clear them out before the problem can be resolved.

Python Script execute commands in Terminal

I prefer usage of subprocess module:

from subprocess import call
call(["ls", "-l"])

Reason is that if you want to pass some variable in the script this gives very easy way for example take the following part of the code

abc = a.c
call(["vim", abc])

How to convert string to long

This is a common way to do it:

long l = Long.parseLong(str);

There is also this method: Long.valueOf(str); Difference is that parseLong returns a primitive long while valueOf returns a new Long() object.

Copy files on Windows Command Line with Progress

robocopy:

Robocopy, or "Robust File Copy", is a command-line directory and/or file replication command. Robocopy functionally replaces Xcopy, with more options. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was first introduced as a standard feature in Windows Vista and Windows Server 2008. The command is robocopy...

What is the difference between a hash join and a merge join (Oracle RDBMS )?

I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.

Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.

Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.

Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.

Copy data into another table

Insert Selected column with condition

INSERT INTO where_to_insert (col_1,col_2) SELECT col1, col2 FROM from_table WHERE condition;

Copy all data from one table to another with the same column name.

INSERT INTO where_to_insert 
SELECT * FROM from_table WHERE condition;

Learning to write a compiler

From the comp.compilers FAQ:

"Programming a Personal Computer" by Per Brinch Hansen Prentice-Hall 1982 ISBN 0-13-730283-5

This unfortunately-titled book explains the design and creation of a single-user programming environment for micros, using a Pascal-like language called Edison. The author presents all source code and explanations for the step-by-step implementation of an Edison compiler and simple supporting operating system, all written in Edison itself (except for a small supporting kernel written in a symbolic assembler for PDP 11/23; the complete source can also be ordered for the IBM PC).

The most interesting things about this book are: 1) its ability to demonstrate how to create a complete, self-contained, self-maintaining, useful compiler and operating system, and 2) the interesting discussion of language design and specification problems and trade-offs in Chapter 2.

"Brinch Hansen on Pascal Compilers" by Per Brinch Hansen Prentice-Hall 1985 ISBN 0-13-083098-4

Another light-on-theory heavy-on-pragmatics here's-how-to-code-it book. The author presents the design, implementation, and complete source code for a compiler and p-code interpreter for Pascal- (Pascal "minus"), a Pascal subset with boolean and integer types (but no characters, reals, subranged or enumerated types), constant and variable definitions and array and record types (but no packed, variant, set, pointer, nameless, renamed, or file types), expressions, assignment statements, nested procedure definitions with value and variable parameters, if statements, while statements, and begin-end blocks (but no function definitions, procedural parameters, goto statements and labels, case statements, repeat statements, for statements, and with statements).

The compiler and interpreter are written in Pascal* (Pascal "star"), a Pascal subset extended with some Edison-style features for creating software development systems. A Pascal* compiler for the IBM PC is sold by the author, but it's easy to port the book's Pascal- compiler to any convenient Pascal platform.

This book makes the design and implementation of a compiler look easy. I particularly like the way the author is concerned with quality, reliability, and testing. The compiler and interpreter can easily be used as the basis for a more involved language or compiler project, especially if you're pressed to quickly get something up and running.

How do I update zsh to the latest version?

If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):

  1. Get the latest version of the ZSH sourcecode

  2. Untar the download into its own directory then install: ./configure && make && make test && sudo make install

  3. This installs the the zsh binary at /usr/local/bin/zsh.

  4. You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...

  5. To make it your default shell you must first edit /etc/shells and add the new path. Then you can either run chsh -s /usr/local/bin/zsh or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".

  6. Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).

I need an unordered list without any bullets

This orders a list vertically without bullet points. In just one line!

li {
    display: block;
}

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Remove the space or empty line in server.xml or context.xml at the beginning of your code

How can I add to a List's first position?

Of course, Insert or AddFirst will do the trick, but you could always do:

myList.Reverse();
myList.Add(item);
myList.Reverse();

SSL certificate is not trusted - on mobile only

Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

preventDefault() on an <a> tag

Why not just do it in css?

Take out the 'href' attribute in your anchor tag

<ul class="product-info">
  <li>
    <a>YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>

In your css,

  a{
    cursor: pointer;
    }

Predefined type 'System.ValueTuple´2´ is not defined or imported

For .NET 4.6.2 or lower, .NET Core 1.x, and .NET Standard 1.x you need to install the NuGet package System.ValueTuple:

Install-Package "System.ValueTuple"

Or using a package reference in VS 2017:

<PackageReference Include="System.ValueTuple" Version="4.4.0" />

.NET Framework 4.7, .NET Core 2.0, and .NET Standard 2.0 include these types.

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


Why can't I use switch statement on a String?

If you have a place in your code where you can switch on a String, then it may be better to refactor the String to be an enumeration of the possible values, which you can switch on. Of course, you limit the potential values of Strings you can have to those in the enumeration, which may or may not be desired.

Of course your enumeration could have an entry for 'other', and a fromString(String) method, then you could have

ValueEnum enumval = ValueEnum.fromString(myString);
switch (enumval) {
   case MILK: lap(); break;
   case WATER: sip(); break;
   case BEER: quaff(); break;
   case OTHER: 
   default: dance(); break;
}

Append an empty row in dataframe using pandas

Assuming df is your dataframe,

df_prime = pd.concat([df, pd.DataFrame([[np.nan] * df.shape[1]], columns=df.columns)], ignore_index=True)

where df_prime equals df with an additional last row of NaN's.

Note that pd.concat is slow so if you need this functionality in a loop, it's best to avoid using it. In that case, assuming your index is incremental, you can use

df.loc[df.iloc[-1].name + 1,:] = np.nan

Write HTML to string

You can use T4 Templates for generating Html (or any) from your code. see this: http://msdn.microsoft.com/en-us/library/ee844259.aspx

How to resolve 'npm should be run outside of the node repl, in your normal shell'

enter image description here

Just open Node.js commmand promt as run as administrator

Center Contents of Bootstrap row container

For Bootstrap 4, use the below code:

<div class="mx-auto" style="width: 200px;">
  Centered element
</div>

Ref: https://getbootstrap.com/docs/4.0/utilities/spacing/#horizontal-centering

Oracle date "Between" Query

Date Between Query

SELECT *
    FROM emp
    WHERE HIREDATE between to_date (to_char(sysdate, 'yyyy') ||'/09/01', 'yyyy/mm/dd')
    AND to_date (to_char(sysdate, 'yyyy') + 1|| '/08/31', 'yyyy/mm/dd');

How can I use jQuery to move a div across the screen

In jQuery 1.2 and newer you no longer have to position the element absolutely; you can use normal relative positioning and use += or -= to add to or subtract from properties, e.g.

$("#startAnimation").click(function(){
    $(".toBeAnimated").animate({ 
        marginLeft: "+=250px",
    }, 1000 );
});

And to echo the guy who answered first's advice: Javascript is not performant. Don't overuse animations, or expect things than run nice and fast on your high performance PC on Chrome to look good on a bog-standard PC running IE. Test it, and make sure it degrades well!

Remove non-numeric characters (except periods and commas) from a string

I'm surprised there's been no mention of filter_var here for this being such an old question...

PHP has a built in method of doing this using sanitization filters. Specifically, the one to use in this situation is FILTER_SANITIZE_NUMBER_FLOAT with the FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND flags. Like so:

$numeric_filtered = filter_var("AR3,373.31", FILTER_SANITIZE_NUMBER_FLOAT,
    FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
echo $numeric_filtered; // Will print "3,373.31"

It might also be worthwhile to note that because it's built-in to PHP, it's slightly faster than using regex with PHP's current libraries (albeit literally in nanoseconds).

What is an ORM, how does it work, and how should I use one?

Can anyone give me a brief explanation...

Sure.

ORM stands for "Object to Relational Mapping" where

  • The Object part is the one you use with your programming language ( python in this case )

  • The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )

  • And finally the Mapping part is where you do a bridge between your objects and your tables.

In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.

So let's say you have this object.

 class Employee:
      def __init__( self, name ): 
          self.__name = name

       def getName( self ):
           return self.__name

       #etc.

and the table

   create table employee(
          name varcar(10),
          -- etc  
    )

Using an ORM framework would allow you to map that object with a db record automagically and write something like:

   emp = Employee("Ryan")

   orm.save( emp )

And have the employee inserted into the DB.

Oops it was not that brief but I hope it is simple enough to catch other articles you read.

gulp command not found - error after installing gulp

In my case it was that I had to install gulp-cli by command npm -g install gulp-cli

How to open html file?

I encountered this problem today as well. I am using Windows and the system language by default is Chinese. Hence, someone may encounter this Unicode error similarly. Simply add encoding = 'utf-8':

with open("test.html", "r", encoding='utf-8') as f:
    text= f.read()

Java 'file.delete()' Is not Deleting Specified File

In my case I was processing a set of jar files contained in a directory. After I processed them I tried to delete them from that directory, but they wouldn't delete. I was using JarFile to process them and the problem was that I forgot to close the JarFile when I was done.

Hover and Active only when not disabled

If you are using LESS or Sass, You can try this:

.btn {
  &[disabled] {
    opacity: 0.6;
  }
  &:hover, &:active {
    &:not([disabled]) {
      background-color: darken($orange, 15);
    }
  }
}

Group dataframe and get sum AND count?

df.groupby('Company Name').agg({'Organisation name':'count','Amount':'sum'})\
    .apply(lambda x: x.sort_values(['count','sum'], ascending=False))

Toolbar navigation icon never set

In case you don't wish to set the toolbar as the action bar, you can use this:

        val toggle = ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        toggle.isDrawerSlideAnimationEnabled = false
        toggle.isDrawerIndicatorEnabled = false
        toggle.setHomeAsUpIndicator(AppCompatResources.getDrawable(this, ...))
        drawer!!.addDrawerListener(toggle)
        toggle.setToolbarNavigationClickListener {
            setDrawerOpened(!isDrawerOpened())
        }
        toggle.syncState()

fun setDrawerOpened(open: Boolean) {
    if (open == drawerLayout.isDrawerOpen(GravityCompat.START))
        return
    if (open)
        drawerLayout.openDrawer(GravityCompat.START)
    else drawerLayout.closeDrawer(GravityCompat.START)
}

Use child_process.execSync but keep output in console

You can simply use .toString().

var result = require('child_process').execSync('rsync -avAXz --info=progress2 "/src" "/dest"').toString();
console.log(result);

This has been tested on Node v8.5.0, I'm not sure about previous versions. According to @etov, it doesn't work on v6.3.1 - I'm not sure about in-between.


Edit: Looking back on this, I've realised that it doesn't actually answer the specific question because it doesn't show the output to you 'live' — only once the command has finished running.

However, I'm leaving this answer here because I know quite a few people come across this question just looking for how to print the result of the command after execution.

Remove a cookie

To reliably delete a cookie it's not enough to set it to expire anytime in the past, as computed by your PHP server. This is because client computers can and often do have times which differ from that of your server.

The best practice is to overwrite the current cookie with a blank cookie which expires one second in the future after the epoch (1 January 1970 00:00:00 UTC), as so:

setcookie("hello", "", 1);

How to do a https request with bad certificate?

Security note: Disabling security checks is dangerous and should be avoided

You can disable security checks globally for all requests of the default client:

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func main() {
    http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
    _, err := http.Get("https://golang.org/")
    if err != nil {
        fmt.Println(err)
    }
}

You can disable security check for a client:

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func main() {
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
    _, err := client.Get("https://golang.org/")
    if err != nil {
        fmt.Println(err)
    }
}

C: How to free nodes in the linked list?

An iterative function to free your list:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

What the function is doing is the follow:

  1. check if head is NULL, if yes the list is empty and we just return

  2. Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next

  3. Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1

Recommendation for compressing JPG files with ImageMagick

I use always:

  • quality in 85
  • progressive (comprobed compression)
  • a very tiny gausssian blur to optimize the size (0.05 or 0.5 of radius) depends on the quality and size of the picture, this notably optimizes the size of the jpeg.
  • Strip any comment or EXIF metadata

in imagemagick should be

convert -strip -interlace Plane -gaussian-blur 0.05 -quality 85% source.jpg result.jpg

or in the newer version:

magick source.jpg -strip -interlace Plane -gaussian-blur 0.05 -quality 85% result.jpg

Source.

From @Fordi in the comments (Don't forget to upvote him if you like this): If you dislike blurring, use -sampling-factor 4:2:0 instead. What this does is reduce the chroma channel's resolution to half, without messing with the luminance resolution that your eyes latch onto. If you want better fidelity in the conversion, you can get a slight improvement without an increase in filesize by specifying -define jpeg:dct-method=float - that is, use the more accurate floating point discrete cosine transform, rather than the default fast integer version.

Hashing with SHA1 Algorithm in C#

I'll throw my hat in here:

(as part of a static class, as this snippet is two extensions)

//hex encoding of the hash, in uppercase.
public static string Sha1Hash (this string str)
{
    byte[] data = UTF8Encoding.UTF8.GetBytes (str);
    data = data.Sha1Hash ();
    return BitConverter.ToString (data).Replace ("-", "");
}
// Do the actual hashing
public static byte[] Sha1Hash (this byte[] data)
{
    using (SHA1Managed sha1 = new SHA1Managed ()) {
    return sha1.ComputeHash (data);
}

Spring Boot - How to get the running port

Starting with Spring Boot 1.4.0 you can use this in your test:

import org.springframework.boot.context.embedded.LocalServerPort;

@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {

  @LocalServerPort
  int randomPort;

  // ...
}

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

Looks like it's failing trying to open a connection to SQL Server.

You need to add a login to SQL Server for IIS APPPOOL\ASP.NET v4.0 and grant permissions to the database.

In SSMS, under the server, expand Security, then right click Logins and select "New Login...".

In the New Login dialog, enter the app pool as the login name and click "OK".

enter image description here

You can then right click the login for the app pool, select Properties and select "User Mapping". Check the appropriate database, and the appropriate roles. I think you could just select db_datareader and db_datawriter, but I think you would still need to grant permissions to execute stored procedures if you do that through EF. You can check the details for the roles here.

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
          .ContinueWith((taskwithresponse) =>
          {
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.

EDIT 2:

There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

check all socket opened in linux OS

Also you can use ss utility to dump sockets statistics.

To dump summary:

ss -s

Total: 91 (kernel 0)
TCP:   18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -        
RAW       0         0         0        
UDP       4         2         2        
TCP       18        16        2        
INET      22        18        4        
FRAG      0         0         0

To display all sockets:

ss -a

To display UDP sockets:

ss -u -a

To display TCP sockets:

ss -t -a

Here you can read ss man: ss

Installing tkinter on ubuntu 14.04

Install the package python-tk like

sudo apt-get install python-tk

That is described (with apt-cache search python-tk as)

Tkinter - Writing Tk applications with Python

IE7 Z-Index Layering Issues

In IE positioned elements generate a new stacking context, starting with a z-index value of 0. Therefore z-index doesn’t work correctly.

Try give the parent element a higher z-index value (can be even higher than the child’s z-index value itself) to fix the bug.

How to remove a build from itunes connect?

I had this problem. I'll share my ride on the learning curve.

First, I couldn't find how to reject the binary but remembered seeing it earlier today in the iTunesConnect App. So using the App I rejected the binary.

If you "mouse over" the rejected binary under the "Build" section you'll notice that a red circle icon with a - (i.e. a delete button) appears. Tap on this and then hit the save button at the top of the screen. Submitted binary is now gone.

You should now get all the notifications for the app being in state "Prepare for Upload" (email, App notification etc).

Xcode organiser was still giving me "Redundant Binary". After a bit of research I now understand the difference between "Version" & "Build". Version is what iTunes displays and the user sees. Build is just the internal tracking number. I had both at 2.3.0, I changed build to 2.3.0.1 and re-Archive. Now it validates and I can upload the new binary and re-submit. Hope that helps others!

Set a cookie to never expire

Can't you just say a never ending loop, cookie expires as current date + 1 so it never hits the date it's supposed to expire on because it's always tomorrow? A bit overkill but just saying.

Route [login] not defined

I ran into this error recently after using Laravel's built-in authentication routing using php artisan make:auth. When you run that command, these new routes are added to your web.php file:

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

I must have accidentally deleted these routes. Running php artisan make:auth again restored the routes and solved the problem. I'm running Laravel 5.5.28.

How to configure socket connect timeout

I dont program in C# but in C, we solve the same problem by making the socket non-blocking and then putting the fd in a select/poll loop with a timeout value equal to the amount of time we are willing to wait for the connect to succeed.

I found this for Visual C++ and the explanation there also bends towards the select/poll mechanism I explained before.

In my experience, you cannot change connect timeout values per socket. You change it for all (by tuning OS parameters).

Count the number of occurrences of each letter in string

//c code for count the occurence of each character in a string.

void main()
   {
   int i,j; int c[26],count=0; char a[]="shahid";
   clrscr();
   for(i=0;i<26;i++)
    {
        count=0;
          for(j=0;j<strlen(a);j++)
                {
                 if(a[j]==97+i)
                    {
                     count++;
                         }
                           }
                  c[i]=count;
               }
              for(i=0;i<26;i++)
               {
              j=97+i;
          if(c[i]!=0) {  printf("%c of %d times\n",j,c[i]);
                 }
              }
           getch();
           }

How do you create a read-only user in PostgreSQL?

Taken from a link posted in response to despesz' link.

Postgres 9.x appears to have the capability to do what is requested. See the Grant On Database Objects paragraph of:

http://www.postgresql.org/docs/current/interactive/sql-grant.html

Where it says: "There is also an option to grant privileges on all objects of the same type within one or more schemas. This functionality is currently supported only for tables, sequences, and functions (but note that ALL TABLES is considered to include views and foreign tables)."

This page also discusses use of ROLEs and a PRIVILEGE called "ALL PRIVILEGES".

Also present is information about how GRANT functionalities compare to SQL standards.

Quick Sort Vs Merge Sort

I personally wanted to test the difference between Quick sort and merge sort myself and saw the running times for a sample of 1,000,000 elements.

Quick sort was able to do it in 156 milliseconds whereas Merge sort did the same in 247 milliseconds

The Quick sort data, however, was random and quick sort performs well if the data is random where as its not the case with merge sort i.e. merge sort performs the same, irrespective of whether data is sorted or not. But merge sort requires one full extra space and quick sort does not as its an in-place sort

I have written comprehensive working program for them will illustrative pictures too.

How do I kill all the processes in Mysql "show processlist"?

An easy way would be to restart the mysql server.. Open "services.msc" in windows Run, select Mysql from the list. Right click and stop the service. Then Start again and all the processes would have been killed except the one (the default reserved connection)

How do I create a nice-looking DMG for Mac OS X using command-line tools?

.DS_Store files stores windows settings in Mac. Windows settings include the icons layout, the window background, the size of the window, etc. The .DS_Store file is needed in creating the window for mounted images to preserve the arrangement of files and the windows background.

Once you have .DS_Store file created, you can just copy it to your created installer (DMG).

Best way to represent a fraction in Java?

Even though you have the methods compareTo(), if you want to make use of utilities like Collections.sort(), then you should also implement Comparable.

public class Fraction extends Number implements Comparable<Fraction> {
 ...
}

Also, for pretty display I recommend overriding toString()

public String toString() {
    return this.getNumerator() + "/" + this.getDenominator();
}

And finally, I'd make the class public so that you can use it from different packages.

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);

Using LINQ to group a list of objects

is this what you want?

var grouped = CustomerList.GroupBy(m => m.GroupID).Select((n) => new { GroupId = n.Key, Items = n.ToList() });

Why can't DateTime.Parse parse UTC date

or use the AdjustToUniversal DateTimeStyle in a call to

DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles)

How to parse JSON response from Alamofire API in Swift?

I found the answer on GitHub for Swift2

https://github.com/Alamofire/Alamofire/issues/641

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
    .responseJSON { request, response, result in
        switch result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

        case .Failure(let data, let error):
            print("Request failed with error: \(error)")

            if let data = data {
                print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
            }
        }
    }

"psql: could not connect to server: Connection refused" Error when connecting to remote database

Try to migrate your database. For instance, if you are using Heroku to host your project and with Django, then try heroku run python manage.py migrate command; the error should go away.

What exactly is node.js used for?

What can we build with NodeJS:

  • REST APIs and Backend Applications
  • Real-Time services (Chat, Games etc)
  • Blogs, CMS, Social Applications.
  • Utilities and Tools
  • Anything that is not CPU intensive.

How to get URL of current page in PHP

You can use $_SERVER['HTTP_REFERER'] this will give you whole URL for example:

suppose you want to get url of site name www.example.com then $_SERVER['HTTP_REFERER'] will give you https://www.example.com

Easiest way to ignore blank lines when reading a file in Python

@S.Lott

The following code processes lines one at a time and produces a result that isn't memory eager:

filename = 'english names.txt'

with open(filename) as f_in:
    lines = (line.rstrip() for line in f_in)
    lines = (line for line in lines if line)
    the_strange_sum = 0
    for l in lines:
        the_strange_sum += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.find(l[0])

print the_strange_sum

So the generator (line.rstrip() for line in f_in) is quite the same acceptable than the nonblank_lines() function.

Use CSS to remove the space between images

An easy way that is compatible pretty much everywhere is to set font-size: 0 on the container, provided you don't have any descendent text nodes you need to style (though it is trivial to override this where needed).

.nospace {
   font-size: 0;
}

jsFiddle.

You could also change from the default display: inline into block or inline-block. Be sure to use the workarounds required for <= IE7 (and possibly ancient Firefoxes) for inline-block to work.

SQL ROWNUM how to return rows between a specific range

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

Note the double nested view. ROWNUM is evaluated before ORDER BY, so it is required for correct numbering.

If you omit ORDER BY clause, you won't get consistent order.

How do I send a file in Android from a mobile device to server using http?

This can be done with a HTTP Post request to the server:

HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");

method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));

HttpResponse response = http.execute(method);

How can I get log4j to delete old rotating log files?

There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.

Simple instructions found here

From 1:

If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.

How to get value of checked item from CheckedListBox?

EDIT: I realized a little late that it was bound to a DataTable. In that case the idea is the same, and you can cast to a DataRowView then take its Row property to get a DataRow if you want to work with that class.

foreach (var item in checkedListBox1.CheckedItems)
{
    var row = (item as DataRowView).Row;
    MessageBox.Show(row["ID"] + ": " + row["CompanyName"]);
}

You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:

foreach (var item in checkedListBox1.CheckedItems)
{
    var row = (item as DataRowView).Row;
    int id = row.Field<int>("ID");
    string name = row.Field<string>("CompanyName");
    MessageBox.Show(id + ": " + name);
}

You need to cast the item to access the properties of your class.

foreach (var item in checkedListBox1.CheckedItems)
{
    var company = (Company)item;
    MessageBox.Show(company.Id + ": " + company.CompanyName);
}

Alternately, you could use the OfType extension method to get strongly typed results back without explicitly casting within the loop:

foreach (var item in checkedListBox1.CheckedItems.OfType<Company>())
{
    MessageBox.Show(item.Id + ": " + item.CompanyName);
}

Serving static web resources in Spring Boot & Spring Security application

i had the same issue with my spring boot application, so I thought it will be nice if i will share with you guys my solution. I just simply configure the antMatchers to be suited to specific type of filles. In my case that was only js filles and js.map. Here is a code:

   @Configuration
   @EnableWebSecurity
   public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
      .antMatchers("/index.html", "/", "/home", 
       "/login","/favicon.ico","/*.js","/*.js.map").permitAll()
      .anyRequest().authenticated().and().csrf().disable();
   }
  }

What is interesting. I find out that resources path like "resources/myStyle.css" in antMatcher didnt work for me at all. If you will have folder inside your resoruces folder just add it in antMatcher like "/myFolder/myFille.js"* and it should work just fine.

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

Could not find a version that satisfies the requirement <package>

This approach (having all dependencies in a directory and not downloading from an index) only works when the directory contains all packages. The directory should therefore contain all dependencies but also all packages that those dependencies depend on (e.g., six, pytz etc).

You should therefore manually include these in requirements.txt (so that the first step downloads them explicitly) or you should install all packages using PyPI and then pip freeze > requirements.txt to store the list of all packages needed.

How do I print debug messages in the Google Chrome JavaScript Console?

Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.

(Or create your own console.log() which just returns false.)

How to specify the default error page in web.xml?

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

Change color of Button when Mouse is over

<Button Content="Click" Width="200" Height="50">
<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="LightGreen" TargetName="Border" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Button.Style>

How to check if C string is empty

First replace the scanf() with fgets() ...

do {
    if (!fgets(url, sizeof url, stdin)) /* error */;
    /* ... */
} while (*url != '\n');

Convert a date format in epoch

  String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
   DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
        LocalDateTime zdt  = LocalDateTime.parse(dateTime,dtf);
        LocalDateTime now = LocalDateTime.now();
        ZoneId zone = ZoneId.of("Asia/Kolkata");
        ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
        long a= zdt.toInstant(zoneOffSet).toEpochMilli();
        Log.d("time","---"+a);

you can get zone id form this a link!

How do I check whether a file exists without exceptions?

Additionally, os.access():

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()

Being R_OK, W_OK, and X_OK the flags to test for permissions (doc).

In Bash, how can I check if a string begins with some value?

@OP, for both your questions you can use case/esac:

string="node001"
case "$string" in
  node*) echo "found";;
  * ) echo "no node";;
esac

Second question

case "$HOST" in
 node*) echo "ok";;
 user) echo "ok";;
esac

case "$HOST" in
 node*|user) echo "ok";;
esac

Or Bash 4.0

case "$HOST" in
 user) ;&
 node*) echo "ok";;
esac

Having services in React application

Well the most used pattern for reusable logic I have come across is either writing a hook or creating a utils file. It depends on what you want to accomplish.

hooks/useForm.js

Like if you want to validate form data then I would create a custom hook named useForm.js and provide it form data and in return it would return me an object containing two things:

Object: {
    value,
    error,
}

You can definitely return more things from it as you progress.

utils/URL.js

Another example would be like you want to extract some information from a URL then I would create a utils file for it containing a function and import it where needed:

 export function getURLParam(p) {
...
}

Index of duplicates items in a python list

string_list = ['A', 'B', 'C', 'B', 'D', 'B']
pos_list = []
for i in range(len(string_list)):
    if string_list[i] = ='B':
        pos_list.append(i)
print pos_list

How do I get the current date and current time only respectively in Django?

import datetime
datetime.datetime.now().strftime ("%Y%m%d")
20151015

For the time

from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18

Check if a div does NOT exist with javascript

Try getting the element with the ID and check if the return value is null:

document.getElementById('some_nonexistent_id') === null

If you're using jQuery, you can do:

$('#some_nonexistent_id').length === 0

How do I fix MSB3073 error in my post-build event?

I was getting this error after downloading some source code from Github. Specifically the rust oxide development framework. My problem is that the Steam.ps1 script file, that's used to update some of the dlls from Steam was blocked by the OS. I had to open the files properties an UNBLOCK it. I had not realized this was done to ps1 files as well as exes.

What are queues in jQuery?

To understand queue method, you have to understand how jQuery does animation. If you write multiple animate method calls one after the other, jQuery creates an 'internal' queue and adds these method calls to it. Then it runs those animate calls one by one.

Consider following code.

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    //This is the reason that nonStopAnimation method will return immeidately
    //after queuing these calls. 
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);

    //By calling the same function at the end of last animation, we can
    //create non stop animation. 
    $('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}

The 'queue'/'dequeue' method gives you control over this 'animation queue'.

By default the animation queue is named 'fx'. I have created a sample page here which has various examples which will illustrate how the queue method could be used.

http://jsbin.com/zoluge/1/edit?html,output

Code for above sample page:

$(document).ready(function() {
    $('#nonStopAnimation').click(nonStopAnimation);

    $('#stopAnimationQueue').click(function() {
        //By default all animation for particular 'selector'
        //are queued in queue named 'fx'.
        //By clearning that queue, you can stop the animation.
        $('#box').queue('fx', []);
    });

    $('#addAnimation').click(function() {
        $('#box').queue(function() {
            $(this).animate({ height : '-=25'}, 2000);
            //De-queue our newly queued function so that queues
            //can keep running.
            $(this).dequeue();
        });
    });

    $('#stopAnimation').click(function() {
        $('#box').stop();
    });

    setInterval(function() {
        $('#currentQueueLength').html(
         'Current Animation Queue Length for #box ' + 
          $('#box').queue('fx').length
        );
    }, 2000);
});

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);
    $('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}

Now you may ask, why should I bother with this queue? Normally, you wont. But if you have a complicated animation sequence which you want to control, then queue/dequeue methods are your friend.

Also see this interesting conversation on jQuery group about creating a complicated animation sequence.

http://groups.google.com/group/jquery-en/browse_thread/thread/b398ad505a9b0512/f4f3e841eab5f5a2?lnk=gst

Demo of the animation:

http://www.exfer.net/test/jquery/tabslide/

Let me know if you still have questions.

How to set the max value and min value of <input> in html5 by javascript or jquery?

jQuery makes it easy to set any attributes for an element - just use the .attr() method:

$(document).ready(function() {
    $("input").attr({
       "max" : 10,        // substitute your own
       "min" : 2          // values (or variables) here
    });
});

The document ready handler is not required if your script block appears after the element(s) you want to manipulate.

Using a selector of "input" will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:

$("#idHere").attr(...

...or with a class:

$(".classHere").attr(...

The total number of locks exceeds the lock table size

If you have properly structured your tables so that each contains relatively unique values, then the less intensive way to do this would be to do 3 separate insert-into statements, 1 for each table, with the join-filter in place for each insert -

INSERT INTO SkusBought...

SELECT t1.customer, t1.SKU, t1.TypeDesc
FROM transactiondatatransit AS T1
LEFT OUTER JOIN topThreetransit AS T2
ON t1.customer = t2.customernum
WHERE T2.customernum IS NOT NULL

Repeat this for the other two tables - copy/paste is a fine method, simply change the FROM table name. ** IF you are trying to prevent duplicated entries in your SkusBought table you can add the following join code in each section prior to the WHERE clause.

LEFT OUTER JOIN SkusBought AS T3
ON  t1.customer = t3.customer
AND t1.sku = t3.sku

-and then the last line of WHERE clause-

AND t3.customer IS NULL

Your initial code is using a number of sub-queries, and the UNION statement can be expensive as it will first create its own temporary table to populate the data from the three separate sources before inserting into the table you want ALONG with running another sub-query to filter results.

How to remove selected commit log entries from a Git repository while keeping their changes?

You can non-interactively remove B and C in your example with:

git rebase --onto HEAD~5 HEAD~3 HEAD

or symbolically,

git rebase --onto A C HEAD

Note that the changes in B and C will not be in D; they will be gone.

Kill a Process by Looking up the Port being used by it from a .BAT

Paste this into command line

FOR /F "tokens=5 delims= " %P IN ('netstat -ano ^| find "LISTENING" ^| find ":8080 "') DO (TASKKILL /PID %P)

If you want to use it in a batch pu %%P instead of %P

Get height and width of a layout programmatically

As I just ran into this problem thought I would write it for kotlin,

my_view.viewTreeObserver.addOnGlobalLayoutListener {
       // here your view is measured
       // get height using my_view.height
       // get width using my_view.width
    }

or

my_view.post {
       // here your view is measured
       // get height using my_view.height
       // get width using my_view.width
    }

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

What is the difference between char * const and const char *?

I would like to point out that using int const * (or const int *) isn't about a pointer pointing to a const int variable, but that this variable is const for this specific pointer.

For example:

int var = 10;
int const * _p = &var;

The code above compiles perfectly fine. _p points to a const variable, although var itself isn't constant.

Deploying my application at the root in Tomcat

You have a couple of options:

  1. Remove the out-of-the-box ROOT/ directory from tomcat and rename your war file to ROOT.war before deploying it.

  2. Deploy your war as (from your example) war_name.war and configure the context root in conf/server.xml to use your war file :

    <Context path="" docBase="war_name" debug="0" reloadable="true"></Context>
    

The first one is easier, but a little more kludgy. The second one is probably the more elegant way to do it.

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/ directory, or Scripts\ on Windows).

The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Looks like you have a query that is taking longer than it should. From your stack trace and your code you should be able to determine exactly what query that is.

This type of timeout can have three causes;

  1. There's a deadlock somewhere
  2. The database's statistics and/or query plan cache are incorrect
  3. The query is too complex and needs to be tuned

A deadlock can be difficult to fix, but it's easy to determine whether that is the case. Connect to your database with Sql Server Management Studio. In the left pane right-click on the server node and select Activity Monitor. Take a look at the running processes. Normally most will be idle or running. When the problem occurs you can identify any blocked process by the process state. If you right-click on the process and select details it'll show you the last query executed by the process.

The second issue will cause the database to use a sub-optimal query plan. It can be resolved by clearing the statistics:

exec sp_updatestats

If that doesn't work you could also try

dbcc freeproccache

You should not do this when your server is under heavy load because it will temporarily incur a big performace hit as all stored procs and queries are recompiled when first executed. However, since you state the issue occurs sometimes, and the stack trace indicates your application is starting up, I think you're running a query that is only run on occasionally. You may be better off by forcing SQL Server not to reuse a previous query plan. See this answer for details on how to do that.

I've already touched on the third issue, but you can easily determine whether the query needs tuning by executing the query manually, for example using Sql Server Management Studio. If the query takes too long to complete, even after resetting the statistics you'll probably need to tune it. For help with that, you should post the exact query in a new question.

Alternative to google finance api

I followed the top answer and started looking at yahoo finance. Their API can be accessed a number of different ways, but I found a nice reference for getting stock info as a CSV here: http://www.jarloo.com/

Using that I wrote this script. I'm not really a ruby guy but this might help you hack something together. I haven't come up with variable names for all the fields yahoo offers yet, so you can fill those in if you need them.

Here's the usage

TICKERS_SP500 = "GICS,CIK,MMM,ABT,ABBV,ACN,ACE,ACT,ADBE,ADT,AES,AET,AFL,AMG,A,GAS,APD,ARG,AKAM,AA,ALXN,ATI,ALLE,ADS,ALL,ALTR,MO,AMZN,AEE,AAL,AEP,AXP,AIG,AMT,AMP,ABC,AME,AMGN,APH,APC,ADI,AON,APA,AIV,AAPL,AMAT,ADM,AIZ,T,ADSK,ADP,AN,AZO,AVGO,AVB,AVY,BHI,BLL,BAC,BK,BCR,BAX,BBT,BDX,BBBY,BBY,BIIB,BLK,HRB,BA,BWA,BXP,BSX,BMY,BRCM,BFB,CHRW,CA,CVC,COG,CAM,CPB,COF,CAH,HSIC,KMX,CCL,CAT,CBG,CBS,CELG,CNP,CTL,CERN,CF,SCHW,CHK,CVX,CMG,CB,CI,XEC,CINF,CTAS,CSCO,C,CTXS,CLX,CME,CMS,COH,KO,CCE,CTSH,CL,CMA,CSC,CAG,COP,CNX,ED,STZ,GLW,COST,CCI,CSX,CMI,CVS,DHI,DHR,DRI,DVA,DE,DLPH,DAL,XRAY,DVN,DO,DTV,DFS,DG,DLTR,D,DOV,DOW,DPS,DTE,DD,DUK,DNB,ETFC,EMN,ETN,EBAY,ECL,EIX,EW,EA,EMC,EMR,ENDP,ESV,ETR,EOG,EQT,EFX,EQIX,EQR,ESS,EL,ES,EXC,EXPE,EXPD,ESRX,XOM,FFIV,FB,FDO,FAST,FDX,FIS,FITB,FSLR,FE,FISV,FLIR,FLS,FLR,FMC,FTI,F,FOSL,BEN,FCX,FTR,GME,GCI,GPS,GRMN,GD,GE,GGP,GIS,GM,GPC,GNW,GILD,GS,GT,GOOG,GWW,HAL,HBI,HOG,HAR,HRS,HIG,HAS,HCA,HCP,HCN,HP,HES,HPQ,HD,HON,HRL,HSP,HST,HCBK,HUM,HBAN,ITW,IR,TEG,INTC,ICE,IBM,IP,IPG,IFF,INTU,ISRG,IVZ,IRM,JEC,JNJ,JCI,JOY,JPM,JNPR,KSU,K,KEY,GMCR,KMB,KIM,KMI,KLAC,KSS,KRFT,KR,LB,LLL,LH,LRCX,LM,LEG,LEN,LVLT,LUK,LLY,LNC,LLTC,LMT,L,LO,LOW,LYB,MTB,MAC,M,MNK,MRO,MPC,MAR,MMC,MLM,MAS,MA,MAT,MKC,MCD,MHFI,MCK,MJN,MWV,MDT,MRK,MET,KORS,MCHP,MU,MSFT,MHK,TAP,MDLZ,MON,MNST,MCO,MS,MOS,MSI,MUR,MYL,NDAQ,NOV,NAVI,NTAP,NFLX,NWL,NFX,NEM,NWSA,NEE,NLSN,NKE,NI,NE,NBL,JWN,NSC,NTRS,NOC,NRG,NUE,NVDA,ORLY,OXY,OMC,OKE,ORCL,OI,PCAR,PLL,PH,PDCO,PAYX,PNR,PBCT,POM,PEP,PKI,PRGO,PFE,PCG,PM,PSX,PNW,PXD,PBI,PCL,PNC,RL,PPG,PPL,PX,PCP,PCLN,PFG,PG,PGR,PLD,PRU,PEG,PSA,PHM,PVH,QEP,PWR,QCOM,DGX,RRC,RTN,RHT,REGN,RF,RSG,RAI,RHI,ROK,COL,ROP,ROST,RCL,R,CRM,SNDK,SCG,SLB,SNI,STX,SEE,SRE,SHW,SIAL,SPG,SWKS,SLG,SJM,SNA,SO,LUV,SWN,SE,STJ,SWK,SPLS,SBUX,HOT,STT,SRCL,SYK,STI,SYMC,SYY,TROW,TGT,TEL,TE,THC,TDC,TSO,TXN,TXT,HSY,TRV,TMO,TIF,TWX,TWC,TJX,TMK,TSS,TSCO,RIG,TRIP,FOXA,TSN,TYC,USB,UA,UNP,UNH,UPS,URI,UTX,UHS,UNM,URBN,VFC,VLO,VAR,VTR,VRSN,VZ,VRTX,VIAB,V,VNO,VMC,WMT,WBA,DIS,WM,WAT,ANTM,WFC,WDC,WU,WY,WHR,WFM,WMB,WIN,WEC,WYN,WYNN,XEL,XRX,XLNX,XL,XYL,YHOO,YUM,ZMH,ZION,ZTS,SAIC,AP"

AllData = loadStockInfo(TICKERS_SP500, allParameters())

SpecificData = loadStockInfo("GOOG,CIK", "ask,dps")

loadStockInfo returns a hash, such that SpecificData["GOOG"]["name"] is "Google Inc."

Finally, the actual code to run that...

require 'net/http'

# Jack Franzen & Garin Bedian
# Based on http://www.jarloo.com/yahoo_finance/

$parametersData = Hash[[

    ["symbol", ["s", "Symbol"]],
    ["ask", ["a", "Ask"]],
    ["divYield", ["y", "Dividend Yield"]],
    ["bid", ["b", "Bid"]],
    ["dps", ["d", "Dividend per Share"]],
    #["noname", ["b2", "Ask (Realtime)"]],
    #["noname", ["r1", "Dividend Pay Date"]],
    #["noname", ["b3", "Bid (Realtime)"]],
    #["noname", ["q", "Ex-Dividend Date"]],
    #["noname", ["p", "Previous Close"]],
    #["noname", ["o", "Open"]],
    #["noname", ["c1", "Change"]],
    #["noname", ["d1", "Last Trade Date"]],
    #["noname", ["c", "Change &amp; Percent Change"]],
    #["noname", ["d2", "Trade Date"]],
    #["noname", ["c6", "Change (Realtime)"]],
    #["noname", ["t1", "Last Trade Time"]],
    #["noname", ["k2", "Change Percent (Realtime)"]],
    #["noname", ["p2", "Change in Percent"]],
    #["noname", ["c8", "After Hours Change (Realtime)"]],
    #["noname", ["m5", "Change From 200 Day Moving Average"]],
    #["noname", ["c3", "Commission"]],
    #["noname", ["m6", "Percent Change From 200 Day Moving Average"]],
    #["noname", ["g", "Day’s Low"]],
    #["noname", ["m7", "Change From 50 Day Moving Average"]],
    #["noname", ["h", "Day’s High"]],
    #["noname", ["m8", "Percent Change From 50 Day Moving Average"]],
    #["noname", ["k1", "Last Trade (Realtime) With Time"]],
    #["noname", ["m3", "50 Day Moving Average"]],
    #["noname", ["l", "Last Trade (With Time)"]],
    #["noname", ["m4", "200 Day Moving Average"]],
    #["noname", ["l1", "Last Trade (Price Only)"]],
    #["noname", ["t8", "1 yr Target Price"]],
    #["noname", ["w1", "Day’s Value Change"]],
    #["noname", ["g1", "Holdings Gain Percent"]],
    #["noname", ["w4", "Day’s Value Change (Realtime)"]],
    #["noname", ["g3", "Annualized Gain"]],
    #["noname", ["p1", "Price Paid"]],
    #["noname", ["g4", "Holdings Gain"]],
    #["noname", ["m", "Day’s Range"]],
    #["noname", ["g5", "Holdings Gain Percent (Realtime)"]],
    #["noname", ["m2", "Day’s Range (Realtime)"]],
    #["noname", ["g6", "Holdings Gain (Realtime)"]],
    #["noname", ["k", "52 Week High"]],
    #["noname", ["v", "More Info"]],
    #["noname", ["j", "52 week Low"]],
    #["noname", ["j1", "Market Capitalization"]],
    #["noname", ["j5", "Change From 52 Week Low"]],
    #["noname", ["j3", "Market Cap (Realtime)"]],
    #["noname", ["k4", "Change From 52 week High"]],
    #["noname", ["f6", "Float Shares"]],
    #["noname", ["j6", "Percent Change From 52 week Low"]],
    ["name", ["n", "Company Name"]],
    #["noname", ["k5", "Percent Change From 52 week High"]],
    #["noname", ["n4", "Notes"]],
    #["noname", ["w", "52 week Range"]],
    #["noname", ["s1", "Shares Owned"]],
    #["noname", ["x", "Stock Exchange"]],
    #["noname", ["j2", "Shares Outstanding"]],
    #["noname", ["v", "Volume"]],
    #["noname", ["a5", "Ask Size"]],
    #["noname", ["b6", "Bid Size"]],
    #["noname", ["k3", "Last Trade Size"]],
    #["noname", ["t7", "Ticker Trend"]],
    #["noname", ["a2", "Average Daily Volume"]],
    #["noname", ["t6", "Trade Links"]],
    #["noname", ["i5", "Order Book (Realtime)"]],
    #["noname", ["l2", "High Limit"]],
    #["noname", ["e", "Earnings per Share"]],
    #["noname", ["l3", "Low Limit"]],
    #["noname", ["e7", "EPS Estimate Current Year"]],
    #["noname", ["v1", "Holdings Value"]],
    #["noname", ["e8", "EPS Estimate Next Year"]],
    #["noname", ["v7", "Holdings Value (Realtime)"]],
    #["noname", ["e9", "EPS Estimate Next Quarter"]],
    #["noname", ["s6", "evenue"]],
    #["noname", ["b4", "Book Value"]],
    #["noname", ["j4", "EBITDA"]],
    #["noname", ["p5", "Price / Sales"]],
    #["noname", ["p6", "Price / Book"]],
    #["noname", ["r", "P/E Ratio"]],
    #["noname", ["r2", "P/E Ratio (Realtime)"]],
    #["noname", ["r5", "PEG Ratio"]],
    #["noname", ["r6", "Price / EPS Estimate Current Year"]],
    #["noname", ["r7", "Price / EPS Estimate Next Year"]],
    #["noname", ["s7", "Short Ratio"]

]]

def replaceCommas(data)
    s = ""
    inQuote = false
    data.split("").each do |a|
        if a=='"'
            inQuote = !inQuote
            s += '"'
        elsif !inQuote && a == ","
            s += "#"
        else
            s += a
        end
    end
    return s
end

def allParameters()
    s = ""
    $parametersData.keys.each do |i|
        s  = s + i + ","
    end
    return s
end

def prepareParameters(parametersText)
    pt = parametersText.split(",")
    if !pt.include? 'symbol'; pt.push("symbol"); end;
    if !pt.include? 'name'; pt.push("name"); end;
    p = []
    pt.each do |i|
        p.push([i, $parametersData[i][0]])
    end
    return p
end

def prepareURL(tickers, parameters)
    urlParameters = ""
    parameters.each do |i|
        urlParameters += i[1]
    end
    s = "http://download.finance.yahoo.com/d/quotes.csv?"
    s = s + "s=" + tickers + "&"
    s = s + "f=" + urlParameters
    return URI(s)
end

def loadStockInfo(tickers, parametersRaw)
    parameters = prepareParameters(parametersRaw)
    url = prepareURL(tickers, parameters)
    data = Net::HTTP.get(url)
    data = replaceCommas(data)
    h = CSVtoObject(data, parameters)
    logStockObjects(h, true)
end

#parse csv
def printCodes(substring, length)

    a = data.index(substring)
    b = data.byteslice(a, 10)
    puts "printing codes of string: "
    puts b
    puts b.split('').map(&:ord).to_s
end

def CSVtoObject(data, parameters)
    rawData = []
    lineBreaks = data.split(10.chr)
    lineBreaks.each_index do |i|
        rawData.push(lineBreaks[i].split("#"))
    end

    #puts "Found " + rawData.length.to_s + " Stocks"
    #puts "   w/ " + rawData[0].length.to_s + " Fields"

    h = Hash.new("MainHash")
    rawData.each_index do |i|
        o = Hash.new("StockObject"+i.to_s)
        #puts "parsing object" + rawData[i][0]
        rawData[i].each_index do |n|
            #puts "parsing parameter" + n.to_s + " " +parameters[n][0]
            o[ parameters[n][0] ] = rawData[i][n].gsub!(/^\"|\"?$/, '')
        end
        h[o["symbol"]] = o;
    end
    return h
end

def logStockObjects(h, concise)
    h.keys.each do |i|
        if concise
            puts "(" + h[i]["symbol"] + ")\t\t" + h[i]["name"]
        else
            puts ""
            puts h[i]["name"]
            h[i].keys.each do |p|
                puts "    " + $parametersData[p][1] + " : " + h[i][p].to_s
            end
        end
    end
end

MSVCP120d.dll missing

From the comments, the problem was caused by using dlls that were built with Visual Studio 2013 in a project compiled with Visual Studio 2012. The reason for this was a third party library named the folders containing the dlls vc11, vc12. One has to be careful with any system that uses the compiler version (less than 4 digits) since this does not match the version of Visual Studio (except for Visual Studio 2010).

  • vc8 = Visual Studio 2005
  • vc9 = Visual Studio 2008
  • vc10 = Visual Studio 2010
  • vc11 = Visual Studio 2012
  • vc12 = Visual Studio 2013
  • vc14 = Visual Studio 2015
  • vc15 = Visual Studio 2017
  • vc16 = Visual Studio 2019

The Microsoft C++ runtime dlls use a 2 or 3 digit code also based on the compiler version not the version of Visual Studio.

  • MSVCP80.DLL is from Visual Studio 2005
  • MSVCP90.DLL is from Visual Studio 2008
  • MSVCP100.DLL is from Visual Studio 2010
  • MSVCP110.DLL is from Visual Studio 2012
  • MSVCP120.DLL is from Visual Studio 2013
  • MSVCP140.DLL is from Visual Studio 2015, 2017 and 2019

There is binary compatibility between Visual Studio 2015, 2017 and 2019.

Python 3: EOF when reading a line (Sublime Text 2 is angry)

EOF is a special out-of-band signal which means the end of input. It's not a character (though in the old DOS days, 0x1B acted like EOF), but rather a signal from the OS that the input has ended.

On Windows, you can "input" an EOF by pressing Ctrl+Z at the command prompt. This signals the terminal to close the input stream, which presents an EOF to the running program. Note that on other OSes or terminal emulators, EOF is usually signalled using Ctrl+D.

As for your issue with Sublime Text 2, it seems that stdin is not connected to the terminal when running a program within Sublime, and so consequently programs start off connected to an empty file (probably nul or /dev/null). See also Python 3.1 and Sublime Text 2 error.

Get the first key name of a JavaScript object

You can query the content of an object, per its array position.
For instance:

 let obj = {plainKey: 'plain value'};

 let firstKey = Object.keys(obj)[0]; // "plainKey"
 let firstValue = Object.values(obj)[0]; // "plain value"

 /* or */

 let [key, value] = Object.entries(obj)[0]; // ["plainKey", "plain value"]

 console.log(key); // "plainKey"
 console.log(value); // "plain value"

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

datetimepicker is not a function jquery

I had the same problem with bootstrap datetimepicker extension. Including moment.js before datetimepicker.js was the solution.

How to delete an SVN project from SVN repository

"Obliberating" contents from a svn repository, i.e. wiping this contents from the disc, can be done as described in this article http://www.limilabs.com/blog/how-to-permanently-remove-svn-folder

It requires access to the server side svn repository, thus you must have some admin privileges.

It works by (a) dumping the repository content into a file, (b) excluding some contents and (c) wiping and re-creating the plain repository again and eventually by (d) loading the filtered repository contents:

svnadmin dump "path/to/svnrepo" > svnrepo.txt                    // (a)
svndumpfilter exclude "my/folder" < svnrepo.txt > filtered.txt   // (b)
rm -rf "path/to/svnrepo" && svnadmin create "path/to/svnrepo"    // (c)
svnadmin load "path/to/svnrepo" < filtered.txt                   // (d)

The repository counter is unchanged by this operations. However, your repository is now "missing" all those revision numbers used to create that contents you removed in step (b).

Subversion 1.7.5 appears to handle this "missing" revisions pretty well. Using "svn ls -r $missing" for example, reports the very same as "svn ls -r $(( missing - 1))".

Contrary to this, my (pretty old) VIEWVC reports "no contents" when querying a "missing" revision.

Large WCF web service request failing with (400) HTTP Bad Request

Try setting maxReceivedMessageSize on the server too, e.g. to 4MB:

    <binding name="MyService.MyServiceBinding" 
           maxReceivedMessageSize="4194304">

The main reason the default (65535 I believe) is so low is to reduce the risk of Denial of Service (DoS) attacks. You need to set it bigger than the maximum request size on the server, and the maximum response size on the client. If you're in an Intranet environment, the risk of DoS attacks is probably low, so it's probably safe to use a value much higher than you expect to need.

By the way a couple of tips for troubleshooting problems connecting to WCF services:

  • Enable tracing on the server as described in this MSDN article.

  • Use an HTTP debugging tool such as Fiddler on the client to inspect the HTTP traffic.

LINQ to SQL - How to select specific columns and return strongly typed list

The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!

How to read a text file into a list or an array with Python

You will have to split your string into a list of values using split()

So,

lines = text_file.read().split(',')

EDIT: I didn't realise there would be so much traction to this. Here's a more idiomatic approach.

import csv
with open('filename.csv', 'r') as fd:
    reader = csv.reader(fd)
    for row in reader:
        # do something

CentOS: Copy directory to another directory

As I understand, you want to recursively copy test directory into /home/server/ path...

This can be done as:

-cp -rf /home/server/folder/test/* /home/server/

Hope this helps

List<T> or IList<T>

You would because defining an IList or an ICollection would open up for other implementations of your interfaces.

You might want to have an IOrderRepository that defines a collection of orders in either a IList or ICollection. You could then have different kinds of implementations to provide a list of orders as long as they conform to "rules" defined by your IList or ICollection.

How to find a min/max with Ruby

If you need to find the max/min of a hash, you can use #max_by or #min_by

people = {'joe' => 21, 'bill' => 35, 'sally' => 24}

people.min_by { |name, age| age } #=> ["joe", 21]
people.max_by { |name, age| age } #=> ["bill", 35]

Genymotion Android emulator - adb access?

Just Go To the Genymotion Installation Directory and then in folder tools you will see adb.exe there open command prompt here and run adb commands

EF Core add-migration Build Failed

In my case I had couple of such errors:

The process cannot access the file 'C:\xxx\bin\Debug\netcoreapp3.1\yyy.dll' 
because it is being used by another process. [C:\zzz.csproj]

I was able to see those errors only after adding -v parameter.

The solution was to shutdown the Visual Studio and run the command again.

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

how to add value to a tuple?

    list_of_tuples = [('1', '2', '3', '4'),
                      ('2', '3', '4', '5'),
                      ('3', '4', '5', '6'),
                      ('4', '5', '6', '7')]


    def mod_tuples(list_of_tuples):
        for i in range(0, len(list_of_tuples)):
            addition = ''
            for x in list_of_tuples[i]:
                addition = addition + x
            list_of_tuples[i] = list_of_tuples[i] + (addition,)
        return list_of_tuples

    # check: 
    print mod_tuples(list_of_tuples)

Get list of data-* attributes using javascript / jQuery

One way of finding all data attributes is using element.attributes. Using .attributes, you can loop through all of the element attributes, filtering out the items which include the string "data-".

let element = document.getElementById("element");

function getDataAttributes(element){
    let elementAttributes = {},
        i = 0;

    while(i < element.attributes.length){
        if(element.attributes[i].name.includes("data-")){
            elementAttributes[element.attributes[i].name] = element.attributes[i].value
        }
        i++;
    }

    return elementAttributes;

}

Converting String to Double in Android

try this:

double d= Double.parseDouble(yourString);

VBA using ubound on a multidimensional array

You need to deal with the optional Rank parameter of UBound.

Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1)  '? returns 4
Debug.Print UBound(arr, 2)  '? returns 3

More at: UBound Function (Visual Basic)

Working Soap client example

Calculator SOAP service test from SoapUI, Online SoapClient Calculator

Generate the SoapMessage object form the input SoapEnvelopeXML and SoapDataXml.

SoapEnvelopeXML

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:Add xmlns:tem="http://tempuri.org/">
         <tem:intA>3</tem:intA>
         <tem:intB>4</tem:intB>
      </tem:Add>
   </soapenv:Body>
</soapenv:Envelope>

use the following code to get SoapMessage Object.

MessageFactory messageFactory = MessageFactory.newInstance();
    MimeHeaders headers = new MimeHeaders();
    ByteArrayInputStream xmlByteStream = new ByteArrayInputStream(SoapEnvelopeXML.getBytes());
SOAPMessage soapMsg = messageFactory.createMessage(headers, xmlByteStream);

SoapDataXml

<tem:Add xmlns:tem="http://tempuri.org/">
    <tem:intA>3</tem:intA>
    <tem:intB>4</tem:intB>
</tem:Add>

use below code to get SoapMessage Object.

public static SOAPMessage getSOAPMessagefromDataXML(String saopBodyXML) throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    dbFactory.setIgnoringComments(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    InputSource ips = new org.xml.sax.InputSource(new StringReader(saopBodyXML));
    Document docBody = dBuilder.parse(ips);
    System.out.println("Data Document: "+docBody.getDocumentElement());
    
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage soapMsg = messageFactory.createMessage();
    
    SOAPBody soapBody = soapMsg.getSOAPPart().getEnvelope().getBody();
    soapBody.addDocument(docBody);
    
    return soapMsg;
}

By getting the SoapMessage Object. It is clear that the Soap XML is valid. Then prepare to hit the service to get response. It can be done in many ways.

  1. Using Client Code Generated form WSDL.
java.net.URL endpointURL = new java.net.URL(endPointUrl);
javax.xml.rpc.Service service = new org.apache.axis.client.Service();
((org.apache.axis.client.Service) service).setTypeMappingVersion("1.2");
CalculatorSoap12Stub obj_axis = new CalculatorSoap12Stub(endpointURL, service);
int add = obj_axis.add(10, 20);
System.out.println("Response: "+ add);
  1. Using javax.xml.soap.SOAPConnection.
public static void getSOAPConnection(SOAPMessage soapMsg) throws Exception {
    System.out.println("===== SOAPConnection =====");
    MimeHeaders headers = soapMsg.getMimeHeaders(); // new MimeHeaders();
    headers.addHeader("SoapBinding",   serverDetails.get("SoapBinding") );
    headers.addHeader("MethodName",    serverDetails.get("MethodName") );
    headers.addHeader("SOAPAction",    serverDetails.get("SOAPAction") );
    headers.addHeader("Content-Type",  serverDetails.get("Content-Type"));
    headers.addHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
    if (soapMsg.saveRequired()) {
        soapMsg.saveChanges();
    }
    
    SOAPConnectionFactory newInstance = SOAPConnectionFactory.newInstance();
    javax.xml.soap.SOAPConnection connection = newInstance.createConnection();
    SOAPMessage soapMsgResponse = connection.call(soapMsg, getURL( serverDetails.get("SoapServerURI"), 5*1000 ));
    
    getSOAPXMLasString(soapMsgResponse);
}
  1. Form HTTP Connection Classes org.apache.commons.httpclient.
public static void getHttpConnection(SOAPMessage soapMsg) throws SOAPException, IOException {
    System.out.println("===== HttpClient =====");
    HttpClient httpClient = new HttpClient();
    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(3 * 1000); // Connection timed out
    params.setSoTimeout(3 * 1000);         // Request timed out
    params.setParameter("http.useragent", "Web Service Test Client");

    PostMethod methodPost = new PostMethod( serverDetails.get("SoapServerURI") );
    methodPost.setRequestBody( getSOAPXMLasString(soapMsg) );
    methodPost.setRequestHeader("Content-Type", serverDetails.get("Content-Type") );
    methodPost.setRequestHeader("SoapBinding",  serverDetails.get("SoapBinding") );
    methodPost.setRequestHeader("MethodName",   serverDetails.get("MethodName") );
    methodPost.setRequestHeader("SOAPAction",   serverDetails.get("SOAPAction") );

    methodPost.setRequestHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));

    try {
        int returnCode = httpClient.executeMethod(methodPost);
        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.out.println("The Post method is not implemented by this URI");
            methodPost.getResponseBodyAsString();
        } else {
            BufferedReader br = new BufferedReader(new InputStreamReader(methodPost.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                System.out.println(readLine);
            }
            br.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        methodPost.releaseConnection();
    }
}
public static void accessResource_AppachePOST(SOAPMessage soapMsg) throws Exception {
    System.out.println("===== HttpClientBuilder =====");
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    URIBuilder builder = new URIBuilder( serverDetails.get("SoapServerURI") );
    HttpPost methodPost = new HttpPost(builder.build());
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(5 * 1000)
            .setConnectionRequestTimeout(5 * 1000)
            .setSocketTimeout(5 * 1000)
            .build();
    methodPost.setConfig(config);
        HttpEntity xmlEntity = new StringEntity(getSOAPXMLasString(soapMsg), "utf-8");
    methodPost.setEntity(xmlEntity);
        
    methodPost.setHeader("Content-Type", serverDetails.get("Content-Type"));
    methodPost.setHeader("SoapBinding", serverDetails.get("SoapBinding") );
    methodPost.setHeader("MethodName", serverDetails.get("MethodName") );
    methodPost.setHeader("SOAPAction", serverDetails.get("SOAPAction") );
    methodPost.setHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
    
    // Create a custom response handler
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status <= 500) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }
            return "";
        }
    };
    String execute = httpClient.execute( methodPost, responseHandler );
    System.out.println("AppachePOST : "+execute);
}

Full Example:

public class SOAP_Calculator {
    static HashMap<String, String> serverDetails = new HashMap<>();
    static {
        // Calculator
        serverDetails.put("SoapServerURI", "http://www.dneonline.com/calculator.asmx");
        serverDetails.put("SoapWSDL", "http://www.dneonline.com/calculator.asmx?wsdl");
        serverDetails.put("SoapBinding", "CalculatorSoap");        // <wsdl:binding name="CalculatorSoap12" type="tns:CalculatorSoap">
        serverDetails.put("MethodName", "Add");                    // <wsdl:operation name="Add">
        serverDetails.put("SOAPAction", "http://tempuri.org/Add"); // <soap12:operation soapAction="http://tempuri.org/Add" style="document"/>
        serverDetails.put("SoapXML", "<tem:Add xmlns:tem=\"http://tempuri.org/\"><tem:intA>2</tem:intA><tem:intB>4</tem:intB></tem:Add>");
        
        serverDetails.put("Accept-Encoding", "gzip,deflate");
        serverDetails.put("Content-Type", "");
    }
    public static void callSoapService( ) throws Exception {
        String xmlData = serverDetails.get("SoapXML");
        
        SOAPMessage soapMsg = getSOAPMessagefromDataXML(xmlData);
        System.out.println("Requesting SOAP Message:\n"+ getSOAPXMLasString(soapMsg) +"\n");
        
        SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();
        if (envelope.getElementQName().getNamespaceURI().equals("http://schemas.xmlsoap.org/soap/envelope/")) {
            System.out.println("SOAP 1.1 NamespaceURI: http://schemas.xmlsoap.org/soap/envelope/");
            serverDetails.put("Content-Type", "text/xml; charset=utf-8");
        } else {
            System.out.println("SOAP 1.2 NamespaceURI: http://www.w3.org/2003/05/soap-envelope");
            serverDetails.put("Content-Type", "application/soap+xml; charset=utf-8");
        }
        
        getHttpConnection(soapMsg);
        getSOAPConnection(soapMsg);
        accessResource_AppachePOST(soapMsg);
    }
    public static void main(String[] args) throws Exception {
        callSoapService();
    }

    private static URL getURL(String endPointUrl, final int timeOutinSeconds) throws MalformedURLException {
        URL endpoint = new URL(null, endPointUrl, new URLStreamHandler() {
            protected URLConnection openConnection(URL url) throws IOException {
                URL clone = new URL(url.toString());
                URLConnection connection = clone.openConnection();
                connection.setConnectTimeout(timeOutinSeconds);
                connection.setReadTimeout(timeOutinSeconds);
                //connection.addRequestProperty("Developer-Mood", "Happy"); // Custom header
                return connection;
            }
        });
        return endpoint;
    }
    public static String getSOAPXMLasString(SOAPMessage soapMsg) throws SOAPException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapMsg.writeTo(out);
        // soapMsg.writeTo(System.out);
        String strMsg = new String(out.toByteArray());
        System.out.println("Soap XML: "+ strMsg);
        return strMsg;
    }
}

@See list of some WebServices at http://sofa.uqam.ca/soda/webservices.php

How can I reduce the waiting (ttfb) time

I have met the same problem. My project is running on the local server. I checked my php code.

$db = mysqli_connect('localhost', 'root', 'root', 'smart');

I use localhost to connect to my local database. That maybe the cause of the problem which you're describing. You can modify your HOSTS file. Add the line

127.0.0.1 localhost.

How to check if a file exists in Documents folder?

Swift 3:

let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:

let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)

Objective-C:

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

How to select all records from one table that do not exist in another table?

Watch out for pitfalls. If the field Name in Table1 contain Nulls you are in for surprises. Better is:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT ISNULL(name ,'')
     FROM table1)

What's the difference between OpenID and OAuth?

I believe it makes sense revisit this question as also pointed out in the comments, the introduction of OpenID Connect may have brought more confusion.

OpenID Connect is an authentication protocol like OpenID 1.0/2.0 but it is actually built on top of OAuth 2.0, so you'll get authorization features along with authentication features. The difference between the two is pretty well explained in detail in this (relatively recent, but important) article: http://oauth.net/articles/authentication/

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

COPY copies a file/directory from your host to your image.

ADD copies a file/directory from your host to your image, but can also fetch remote URLs, extract TAR files, etc...

Use COPY for simply copying files and/or directories into the build context.

Use ADD for downloading remote resources, extracting TAR files, etc..

Extract number from string with Oracle function

You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:

select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;

which will return "12345569".

also you can use this one:

select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
       regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual

which will return "12345569" for numbers and "StackOverFlow" for characters.

Adding line break in C# Code behind page

In C# there's no 'new line' character like there is in VB.NET. The end of a logical 'line' of code is denoted by a ';'. If you wish to break the line of code over multiple lines, just hit the carriage return (or if you want to programmatically add it (for programmatically generated code) insert 'Environment.NewLine' or '\r\n'.

Edit: In response to your comment: If you wish to break a string over multiple lines (i.e. programmatically), you should insert the Environment.NewLine character. This will take the environment into account in order to create the line ending. For instance, many environments, including Unix/Linux only use a NewLine character (\n), but Windows uses both carriage return and line feed (\r\n). So to break a string you would use:

string output = "Hello this is my string\r\nthat I want broken over multiple lines."

Of course, this would only be good for Windows, so before I get flamed for incorrect practice you should actually do this:

string output = string.Format("Hello this is my string{0}that I want broken over multiple lines.", Environment.NewLine);

Or if you want to break over multiple lines in your IDE, you would do:

string output = "My string"
              + "is split over"
              + "multiple lines";

Inserting the same value multiple times when formatting a string

Depends on what you mean by better. This works if your goal is removal of redundancy.

s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))

Difference between long and int data types

You're on a 32-bit machine or a 64-bit Windows machine. On my 64-bit machine (running a Unix-derivative O/S, not Windows), sizeof(int) == 4, but sizeof(long) == 8.

They're different types — sometimes the same size as each other, sometimes not.

(In the really old days, sizeof(int) == 2 and sizeof(long) == 4 — though that might have been the days before C++ existed, come to think of it. Still, technically, it is a legitimate configuration, albeit unusual outside of the embedded space, and quite possibly unusual even in the embedded space.)

How to implement HorizontalScrollView like Gallery?

You may use HorizontalScrollView to implement Horizontal scrolling.

Code

<HorizontalScrollView
android:id="@+id/hsv"
android:layout_width="fill_parent"
android:layout_height="100dp"
 android:layout_weight="0"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none" >
<LinearLayout
    android:id="@+id/innerLay"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:gravity="center_vertical"
    android:orientation="horizontal" >
    </LinearLayout>
    </HorizontalScrollView>

featured.xml:

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

      <RelativeLayout 
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
>

<ProgressBar                
    android:layout_width="15dip"       
    android:layout_height="15dip"
    android:id="@+id/progress" 
    android:layout_centerInParent="true"
    />

<ImageView
    android:id="@+id/image"       
    android:layout_width="fill_parent"       
    android:layout_height="fill_parent"
    android:background="#20000000"
    />

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="30dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:gravity="center"
    android:textColor="#000000"
    android:background="#ffffff"
    android:text="Image Text" />

      </RelativeLayout>
     </LinearLayout>

Java Code:

 LayoutInflater inflater;

    inflater=getLayoutInflater();
    LinearLayout inLay=(LinearLayout) findViewById(R.id.innerLay);

    for(int x=0;x<10;x++)
    {
        inLay.addView(getView(x));
    }




 View getView(final int x)
{
   View rootView = inflater.inflate( R.layout.featured_item,null);

   ImageView image = (ImageView) rootView.findViewById(R.id.image);

   //Thease Two Line is sufficient my dear to implement lazyLoading
   AQuery aq = new AQuery(rootView);
   String url="http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";
   aq.id(image).progress(R.id.progress).image(url, true, true, 0, R.drawable.placeholder1);
   image.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
     Toast.makeText(PhotoActivity.this, "Click Here Postion "+x,     

         Toast.LENGTH_LONG).show();
        }
    });
   return rootView;
       }

Note: to implement lazy loading, please use this link for AQUERY

https://code.google.com/p/android-query/wiki/ImageLoading

How to append binary data to a buffer in node.js

insert byte to specific place.

insertToArray(arr,index,item) {
   return Buffer.concat([arr.slice(0,index),Buffer.from(item,"utf-8"),arr.slice(index)]);
}

Auto-scaling input[type=text] to width of value?

Unfortunately the size attribute will not work very well. There will be extra space and too little space sometimes, depending on how the font is set up. (check out the example)

If you want this to work well, try watching for changes on the input, and resize it then. You probably want to set it to the input's scrollWidth. We would need to account for box sizing, too.

In the following example, I'm setting the size of the input to 1 to prevent it from having a scrollWidth that is greater than our initial width (set manually with CSS).

_x000D_
_x000D_
// (no-jquery document.ready)_x000D_
function onReady(f) {_x000D_
    "complete" === document.readyState_x000D_
        ? f() : setTimeout(onReady, 10, f);_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
    [].forEach.call(_x000D_
        document.querySelectorAll("input[type='text'].autoresize"),_x000D_
        registerInput_x000D_
    );_x000D_
});_x000D_
function registerInput(el) {_x000D_
    el.size = 1;_x000D_
    var style = el.currentStyle || window.getComputedStyle(el),_x000D_
        borderBox = style.boxSizing === "border-box",_x000D_
        boxSizing = borderBox_x000D_
            ? parseInt(style.borderRightWidth, 10) +_x000D_
                parseInt(style.borderLeftWidth, 10)_x000D_
            : 0;_x000D_
    if ("onpropertychange" in el) {_x000D_
         // IE_x000D_
         el.onpropertychange = adjust;_x000D_
    } else if ("oninput" in el) {_x000D_
         el.oninput = adjust;_x000D_
    }_x000D_
    adjust();_x000D_
_x000D_
    function adjust() {_x000D_
_x000D_
        // reset to smaller size (for if text deleted) _x000D_
        el.style.width = "";_x000D_
_x000D_
        // getting the scrollWidth should trigger a reflow_x000D_
        // and give you what the width would be in px if _x000D_
        // original style, less any box-sizing_x000D_
        var newWidth = el.scrollWidth + boxSizing;_x000D_
_x000D_
        // so let's set this to the new width!_x000D_
        el.style.width = newWidth + "px";_x000D_
    }_x000D_
}
_x000D_
* {_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
input.autoresize {_x000D_
  width: 125px;_x000D_
  min-width: 125px;_x000D_
  max-width: 400px;_x000D_
}_x000D_
input[type='text'] {_x000D_
  box-sizing: border-box;_x000D_
  padding: 4px 8px;_x000D_
  border-radius: 4px;_x000D_
  border: 1px solid #ccc;_x000D_
  margin-bottom: 10px;_x000D_
}
_x000D_
<label> _x000D_
  Resizes:_x000D_
  <input class="autoresize" placeholder="this will resize" type='text'>_x000D_
</label>_x000D_
<br/>_x000D_
<label>_x000D_
  Doesn't resize:_x000D_
<input placeholder="this will not" type='text'>_x000D_
</label>_x000D_
<br/>_x000D_
<label>_x000D_
  Has extra space to right:_x000D_
  <input value="123456789" size="9" type="text"/>_x000D_
</label>
_x000D_
_x000D_
_x000D_

I think this should work in even IE6, but don't take my word for it.

Depending on your use case, you may need to bind the adjust function to other events. E.g. changing an input's value programmatically, or changing the element's style's display property from none (where scrollWidth === 0) to block or inline-block, etc.

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

Just for the record: for me it turned out that it was the gem called 'mysql' ... obviously this is working with US-ASCII 8 bit by default. So changing it to the gem called mysql2 (the 2 is the important point here) solved all of my issues.

I looked @ the gem list posted above - Michael Koper has obviously mysql2 installed but I posted this in case someone has this issue as well .. (took me some time to figure out).

If you dislike this answer please comment and I will delete it.

P.S: German umlauts (ä,ö and ü) screwed it out with mysql

Failed to load ApplicationContext from Unit Test: FileNotFound

I faced the same error and realized that pom.xml had java 1.7 and STS compiler pointed to Java 1.8. Upon changing compiler to 1.7 and rebuild fixed the issue.

PS: This answer is not related to actual question posted but applies to similar error for app Context not loading

Get MD5 hash of big files in Python

Break the file into 8192-byte chunks (or some other multiple of 128 bytes) and feed them to MD5 consecutively using update().

This takes advantage of the fact that MD5 has 128-byte digest blocks (8192 is 128×64). Since you're not reading the entire file into memory, this won't use much more than 8192 bytes of memory.

In Python 3.8+ you can do

import hashlib
with open("your_filename.txt", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes