Programs & Examples On #Distributed objects

Distributed objects architecture enables objects in different threads or tasks, perhaps on different machines, to transparently send messages to each other

Editing dictionary values in a foreach loop

You can't modify the keys nor the values directly in a ForEach, but you can modify their members. E.g., this should work:

public class State {
    public int Value;
}

...

Dictionary<string, State> colStates = new Dictionary<string,State>();

int OtherCount = 0;
foreach(string key in colStates.Keys)
{
    double  Percent = colStates[key].Value / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key].Value;
        colStates[key].Value = 0;
    }
}

colStates.Add("Other", new State { Value =  OtherCount } );

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

What is dtype('O'), in pandas?

It means "a python object", i.e. not one of the builtin scalar types supported by numpy.

np.array([object()]).dtype
=> dtype('O')

Python 3.1.1 string to hex

In Python 3.5+, encode the string to bytes and use the hex() method, returning a string.

s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'

Optionally convert the string back to bytes:

b = bytes(s, "utf-8")
b
# b'68656c6c6f'

How to call javascript from a href?

The proper way to invoke javascript code when clicking a link would be to add an onclick handler:

<a href="#" onclick="myFunction()">LinkText</a>

Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded.

How to call a function after delay in Kotlin?

If you are in a fragment with viewModel scope you can use Kotlin coroutines:

    myViewModel.viewModelScope.launch {
        delay(2000)
        // DoSomething()
    }

Is there a way to make mv create the directory to be moved to if it doesn't exist?

It sounds like the answer is no :). I don't really want to create an alias or func just to do this, often because it's one-off and I'm already in the middle of typing the mv command, but I found something that works well for that:

mv *.sh  shell_files/also_with_subdir/ || mkdir -p $_

If mv fails (dir does not exist), it will make the directory (which is the last argument to the previous command, so $_ has it). So just run this command, then up to re-run it, and this time mv should succeed.

CSS Circular Cropping of Rectangle Image

Johnny's solution is good. I found that adding min-width:100%, really helps images fill the entire circle. You could do this with a combination of JavaScript to get optimal results or use ImageMagick - http://www.imagemagick.org/script/index.php if you're really serious about getting it right.

_x000D_
_x000D_
.image-cropper {_x000D_
_x000D_
  width: 35px;_x000D_
_x000D_
  height: 35px;_x000D_
_x000D_
  position: relative;_x000D_
_x000D_
  overflow: hidden;_x000D_
_x000D_
  border-radius: 50%;_x000D_
_x000D_
}_x000D_
_x000D_
.image-cropper__image {_x000D_
_x000D_
  display: inline;_x000D_
_x000D_
  margin: 0 auto;_x000D_
_x000D_
  height: 100%;_x000D_
_x000D_
  min-width: 100%;_x000D_
_x000D_
}
_x000D_
<div class="image-cropper">_x000D_
  <img src="#" class="image-cropper__image">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get last inserted id?

After inserting any row you can get last inserted id by below line of query.

INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId); SELECT @@IDENTITY

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

Centering a Twitter Bootstrap button

Bootstrap has it's own centering class named text-center.

<div class="span7 text-center"></div>

Python - abs vs fabs

math.fabs() always returns float, while abs() may return integer.

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

As you said, there are many duplicate questions on the same topic. Any how explaining your situation.

The problem might be solved by adding a timeout to call your index.html

ie you need to add super.setIntegerProperty("loadUrlTimeoutValue", 70000); in your activity.java file ( inside src/com/yourProj/--/youractivity.java) above this line: super.loadUrl("file:///android_asset/www/index.html");

Explanation:

This can be happened due to the following reasons

The core reason: the problem is likely due to the speed of the emulator so the network is too slow complete the communication in a timely fashion.

This can be due to:

  1. Your code/data/image is of too much of size ( I guess in your case you are using some images ,as you said you made some UI modifications, may be the size of images are high)
  2. Your script may have a infinite or long loop, so that it takes too much of time to load.
  3. You will be using too much of scripts (jQuery, iscroll, etc etc.. more number of plugins or scripts )

Declaring abstract method in TypeScript

I believe that using a combination of interfaces and base classes could work for you. It will enforce behavioral requirements at compile time (rq_ post "below" refers to a post above, which is not this one).

The interface sets the behavioral API that isn't met by the base class. You will not be able to set base class methods to call on methods defined in the interface (because you will not be able to implement that interface in the base class without having to define those behaviors). Maybe someone can come up with a safe trick to allow calling of the interface methods in the parent.

You have to remember to extend and implement in the class you will instantiate. It satisfies concerns about defining runtime-fail code. You also won't even be able to call the methods that would puke if you haven't implemented the interface (such as if you try to instantiate the Animal class). I tried having the interface extend the BaseAnimal below, but it hid the constructor and the 'name' field of BaseAnimal from Snake. If I had been able to do that, the use of a module and exports could have prevented accidental direct instantiation of the BaseAnimal class.

Paste this in here to see if it works for you: http://www.typescriptlang.org/Playground/

// The behavioral interface also needs to extend base for substitutability
interface AbstractAnimal extends BaseAnimal {
    // encapsulates animal behaviors that must be implemented
    makeSound(input : string): string;
}

class BaseAnimal {
    constructor(public name) { }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

// If concrete class doesn't extend both, it cannot use super methods.
class Snake extends BaseAnimal implements AbstractAnimal {
    constructor(name) { super(name); }
    makeSound(input : string): string {
        var utterance = "sssss"+input;
        alert(utterance);
        return utterance;
    }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

var longMover = new Snake("windy man");

longMover.makeSound("...am I nothing?");
longMover.move();

var fulture = new BaseAnimal("bob fossil");
// compile error on makeSound() because it is not defined.
// fulture.makeSound("you know, like a...")
fulture.move(1);

I came across FristvanCampen's answer as linked below. He says abstract classes are an anti-pattern, and suggests that one instantiate base 'abstract' classes using an injected instance of an implementing class. This is fair, but there are counter arguments made. Read for yourself: https://typescript.codeplex.com/discussions/449920

Part 2: I had another case where I wanted an abstract class, but I was prevented from using my solution above, because the defined methods in the "abstract class" needed to refer to the methods defined in the matching interface. So, I tool FristvanCampen's advice, sort of. I have the incomplete "abstract" class, with method implementations. I have the interface with the unimplemented methods; this interface extends the "abstract" class. I then have a class that extends the first and implements the second (it must extend both because the super constructor is inaccessible otherwise). See the (non-runnable) sample below:

export class OntologyConceptFilter extends FilterWidget.FilterWidget<ConceptGraph.Node, ConceptGraph.Link> implements FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link> {

    subMenuTitle = "Ontologies Rendered"; // overload or overshadow?

    constructor(
        public conceptGraph: ConceptGraph.ConceptGraph,
        graphView: PathToRoot.ConceptPathsToRoot,
        implementation: FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link>
        ){
        super(graphView);
        this.implementation = this;
    }
}

and

export class FilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> {

    public implementation: IFilterWidget<N, L>

    filterContainer: JQuery;

    public subMenuTitle : string; // Given value in children

    constructor(
        public graphView: GraphView.GraphView<N, L>
        ){

    }

    doStuff(node: N){
        this.implementation.generateStuff(thing);
    }

}

export interface IFilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> extends FilterWidget<N, L> {

    generateStuff(node: N): string;

}

How to add google-services.json in Android?

For using Google SignIn in Android app, you need

google-services.json

which you can generate using the instruction mentioned here

What is the simplest SQL Query to find the second largest value?

select min(sal) from emp where sal in 
    (select TOP 2 (sal) from emp order by sal desc)

Note

sal is col name
emp is table name

How do I change a tab background color when using TabLayout?

You can change the background color of the tab by this attribute

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/CategoryTab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
'android:background="@color/primary_color"/>'

How can I merge two MySQL tables?

If you need to do it manually, one time:

First, merge in a temporary table, with something like:

create table MERGED as select * from table 1 UNION select * from table 2

Then, identify the primary key constraints with something like

SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1

Where PK is the primary key field...

Solve the duplicates.

Rename the table.

[edited - removed brackets in the UNION query, which was causing the error in the comment below]

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.

Timing:

|------------|----------------|-------------------|
|            | shape (10000)  |  shape (1,10000)  |
|------------|----------------|-------------------|
| np.concat  |    0.18280     |      0.17960      |
|------------|----------------|-------------------|
|  np.stack  |    0.21501     |      0.16465      |
|------------|----------------|-------------------|
| np.vstack  |    0.21501     |      0.17181      |
|------------|----------------|-------------------|
|  np.array  |    0.21656     |      0.16833      |
|------------|----------------|-------------------|

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.

Code:

from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)
    l.append(new_np)



start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

OR operator in switch-case?

dude do like this

    case R.id.someValue :
    case R.id.someOtherValue :
       //do stuff

This is same as using OR operator between two values Because of this case operator isn't there in switch case

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

Make sure that there is no project Deploy in server. If so ,please right click on server ,select add and remove ,Then remove all project. After this you can double click on server and the option will be enabled for you.

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

It comes from +[UIWindow _synchronizeDrawingAcrossProcessesOverPort:withPreCommitHandler:] via os_log API. It doesn't depend from another components/frameworks that you are using(only from UIKit) - it reproduces in clean single view application project on changing interface orientation.

This method consists from 2 parts:

  1. adding passed precommit handler to list of handlers;
  2. do some work, that depends on current finite state machine state.

When second part fails (looks like prohibited transition), it prints message above to error log. However, I think that this problem is not fatal: there are 2 additional assert cases in this method, that will lead to crash in debug.

Seems that radar is the best we can do.

how to resolve DTS_E_OLEDBERROR. in ssis

I faced the similar issue.

Deselect the check box ("In wizard deselect the checkbox stating "First row has columns names") and before running the wizard make sure you have opened your excel sheet.

Then run the wizard by deselecting the checkbox.

This resolved my issue.

Convert HashBytes to VarChar

Use master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0) instead of master.dbo.fn_varbintohexstr and then substringing the result.

In fact fn_varbintohexstr calls fn_varbintohexsubstring internally. The first argument of fn_varbintohexsubstring tells it to add 0xF as the prefix or not. fn_varbintohexstr calls fn_varbintohexsubstring with 1 as the first argument internaly.

Because you don't need 0xF, call fn_varbintohexsubstring directly.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

Used a modified version of Jason's answer:

public string ProcessMyDataItem(object myValue)
{
  if (myValue.ToString().Length < 1)
  {
     return "0 value";
  }

  return myValue.ToString();
}

jQuery CSS Opacity

Try with this :

jQuery('#main').css({ opacity: 0.6 });

R barplot Y-axis scale too short

Simplest solution seems to be specifying the ylim range. Here is some code to do this automatically (left default, right - adjusted):

# default y-axis
barplot(dat, beside=TRUE)

# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))

img

The trick is to use pretty() which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.

In the example 0 was also added pretty(c(0, dat)) which makes sure that axis starts from 0.

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

How to get the date from jQuery UI datepicker

You can retrieve the date by using the getDate function:

$("#datepicker").datepicker( 'getDate' );

The value is returned as a JavaScript Date object.

If you want to use this value when the user selects a date, you can use the onSelect event:

$("#datepicker").datepicker({
   onSelect: function(dateText, inst) { 
      var dateAsString = dateText; //the first parameter of this function
      var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
   }
});

The first parameter is in this case the selected Date as String. Use parseDate to convert it to a JS Date Object.

See http://docs.jquery.com/UI/Datepicker for the full jQuery UI DatePicker reference.

Event for Handling the Focus of the EditText

  1. Declare object of EditText on top of class:

     EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                         Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    

It works fine.

What are the undocumented features and limitations of the Windows FINDSTR command?

Answer continued from part 1 above - I've run into the 30,000 character answer limit :-(

Limited Regular Expressions (regex) Support
FINDSTR support for regular expressions is extremely limited. If it is not in the HELP documentation, it is not supported.

Beyond that, the regex expressions that are supported are implemented in a completely non-standard manner, such that results can be different then would be expected coming from something like grep or perl.

Regex Line Position anchors ^ and $
^ matches beginning of input stream as well as any position immediately following a <LF>. Since FINDSTR also breaks lines after <LF>, a simple regex of "^" will always match all lines within a file, even a binary file.

$ matches any position immediately preceding a <CR>. This means that a regex search string containing $ will never match any lines within a Unix style text file, nor will it match the last line of a Windows text file if it is missing the EOL marker of <CR><LF>.

Note - As previously discussed, piped and redirected input to FINDSTR may have <CR><LF> appended that is not in the source. Obviously this can impact a regex search that uses $.

Any search string with characters before ^ or after $ will always fail to find a match.

Positional Options /B /E /X
The positional options work the same as ^ and $, except they also work for literal search strings.

/B functions the same as ^ at the start of a regex search string.

/E functions the same as $ at the end of a regex search string.

/X functions the same as having both ^ at the beginning and $ at the end of a regex search string.

Regex word boundary
\< must be the very first term in the regex. The regex will not match anything if any other characters precede it. \< corresponds to either the very beginning of the input, the beginning of a line (the position immediately following a <LF>), or the position immediately following any "non-word" character. The next character need not be a "word" character.

\> must be the very last term in the regex. The regex will not match anything if any other characters follow it. \> corresponds to either the end of input, the position immediately prior to a <CR>, or the position immediately preceding any "non-word" character. The preceding character need not be a "word" character.

Here is a complete list of "non-word" characters, represented as the decimal byte code. Note - this list was compiled on a U.S machine. I do not know what impact other languages may have on this list.

001   028   063   179   204   230
002   029   064   180   205   231
003   030   091   181   206   232
004   031   092   182   207   233
005   032   093   183   208   234
006   033   094   184   209   235
007   034   096   185   210   236
008   035   123   186   211   237
009   036   124   187   212   238
011   037   125   188   213   239
012   038   126   189   214   240
014   039   127   190   215   241
015   040   155   191   216   242
016   041   156   192   217   243
017   042   157   193   218   244
018   043   158   194   219   245
019   044   168   195   220   246
020   045   169   196   221   247
021   046   170   197   222   248
022   047   173   198   223   249
023   058   174   199   224   250
024   059   175   200   226   251
025   060   176   201   227   254
026   061   177   202   228   255
027   062   178   203   229

Regex character class ranges [x-y]
Character class ranges do not work as expected. See this question: Why does findstr not handle case properly (in some circumstances)?, along with this answer: https://stackoverflow.com/a/8767815/1012053.

The problem is FINDSTR does not collate the characters by their byte code value (commonly thought of as the ASCII code, but ASCII is only defined from 0x00 - 0x7F). Most regex implementations would treat [A-Z] as all upper case English capital letters. But FINDSTR uses a collation sequence that roughly corresponds to how SORT works. So [A-Z] includes the complete English alphabet, both upper and lower case (except for "a"), as well as non-English alpha characters with diacriticals.

Below is a complete list of all characters supported by FINDSTR, sorted in the collation sequence used by FINDSTR to establish regex character class ranges. The characters are represented as their decimal byte code value. I believe the collation sequence makes the most sense if the characters are viewed using code page 437. Note - this list was compiled on a U.S machine. I do not know what impact other languages may have on this list.

001
002
003
004
005
006
007
008
014
015
016
017
018           
019
020
021
022
023
024
025
026
027
028
029
030
031
127
039
045
032
255
009
010
011
012
013
033
034
035
036
037
038
040
041
042
044
046
047
058
059
063
064
091
092
093
094
095
096
123
124
125
126
173
168
155
156
157
158
043
249
060
061
062
241
174
175
246
251
239
247
240
243
242
169
244
245
254
196
205
179
186
218
213
214
201
191
184
183
187
192
212
211
200
217
190
189
188
195
198
199
204
180
181
182
185
194
209
210
203
193
207
208
202
197
216
215
206
223
220
221
222
219
176
177
178
170
248
230
250
048
172
171
049
050
253
051
052
053
054
055
056
057
236
097
065
166
160
133
131
132
142
134
143
145
146
098
066
099
067
135
128
100
068
101
069
130
144
138
136
137
102
070
159
103
071
104
072
105
073
161
141
140
139
106
074
107
075
108
076
109
077
110
252
078
164
165
111
079
167
162
149
147
148
153
112
080
113
081
114
082
115
083
225
116
084
117
085
163
151
150
129
154
118
086
119
087
120
088
121
089
152
122
090
224
226
235
238
233
227
229
228
231
237
232
234

Regex character class term limit and BUG
Not only is FINDSTR limited to a maximum of 15 character class terms within a regex, it fails to properly handle an attempt to exceed the limit. Using 16 or more character class terms results in an interactive Windows pop up stating "Find String (QGREP) Utility has encountered a problem and needs to close. We are sorry for the inconvenience." The message text varies slightly depending on the Windows version. Here is one example of a FINDSTR that will fail:

echo 01234567890123456|findstr [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]

This bug was reported by DosTips user Judago here. It has been confirmed on XP, Vista, and Windows 7.

Regex searches fail (and may hang indefinitely) if they include byte code 0xFF (decimal 255)
Any regex search that includes byte code 0xFF (decimal 255) will fail. It fails if byte code 0xFF is included directly, or if it is implicitly included within a character class range. Remember that FINDSTR character class ranges do not collate characters based on the byte code value. Character <0xFF> appears relatively early in the collation sequence between the <space> and <tab> characters. So any character class range that includes both <space> and <tab> will fail.

The exact behavior changes slightly depending on the Windows version. Windows 7 hangs indefinitely if 0xFF is included. XP doesn't hang, but it always fails to find a match, and occasionally prints the following error message - "The process tried to write to a nonexistent pipe."

I no longer have access to a Vista machine, so I haven't been able to test on Vista.

Regex bug: . and [^anySet] can match End-Of-File
The regex . meta-character should only match any character other than <CR> or <LF>. There is a bug that allows it to match the End-Of-File if the last line in the file is not terminated by <CR> or <LF>. However, the . will not match an empty file.

For example, a file named "test.txt" containing a single line of x, without terminating <CR> or <LF>, will match the following:

findstr /r x......... test.txt

This bug has been confirmed on XP and Win7.

The same seems to be true for negative character sets. Something like [^abc] will match End-Of-File. Positive character sets like [abc] seem to work fine. I have only tested this on Win7.

How to determine the number of days in a month in SQL Server?

I upvoted Mehrdad, but this works as well. :)

CREATE function dbo.IsLeapYear
(
    @TestYear int
)
RETURNS bit
AS
BEGIN
    declare @Result bit
    set @Result = 
    cast(
        case when ((@TestYear % 4 = 0) and (@testYear % 100 != 0)) or (@TestYear % 400 = 0)
        then 1
        else 0
        end
    as bit )
    return @Result
END
GO

CREATE FUNCTION dbo.GetDaysInMonth
(
    @TestDT datetime
)
RETURNS INT
AS
BEGIN

    DECLARE @Result int 
    DECLARE @MonthNo int

    Set @MonthNo = datepart(m,@TestDT)

    Set @Result = 
    case @MonthNo
        when  1 then 31
        when  2 then 
            case 
                when dbo.IsLeapYear(datepart(yyyy,@TestDT)) = 0
                then 28
                else 29
            end
        when  3 then 31
        when  4 then 30
        when  5 then 31
        when  6 then 30
        when  7 then 31
        when  8 then 31
        when  9 then 30 
        when 10 then 31
        when 11 then 30 
        when 12 then 31
    end

    RETURN @Result
END
GO

To Test

declare @testDT datetime;

set @testDT = '2404-feb-15';

select dbo.GetDaysInMonth(@testDT)

How can I convert a zero-terminated byte array to string?

Though not extremely performant, the only readable solution is:

  // Split by separator and pick the first one.
  // This has all the characters till null, excluding null itself.
  retByteArray := bytes.Split(byteArray[:], []byte{0}) [0]

  // OR

  // If you want a true C-like string, including the null character
  retByteArray := bytes.SplitAfter(byteArray[:], []byte{0}) [0]

A full example to have a C-style byte array:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var byteArray = [6]byte{97,98,0,100,0,99}

    cStyleString := bytes.SplitAfter(byteArray[:], []byte{0}) [0]
    fmt.Println(cStyleString)
}

A full example to have a Go style string excluding the nulls:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var byteArray = [6]byte{97, 98, 0, 100, 0, 99}

    goStyleString := string(bytes.Split(byteArray[:], []byte{0}) [0])
    fmt.Println(goStyleString)
}

This allocates a slice of slice of bytes. So keep an eye on performance if it is used heavily or repeatedly.

How to add label in chart.js for pie chart

For those using newer versions Chart.js, you can set a label by setting the callback for tooltips.callbacks.label in options.

Example of this would be:

var chartOptions = {
    tooltips: {
        callbacks: {
            label: function (tooltipItem, data) {
                return 'label';
            }
        }
    }
}

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

What's the best strategy for unit-testing database-driven applications?

I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.

I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).

JavaScript is in array

Depending on the version of JavaScript you have available, you can use indexOf:

Returns the first index at which a given element can be found in the array, or -1 if it is not present.

Or some:

Tests whether some element in the array passes the test implemented by the provided function.

But, if you're doing this sort of existence check a lot you'd be better of using an Object to store your strings (or perhaps an object as well as the Array depending on what you're doing with your data).

How to search for an element in an stl list?

Besides using std::find (from algorithm), you can also use std::find_if (which is, IMO, better than std::find), or other find algorithm from this list


#include <list>
#include <algorithm>
#include <iostream>

int main()
{
    std::list<int> myList{ 5, 19, 34, 3, 33 };
    

    auto it = std::find_if( std::begin( myList ),
                            std::end( myList ),
                            [&]( const int v ){ return 0 == ( v % 17 ); } );
        
    if ( myList.end() == it )
    {
        std::cout << "item not found" << std::endl;
    }
    else
    {
        const int pos = std::distance( myList.begin(), it ) + 1;
        std::cout << "item divisible by 17 found at position " << pos << std::endl;
    }
}

Convert True/False value read from file to boolean

you can use distutils.util.strtobool

>>> from distutils.util import strtobool

>>> strtobool('True')
1
>>> strtobool('False')
0

True values are y, yes, t, true, on and 1; False values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

CSS: auto height on containing div, 100% height on background div inside containing div

Try excluding height from the style element.

i.e. neither give height:100% nor to any other value.

What does "where T : class, new()" mean?

That means that type T must be a class and have a constructor that does not take any arguments.

For example, you must be able to do this:

T t = new T();

while-else-loop

boolean entered = false, last;
while (( entered |= last = ( condition ) )) {
        // Do while
} if ( !entered ) {
        // Else
}

You'r welcome.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

data.matrix(SFI)

From ?data.matrix:

Description:

 Return the matrix obtained by converting all the variables in a
 data frame to numeric mode and then binding them together as the
 columns of a matrix.  Factors and ordered factors are replaced by
 their internal codes.

Rmi connection refused with localhost

It seems to work when I replace the

Runtime.getRuntime().exec("rmiregistry 2020");

by

LocateRegistry.createRegistry(2020);

anyone an idea why? What's the difference?

position: fixed doesn't work on iPad and iPhone

position: fixed does work on android/iphone for vertical scrolling. But you need to make sure your meta tags are fully set. e.g

<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">

Also if you're planning on having the same page work on android pre 4.0, you need to set the top position also, or a small margin will be added for some reason.

CodeIgniter activerecord, retrieve last insert id?

Last insert id means you can get inserted auto increment id by using this method in active record,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

You can refer this link you can find some more stuff.

Information from executing a query

Align DIV's to bottom or baseline

_x000D_
_x000D_
td {_x000D_
  height: 150px;_x000D_
  width: 150px;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
b {_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.child-2 {_x000D_
  vertical-align: bottom;_x000D_
}_x000D_
_x000D_
.child-3 {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<table border=1>_x000D_
  <tr>_x000D_
    <td class="child-1">_x000D_
      <b>child 1</b>_x000D_
    </td>_x000D_
    <td class="child-2">_x000D_
     <b>child 2</b>_x000D_
    </td>_x000D_
    <td class="child-3">_x000D_
      <b>child 3</b>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This is my solution

How to overload functions in javascript?

I tried to develop an elegant solution to this problem described here. And you can find the demo here. The usage looks like this:

var out = def({
    'int': function(a) {
        alert('Here is int '+a);
    },

    'float': function(a) {
        alert('Here is float '+a);
    },

    'string': function(a) {
        alert('Here is string '+a);
    },

    'int,string': function(a, b) {
        alert('Here is an int '+a+' and a string '+b);
    },
    'default': function(obj) {
        alert('Here is some other value '+ obj);
    }

});

out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);

The methods used to achieve this:

var def = function(functions, parent) {
 return function() {
    var types = [];
    var args = [];
    eachArg(arguments, function(i, elem) {
        args.push(elem);
        types.push(whatis(elem));
    });
    if(functions.hasOwnProperty(types.join())) {
        return functions[types.join()].apply(parent, args);
    } else {
        if (typeof functions === 'function')
            return functions.apply(parent, args);
        if (functions.hasOwnProperty('default'))
            return functions['default'].apply(parent, args);        
    }
  };
};

var eachArg = function(args, fn) {
 var i = 0;
 while (args.hasOwnProperty(i)) {
    if(fn !== undefined)
        fn(i, args[i]);
    i++;
 }
 return i-1;
};

var whatis = function(val) {

 if(val === undefined)
    return 'undefined';
 if(val === null)
    return 'null';

 var type = typeof val;

 if(type === 'object') {
    if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
        return 'array';
    if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
        return 'date';
    if(val.hasOwnProperty('toExponential'))
        type = 'number';
    if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
        return 'string';
 }

 if(type === 'number') {
    if(val.toString().indexOf('.') > 0)
        return 'float';
    else
        return 'int';
 }

 return type;
};

SQL ORDER BY date problem

It sounds to me like your column isn't a date column but a text column (varchar/nvarchar etc). You should store it in the database as a date, not a string.

If you have to store it as a string for some reason, store it in a sortable format e.g. yyyy/MM/dd.

As najmeddine shows, you could convert the column on every access, but I would try very hard not to do that. It will make the database do a lot more work - it won't be able to keep appropriate indexes etc. Whenever possible, store the data in a type appropriate to the data itself.

Exception thrown inside catch block - will it be caught again?

The Java Language Specification says in section 14.19.1:

If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

  • If the run-time type of V is assignable to the Parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. If that block completes normally, then the try statement completes normally; if that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

Reference: http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#24134

In other words, the first enclosing catch that can handle the exception does, and if an exception is thrown out of that catch, that's not in the scope of any other catch for the original try, so they will not try to handle it.

One related and confusing thing to know is that in a try-[catch]-finally structure, a finally block may throw an exception and if so, any exception thrown by the try or catch block is lost. That can be confusing the first time you see it.

How to remove all leading zeroes in a string

(string)((int)"00000234892839")

Reverse a comparator in Java 8

You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:

Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
        .thenComparingInt(SomeEntity::getProperty2)
        .thenComparing(SomeEntity::getProperty3, reverseOrder());

How to block users from closing a window in Javascript?

What will you do when a user hits ALT + F4 or closes it from Task Manager

Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."

Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)

While loop in batch

It was very useful for me i have used in the following way to add user in active directory:

:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q

@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "

cls

:while1

if %x% leq %lent% (

    dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
    echo User %Uname%%x% with DC %DcName% is created
    set /a "x = x + 1"
    goto :while1
)

endlocal

Node.js Mongoose.js string to ObjectId function

Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)

_x000D_
_x000D_
...._x000D_
exports.AddSomething = (req,res,next) =>{_x000D_
  const newSomething = new SomeEntity({_x000D_
 _id:new mongoose.Types.ObjectId(), //its very own ID_x000D_
  somethingName:req.body.somethingName,_x000D_
  theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID_x000D_
})_x000D_
}_x000D_
...
_x000D_
_x000D_
_x000D_

Hope it Helps

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

how to count the total number of lines in a text file using python

For the people saying to use with open ("filename.txt","r") as f you can do anyname = open("filename.txt","r")

def main():

    file = open("infile.txt",'r')
    count = 0
    for line in file:
            count+=1

    print (count)

main ()

What do 'real', 'user' and 'sys' mean in the output of time(1)?

I want to mention some other scenario when the real-time is much much bigger than user + sys. I've created a simple server which respondes after a long time

real 4.784
user 0.01s
sys  0.01s

the issue is that in this scenario the process waits for the response which is not on the user site nor in the system.

Something similar happens when you run the find command. In that case, the time is spent mostly on requesting and getting a response from SSD.

CSS two div width 50% in one line with line break in file

Wrap them around a div with the following CSS

.div_wrapper{
    white-space: nowrap;
}

Center Triangle at Bottom of Div

I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.

How to convert a Collection to List?

List list = new ArrayList(coll);
Collections.sort(list);

As Erel Segal Halevi says below, if coll is already a list, you can skip step one. But that would depend on the internals of TreeBidiMap.

List list;
if (coll instanceof List)
  list = (List)coll;
else
  list = new ArrayList(coll);

Twitter Bootstrap modal on mobile devices

Gil's answer holds promise (the library he linked to) --- but for the time being, it still doesn't work when scrolled down on the mobile device.

I solved the issue for myself using just a snippet of CSS at the end of my CSS files:

@media (max-width: 767px) {
  #content .modal.fade.in {
    top: 5%;
  }
}

The #content selector is simply an id that wraps my html so I can override Bootstrap's specificity (set to your own id wrapping your modal html).

The downside: It's not centered vertically on the mobile devices.

The upside: It's visible, and on smaller devices, a reasonably sized modal will take up much of the screen, so the "non-centering" won't be as apparent.

Why it works:

When you're at low screen sizes with Bootstrap's responsive CSS, for devices with smaller screens, it sets .modal.fade.in's 'top' to 'auto'. For some reason the mobile webkit browsers seem to have a hard time with figuring out the vertical placement with the "auto" assignment. So just switch it back to a fixed value and it works great.

Since the modal is already set to postition: absolute, the value is relative to the viewport's height, not the document height, so it works no matter how long the page is or where you're scrolled to.

DECODE( ) function in SQL Server

If I understand the question correctly, you want the equivalent of decode but in T-SQL

Select YourFieldAliasName =
CASE PC_SL_LDGR_CODE
    WHEN '02' THEN 'DR'
    ELSE 'CR'
END

How to position the Button exactly in CSS

It seems some what center of the screen. So I would like to do like this

body { 
     background: url('http://oi44.tinypic.com/33tjudk.jpg') no-repeat center center fixed;    
     background-size:cover; 
     text-align: 0 auto; // Make the play button horizontal center
}

#play_button {
    position:absolute;  // absolutely positioned
    transition: .5s ease;
    top: 50%;  // Makes vertical center
} 

Python dictionary replace values

You cannot select on specific values (or types of values). You'd either make a reverse index (map numbers back to (lists of) keys) or you have to loop through all values every time.

If you are processing numbers in arbitrary order anyway, you may as well loop through all items:

for key, value in inputdict.items():
    # do something with value
    inputdict[key] = newvalue

otherwise I'd go with the reverse index:

from collections import defaultdict

reverse = defaultdict(list)
for key, value in inputdict.items():
    reverse[value].append(key)

Now you can look up keys by value:

for key in reverse[value]:
    inputdict[key] = newvalue

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Get the client's IP address in socket.io

use socket.request.connection.remoteAddress

Elastic Search: how to see the indexed data

Kibana is also a good solution. It is a data visualization platform for Elastic.If installed it runs by default on port 5601.

Out of the many things it provides. It has "Dev Tools" where we can do your debugging.

For example you can check your available indexes here using the command

GET /_cat/indices

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

IMO it's the different way to resolve a name from the OS and PHP.

Try:

echo gethostbyname("host.name.tld");

and

var_export (dns_get_record ( "host.name.tld") );

or

$dns=array("8.8.8.8","8.8.4.4");
var_export (dns_get_record ( "host.name.tld" ,  DNS_ALL , $dns ));

You should found some DNS/resolver error.

PHPExcel set border and format for all sheets in spreadsheet

To answer your extra question:

You can set which rows should be repeated on every page using:

$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);

Now, row 1, 2, 3, 4 and 5 will be repeated.

How do I set a value in CKEditor with Javascript?

Take care to strip out newlines from any string you pass to setData(). Otherwise an exception gets thrown.

Also note that even if you do that, then subsequently get that data again using getData(), CKEditor puts the line breaks back in.

File to import not found or unreadable: compass

In short, if you've installed the gem the run:

compass compile

in your rails root dir

Create hyperlink to another sheet

The "!" sign is the key element. If you have a cell object (like "mycell" in following code sample) and link a cell to this object you must pay attention to ! element.

You must do something like this:

.Cells(i, 2).Hyperlinks.Add Anchor:=.Range(Cells(i, 2).Address), Address:="", _
     SubAddress:= "'" & ws.Name & "'" & _
     "!" & mycell.Address

Does height and width not apply to span?

Span is an inline element. It has no width or height.

You could turn it into a block-level element, then it will accept your dimension directives.

span.product__specfield_8_arrow
{
    display: inline-block; /* or block */
}

How to force Sequential Javascript Execution?

I had the same problem, this is my solution:

_x000D_
_x000D_
var functionsToCall = new Array();_x000D_
_x000D_
function f1() {_x000D_
    $.ajax({_x000D_
        type:"POST",_x000D_
        url: "/some/url",_x000D_
        success: function(data) {_x000D_
            doSomethingWith(data);_x000D_
            //When done, call the next function.._x000D_
            callAFunction("parameter");_x000D_
        }_x000D_
    });_x000D_
}_x000D_
_x000D_
function f2() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter2");_x000D_
}_x000D_
function f3() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter3");_x000D_
}_x000D_
function f4() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter4");_x000D_
}_x000D_
function f5() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter5");_x000D_
}_x000D_
function f6() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter6");_x000D_
}_x000D_
function f7() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter7");_x000D_
}_x000D_
function f8() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter8");_x000D_
}_x000D_
function f9() {_x000D_
    /*...*/_x000D_
    callAFunction("parameter9");_x000D_
}_x000D_
    _x000D_
function callAllFunctionsSy(params) {_x000D_
 functionsToCall.push(f1);_x000D_
 functionsToCall.push(f2);_x000D_
 functionsToCall.push(f3);_x000D_
 functionsToCall.push(f4);_x000D_
 functionsToCall.push(f5);_x000D_
 functionsToCall.push(f6);_x000D_
 functionsToCall.push(f7);_x000D_
 functionsToCall.push(f8);_x000D_
 functionsToCall.push(f9);_x000D_
 functionsToCall.reverse();_x000D_
 callAFunction(params);_x000D_
}_x000D_
_x000D_
function callAFunction(params) {_x000D_
 if (functionsToCall.length > 0) {_x000D_
  var f=functionsToCall.pop();_x000D_
  f(params);_x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

How do I concatenate text in a query in sql server?

The only way would be to convert your text field into an nvarchar field.

Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a

Otherwise, I suggest doing the concatenation in your application.

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Make the console wait for a user input to close

I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a pipeline) there is no point printing a message or waiting. For that you could use Java's Console like this:

import java.io.Console;
// ...
public static void waitForEnter(String message, Object... args) {
    Console c = System.console();
    if (c != null) {
        // printf-like arguments
        if (message != null)
            c.format(message, args);
        c.format("\nPress ENTER to proceed.\n");
        c.readLine();
    }
}

What does "xmlns" in XML mean?

xmlns - xml namespace. It's just a method to avoid element name conflicts. For example:

<config xmlns:rnc="URI1" xmlns:bsc="URI2">
  <rnc:node>
      <rnc:rncId>5</rnc:rncId>
  </rnc:node>

  <bsc:node>
      <bsc:cId>5</bsc:cId>
  </bsc:node>
</config>

Two different node elements in one xml file. Without namespaces this file would not be valid.

How to start Fragment from an Activity

Firstly, you start Activities and Services with an intent, you start fragments with fragment transactions. Secondly, your transaction isnt doing anything. Change it to something like:

FragmentTransaction transaction = getFragmentManager();
    transaction.beginTransaction()
        .replace(R.layout.container, newFragment) //<---replace a view in your layout (id: container) with the newFragment 
        .commit();

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Laravel supports aliases on tables and columns with AS. Try

$users = DB::table('really_long_table_name AS t')
           ->select('t.id AS uid')
           ->get();

Let's see it in action with an awesome tinker tool

$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
//   0 => object(stdClass)(
//     'uid' => '1'
//   )
// )

SQL - Create view from multiple tables

Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:

CREATE VIEW V AS (

  SELECT i.country,i.year,p.pop,f.food,i.income FROM
    INCOME i
  LEFT JOIN 
    POP p 
  ON
    i.country=p.country
  LEFT JOIN
    Food f
  ON 
    i.country=f.country
  WHERE 
    i.year=p.year
  AND
    i.year=f.year
);

The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

(updated on 3-29-2019 to use the https instead of ssh, so you don't need to use ssh keys)

It seems like for BitBucket, you do have to create a repo online first. Using the instructions from Atlassian, simply create a new BitBucket repository, copy the repository url to the clipboard, and then add that repository as a new remote to your local repository (full steps below):

Get Repo URL

  1. in your BitBucket repo, choose "Clone" on the top-right
  2. choose "HTTPS" instead of "SSH" in the top-right of the dialog
  3. it should show your repo url in the form git clone <repository url>

Add Remote Using CLI

  1. cd /path/to/my/repo
  2. git remote add origin https://bitbucket.org/<username>/<reponame>.git
  3. git push -u origin --all

Add Remote Using SourceTree

  1. Repository>Add Remote...
  2. Paste the BitBucket repository url (https://bitbucket.org/<username>/<reponame>.git)

Old Method: Creating & Registering SSH Keys

(this method is if you use the ssh url instead of the https url, which looks like ssh://[email protected]/<username>/<reponame>.git. I recommend just using https)

BitBucket is great for private repos, but you'll need to set up an ssh key to authorize your computer to work with your BitBucket account. Luckily Sourcetree makes it relatively simple:

Creating a Key In SourceTree:

  1. In Tools>Options, make sure SSH Client: is set to PuTTY/Plink under the General tab
  2. Select Tools>Create or Import SSH Keys
  3. In the popup window, click Generate and move your mouse around to give randomness to the key generator
  4. You should get something like whats shown in the screenshot below. Copy the public key (highlighted in blue) to your clipboard

    putty

  5. Click Save private Key and Save public key to save your keys to wherever you choose (e.g. to <Home Dir>/putty/ssk-key.ppk and <Home Dir>/putty/ssh-key.pub respectively) before moving on to the next section

Registering The Key In BitBucket

  1. Log in to your BitBucket account, and on the top right, click your profile picture and click Settings
  2. Go to the SSH Keys tab on the left sidebar
  3. Click Add SSH Key, give it a name, and paste the public key you copied in step 4 of the previous section

That's it! You should now be able to push/pull to your BitBucket private repos. Your keys aren't just for Git either, many services use ssh keys to identify users, and the best part is you only need one. If you ever lose your keys (e.g. when changing computers), just follow the steps to create and register a new one.

Sidenote: Creating SSH Keys using CLI

Just follow this tutorial

How to get row index number in R?

If i understand your question, you just want to be able to access items in a data frame (or list) by row:

x = matrix( ceiling(9*runif(20)), nrow=5  )   
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x)      # create a small data frame

df[1,]                  # get the first row
df[3,]                  # get the third row
df[nrow(df),]           # get the last row

lf = as.list(df)        

lf[[1]]                 # get first row
lf[[3]]                 # get third row

etc.

Which font is used in Visual Studio Code Editor and how to change fonts?

In the default settings, VS Code uses the following fonts (14 pt) in descending order:

  • Monaco
  • Menlo
  • Consolas
  • "Droid Sans Mono"
  • "Inconsolata"
  • "Courier New"
  • monospace (fallback)

How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.

relevant areas

@Scope("prototype") bean scope not creating new bean

@Component

@Scope(value="prototype")

public class TennisCoach implements Coach {

// some code

}

IntelliJ does not show 'Class' when we right click and select 'New'

Another possible solution is that the project name is not acceptable. For example, creating a project with spaces in the name does not block the project creation but the proper sources are not marked and when those are marked manually, I still was unable to create classes. Recreating the project with hyphens (-) instead of spaces corrected the problem for me.

Close Current Tab

As of Chrome 46, a simple onclick=window.close() does the trick. This only closes the tab, and not the entire browser, if multiple tabs are opened.

What is __gxx_personality_v0 for?

It's part of the exception handling. The gcc EH mechanism allows to mix various EH models, and a personality routine is invoked to determine if an exception match, what finalization to invoke, etc. This specific personality routine is for C++ exception handling (as opposed to, say, gcj/Java exception handling).

How can I parse a YAML file from a Linux shell script?

Hard to say because it depends on what you want the parser to extract from your YAML document. For simple cases, you might be able to use grep, cut, awk etc. For more complex parsing you would need to use a full-blown parsing library such as Python's PyYAML or YAML::Perl.

How do I tell what type of value is in a Perl variable?

ref():

Perl provides the ref() function so that you can check the reference type before dereferencing a reference...

By using the ref() function you can protect program code that dereferences variables from producing errors when the wrong type of reference is used...

How to see PL/SQL Stored Function body in Oracle

If is a package then you can get the source for that with:

    select text from all_source where name = 'PADCAMPAIGN' 
    and type = 'PACKAGE BODY'
    order by line;

Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.

Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use

    select text from all_source where name = 'pAdCampaign' 
    and type = 'PACKAGE BODY'
    order by line;

How to convert an address into a Google Maps Link (NOT MAP)

I just found this and like to share..

  1. search your address at maps.google.com
  2. click on the gear icon at the bottom-right
  3. click "shared or embed map"
  4. click the short url checkbox and paste the result in href..

Find all matches in workbook using Excel VBA

Below code avoids creating infinite loop. Assume XYZ is the string which we are looking for in the workbook.

   Private Sub CommandButton1_Click()
   Dim Sh As Worksheet, myCounter
   Dim Loc As Range

   For Each Sh In ThisWorkbook.Worksheets
   With Sh.UsedRange
   Set Loc = .Cells.Find(What:="XYZ")

    If Not Loc Is Nothing Then

           MsgBox ("Value is found  in " & Sh.Name)
           myCounter = 1
            Set Loc = .FindNext(Loc)

    End If
End With
Next
If myCounter = 0 Then
MsgBox ("Value not present in this worrkbook")
End If

End Sub

How to initialize a vector of vectors on a struct?

Like this:

#include <vector>

// ...

std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));

(Pre-C++11 you need to leave whitespace between the angled brackets.)

pass array to method Java

Important Points

  • you have to use java.util package
  • array can be passed by reference

In the method calling statement

  • Don't use any object to pass an array
  • only the array's name is used, don't use datatype or array brackets []

Sample Program

import java.util.*;

class atg {
  void a() {
    int b[]={1,2,3,4,5,6,7};
    c(b);
  }

  void c(int b[]) {
    int e=b.length;
    for(int f=0;f<e;f++) {
      System.out.print(b[f]+" ");//Single Space
    }
  }

  public static void main(String args[]) {
    atg ob=new atg();
    ob.a();
  }
}

Output Sample Program

1 2 3 4 5 6 7

PHP error: Notice: Undefined index:

Are you putting the form processor in the same script as the form? If so, it is attempting to process before the post values are set (everything is executing).

Wrap all the processing code in a conditional that checks if the form has even been sent.

if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
//process form!
}else{
//show form, don't process yet!  You can break out of php here and render your form
}

Scripts execute from the top down when programming procedurally. You need to make sure the program knows to ignore the processing logic if the form has not been sent. Likewise, after processing, you should redirect to a success page with something like

header('Location:http://www.yourdomainhere.com/formsuccess.php');

I would not get into the habit of supressing notices or errors.

Please don't take offense if I suggest that if you are having these problems and you are attempting to build a shopping cart, that you instead utilize a mature ecommerce solution like Magento or OsCommerce. A shopping cart is an interface that requires a high degree of security and if you are struggling with these kind of POST issues I can guarantee you will be fraught with headaches later. There are many great stable releases, some as simple as mere object models, that are available for download.

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

How to access URL segment(s) in blade in Laravel 5?

An easy way to get the first or last segment, in case you are unsure of the path length.

$segments = request()->segments();
$last  = end($segments);
$first = reset($segments);

Cannot get OpenCV to compile because of undefined references?

For me, this type of error:

mingw-w64-x86_64/lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld: mingw-w64-x86_64/x86_64-w64-mingw32/lib/libTransform360.a(VideoFrameTransform.cpp.obj):VideoFrameTransform.cpp:(.text+0xc7c):
undefined reference to `cv::Mat::Mat(cv::Mat const&, cv::Rect_<int> const&)'

meant load order, I had to do -lTransform360 -lopencv_dnn345 -lopencv... just like that, that order. And putting them right next to each other helped too, don't put -lTransform360 all the way at the beginning...or you'll get, for some freaky reason:

undefined reference to `VideoFrameTransform_new'
undefined reference to `VideoFrameTransform_generateMapForPlane'

...

How can I put an icon inside a TextInput in React Native?

This is working for me in ReactNative 0.60.4

View

<View style={styles.SectionStyle}>
    <Image
        source={require('../assets/images/ico-email.png')} //Change your icon image here
        style={styles.ImageStyle}
    />

    <TextInput
        style={{ flex: 1 }}
        placeholder="Enter Your Name Here"
        underlineColorAndroid="transparent"
    />
</View>

Styles

SectionStyle: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderWidth: 0.5,
    borderColor: '#000',
    height: 40,
    borderRadius: 5,
    margin: 10,
},
ImageStyle: {
    padding: 10,
    margin: 5,
    height: 25,
    width: 25,
    resizeMode: 'stretch',
    alignItems: 'center',
}

Passing a variable from node.js to html

Other than those on the top, you can use JavaScript to fetch the details from the server. html file

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
      <div id="test">
      </div>
    <script type="text/javascript">
        let url="http://localhost:8001/test";
        fetch(url).then(response => response.json())
        .then( (result) => {
            console.log('success:', result)
            let div=document.getElementById('test');
            div.innerHTML=`title: ${result.title}<br/>message: ${result.message}`;
        })
        .catch(error => console.log('error:', error));
    </script>
  </body>
</html>

server.js

app.get('/test',(req,res)=>{
    //res.sendFile(__dirname +"/views/test.html",);
    res.json({title:"api",message:"root"});
})

app.get('/render',(req,res)=>{
    res.sendFile(__dirname +"/views/test.html");
})

The best answer i found on the stack-overflow on the said subject, it's not my answer. Found it somewhere for nearly same question...source source of answer

In Python, how do I read the exif data for an image?

I have found that using ._getexif doesn't work in higher python versions, moreover, it is a protected class and one should avoid using it if possible. After digging around the debugger this is what I found to be the best way to get the EXIF data for an image:

from PIL import Image

def get_exif(path):
    return Image.open(path).info['parsed_exif']

This returns a dictionary of all the EXIF data of an image.

Note: For Python3.x use Pillow instead of PIL

How do I get sed to read from standard input?

  1. Open the file using vi myfile.csv
  2. Press Escape
  3. Type :%s/replaceme/withthis/
  4. Type :wq and press Enter

Now you will have the new pattern in your file.

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

What is correct media query for IPad Pro?

This worked for me

/* Portrait */
@media only screen 
  and (min-device-width: 834px) 
  and (max-device-width: 834px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 2) {

}

/* Landscape */
@media only screen 
  and (min-width: 1112px) 
  and (max-width: 1112px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 2)
 {

}

How do I drop a foreign key constraint only if it exists in sql server?

I think this will helpful to you...

    DECLARE @ConstraintName nvarchar(200)
SELECT 
    @ConstraintName = KCU.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC 
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU
    ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG  
    AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA 
    AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE
    KCU.TABLE_NAME = 'TABLE_NAME' AND
    KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME'
IF @ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop  CONSTRAINT ' + @ConstraintName)

It will delete foreign Key Constraint based on specific table and column.

Run a shell script with an html button

As stated by Luke you need to use a server side language, like php. This is a really simple php example:

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("/path/to/name.sh");
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

Save this as myfilename.php and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...

How to center a window on the screen in Tkinter?

I use frame and expand option. Very simple. I want some buttons in the middle of screen. Resize window and button stay in the middle. This is my solution.

frame = Frame(parent_window)
Button(frame, text='button1', command=command_1).pack(fill=X)
Button(frame, text='button2', command=command_2).pack(fill=X)
Button(frame, text='button3', command=command_3).pack(fill=X)
frame.pack(anchor=CENTER, expand=1)

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Detecting mobile devices

Related answer: https://stackoverflow.com/a/13805337/1306809

There's no single approach that's truly foolproof. The best bet is to mix and match a variety of tricks as needed, to increase the chances of successfully detecting a wider range of handheld devices. See the link above for a few different options.

Insert into C# with SQLCommand

public class customer
{
    public void InsertCustomer(string name,int age,string address)
    {
        // create and open a connection object
        using(SqlConnection Con=DbConnection.GetDbConnection())
        {
            // 1. create a command object identifying the stored procedure
            SqlCommand cmd = new SqlCommand("spInsertCustomerData",Con);

            // 2. set the command object so it knows to execute a stored procedure
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter paramName = new SqlParameter();
            paramName.ParameterName = "@nvcname";
            paramName.Value = name;
            cmd.Parameters.Add(paramName);

            SqlParameter paramAge = new SqlParameter();
            paramAge.ParameterName = "@inage";
            paramAge.Value = age;
            cmd.Parameters.Add(paramAge);

            SqlParameter paramAddress = new SqlParameter();
            paramAddress.ParameterName = "@nvcaddress";
            paramAddress.Value = address;
            cmd.Parameters.Add(paramAddress);

            cmd.ExecuteNonQuery();
        }
    }
}

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

How do I get bit-by-bit data from an integer value in C?

As requested, I decided to extend my comment on forefinger's answer to a full-fledged answer. Although his answer is correct, it is needlessly complex. Furthermore all current answers use signed ints to represent the values. This is dangerous, as right-shifting of negative values is implementation-defined (i.e. not portable) and left-shifting can lead to undefined behavior (see this question).

By right-shifting the desired bit into the least significant bit position, masking can be done with 1. No need to compute a new mask value for each bit.

(n >> k) & 1

As a complete program, computing (and subsequently printing) an array of single bit values:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    unsigned
        input = 0b0111u,
        n_bits = 4u,
        *bits = (unsigned*)malloc(sizeof(unsigned) * n_bits),
        bit = 0;

    for(bit = 0; bit < n_bits; ++bit)
        bits[bit] = (input >> bit) & 1;

    for(bit = n_bits; bit--;)
        printf("%u", bits[bit]);
    printf("\n");

    free(bits);
}

Assuming that you want to calculate all bits as in this case, and not a specific one, the loop can be further changed to

for(bit = 0; bit < n_bits; ++bit, input >>= 1)
    bits[bit] = input & 1;

This modifies input in place and thereby allows the use of a constant width, single-bit shift, which may be more efficient on some architectures.

Pass by Reference / Value in C++

I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:

struct Object {
    int i;
};

void sample(Object* o) { // 1
    o->i++;
}

void sample(Object const& o) { // 2
    // nothing useful here :)
}

void sample(Object & o) { // 3
    o.i++;
}

void sample1(Object o) { // 4
    o.i++;
}

int main() {
    Object obj = { 10 };
    Object const obj_c = { 10 };

    sample(&obj); // calls 1
    sample(obj) // calls 3
    sample(obj_c); // calls 2
    sample1(obj); // calls 4
}

Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.

I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:

    sample(&obj);
       // yields a `Object*`. Passes a *pointer* to the object by value. 
       // The caller can change the pointer (the parameter), but that 
       // won't change the temporary pointer created on the call side (the argument). 

    sample(obj)
       // passes the object by *reference*. It denotes the object itself. The callee
       // has got a reference parameter.

    sample(obj_c);
       // also passes *by reference*. the reference parameter references the
       // same object like the argument expression. 

    sample1(obj);
       // pass by value. The parameter object denotes a different object than the 
       // one passed in.

I vote for the following definition:

An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.

That means that the following is pass by value:

void f1(Object const& o);
f1(Object()); // 1

void f2(int const& i);
f2(42); // 2

void f3(Object o);
f3(Object());     // 3
Object o1; f3(o1); // 4

void f4(Object *o);
Object o1; f4(&o1); // 5

1 is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2 is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3 is pass by value, because the parameter has not reference type. 4 is pass by value for the same reason. 5 is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):

void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1

void f2(Object const& op);
Object b; f2(b); // 2

struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference

Import CSV file with mixed data types

Depending on the format of your file, importdata might work.

You can store Strings in a cell array. Type "doc cell" for more information.

How do I remove an array item in TypeScript?

One more solution using Typescript:

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
        updated.push(el);
    }
}
this.oldArray = updated;

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

This particular NuGet package has a habit of losing its references in one of our projects. From time to time I will need to run the following command in the Package Manager Console to restore the references and everything is OK again

Update-Package Microsoft.AspNet.Webpages -reinstall

Why am I getting a NoClassDefFoundError in Java?

I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar. When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec. I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.

How to do an array of hashmaps?

You can't have an array of a generic type. Use List instead.

Remove directory which is not empty

I reached here while trying to get over with the gulp and I'm writing for further reaches.

When you want to delete files and folders using del, you should append /** for recursive deletion.

gulp.task('clean', function () {
    return del(['some/path/to/delete/**']);
});

How do you pull first 100 characters of a string in PHP

$small = substr($big, 0, 100);

For String Manipulation here is a page with a lot of function that might help you in your future work.

How to create cron job using PHP?

In the same way you are trying to run cron.php, you can run another PHP script. You will have to do so via the CLI interface though.

#!/usr/bin/env php
<?php
# This file would be say, '/usr/local/bin/run.php'
// code
echo "this was run from CRON";

Then, add an entry to the crontab:

* * * * * /usr/bin/php -f /usr/local/bin/run.php &> /dev/null

If the run.php script had executable permissions, it could be listed directly in the crontab, without the /usr/bin/php part as well. The 'env php' part, in the script, would find the appropriate program to actually run the PHP code. So, for the 'executable' version - add executable permission to the file:

chmod +x /usr/local/bin/run.php

and then, add the following entry into crontab:

* * * * * /usr/local/bin/run.php &> /dev/null

TypeScript error TS1005: ';' expected (II)

Just try to without changing anything npm install [email protected] X.X.X is your current version

Reset select value to default

You can make use of the defaultSelected property of an option element:

Contains the initial value of the selected HTML attribute, indicating whether the option is selected by default or not.

So, the DOM interface already keeps track which option was selected initially.

$("#reset").on("click", function () {
    $('#my_select option').prop('selected', function() {
        return this.defaultSelected;
    });
});

DEMO

This would even work for multi-select elements.

If you don't want to iterate over all options, but "break" after you found the originally selected one, you can use .each instead:

$('#my_select option').each(function () {
    if (this.defaultSelected) {
        this.selected = true;
        return false;
    }
});

Without jQuery:

var options = document.querySelectorAll('#my_select option');
for (var i = 0, l = options.length; i < l; i++) {
    options[i].selected = options[i].defaultSelected;
}

Calling a method inside another method in same class

The add method that takes a String and a Person is calling a different add method that takes a Position. The one that takes Position is inherited from the ArrayList class.

Since your class Staff extends ArrayList<Position>, it automatically has the add(Position) method. The new add(String, Person) method is one that was written particularly for the Staff class.

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I had the same issue (EF Core) while setting up xUnit tests. What 'fixed' it for me in testing was looping through the change tracker entities after setting up the seed data.

  • at the bottom of the SeedAppDbContext() method.

I set up a Test Mock Context:

/// <summary>
/// Get an In memory version of the app db context with some seeded data
/// </summary>
public static AppDbContext GetAppDbContext(string dbName)
{
    //set up the options to use for this dbcontext
    var options = new DbContextOptionsBuilder<AppDbContext>()
        .UseInMemoryDatabase(databaseName: dbName)
        //.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
        .Options;

    var dbContext = new AppDbContext(options);
    dbContext.SeedAppDbContext();
    return dbContext;
}

Extension method to add some seed data:

  • and detach entities in foreach loop at bottom of method.
    public static void SeedAppDbContext(this AppDbContext appDbContext)
    {
       // add companies
       var c1 = new Company() { Id = 1, CompanyName = "Fake Company One", ContactPersonName = "Contact one", eMail = "[email protected]", Phone = "0123456789", AdminUserId = "" };
       c1.Address = new Address() { Id = 1, AddressL1 = "Field Farm", AddressL2 = "Some Lane", City = "some city", PostalCode = "AB12 3CD" };
       appDbContext.CompanyRecords.Add(c1);
                        
       var nc1 = new Company() { Id = 2, CompanyName = "Test Company 2", ContactPersonName = "Contact two", eMail = "[email protected]", Phone = "0123456789", Address = new Address() { }, AdminUserId = "" };
       nc1.Address = new Address() { Id = 2, AddressL1 = "The Barn", AddressL2 = "Some Lane", City = "some city", PostalCode = "AB12 3CD" };
       appDbContext.CompanyRecords.Add(nc1);

       //....and so on....
            
       //last call to commit everything to the memory db
       appDbContext.SaveChanges();

       //and then to detach everything 
       foreach (var entity in appDbContext.ChangeTracker.Entries())
       {
           entity.State = EntityState.Detached;
       }
    }

The controller put method

The .ConvertTo<>() Method is an extension method from ServiceStack

 [HttpPut]
public async Task<IActionResult> PutUpdateCompany(CompanyFullDto company)
{
    if (0 == company.Id)
        return BadRequest();
    try
    {
        Company editEntity = company.ConvertTo<Company>();
        
        //Prior to detaching an error thrown on line below (another instance with id)
        var trackedEntity = _appDbContext.CompanyRecords.Update(editEntity);
        

        await _appDbContext.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException dbError)
    {
        if (!CompanyExists(company.Id))
            return NotFound();
        else
            return BadRequest(dbError);
    }
    catch (Exception Error)
    {
        return BadRequest(Error);
    }
    return Ok();
}

and the test:

    [Fact]
    public async Task PassWhenEditingCompany()
    {
        var _appDbContext = AppDbContextMocker.GetAppDbContext(nameof(CompaniesController));
        var _controller = new CompaniesController(null, _appDbContext);

        //Arrange
        const string companyName = "Fake Company One";
        const string contactPerson = "Contact one";

        const string newCompanyName = "New Fake Company One";
        const string newContactPersonName = "New Contact Person";

        //Act
        var getResult = _controller.GetCompanyById(1);
        var getEntity = (getResult.Result.Result as OkObjectResult).Value;
        var entityDto = getEntity as CompanyFullDto;


        //Assert
        Assert.Equal(companyName, entityDto.CompanyName);
        Assert.Equal(contactPerson, entityDto.ContactPersonName);
        Assert.Equal(1, entityDto.Id);

        //Arrange
        Company entity = entityDto.ConvertTo<Company>();
        entity.CompanyName = newCompanyName;
        entity.ContactPersonName = newContactPersonName;
        CompanyFullDto entityDtoUpd = entity.ConvertTo<CompanyFullDto>();

        //Act
        var result = await _controller.PutUpdateCompany(entityDtoUpd) as StatusCodeResult;

        //Assert           
        Assert.True(result.StatusCode == 200);

        //Act
        getResult = _controller.GetCompanyById(1);
        getEntity = (getResult.Result.Result as OkObjectResult).Value;
        
        entityDto = getEntity as CompanyFullDto;
        
        //Assert
        Assert.Equal(1, entityDto.Id); // didn't add a new record
        Assert.Equal(newCompanyName, entityDto.CompanyName); //updated the name
        Assert.Equal(newContactPersonName, entityDto.ContactPersonName); //updated the contact

//make sure to dispose of the _appDbContext otherwise running the full test will fail.
_appDbContext.Dispose();
    }

Implements vs extends: When to use? What's the difference?

  • A extends B:

    A and B are both classes or both interfaces

  • A implements B

    A is a class and B is an interface

  • The remaining case where A is an interface and B is a class is not legal in Java.

substring index range

Like you I didn't find it came naturally. I normally still have to remind myself that

  • the length of the returned string is

    lastIndex - firstIndex

  • that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception

so

"University".substring(6, 10)

returns the 4-character string "sity" even though there is no character at position 10.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

How to change the remote repository for a git submodule?

You should just be able to edit the .gitmodules file to update the URL and then run git submodule sync --recursive to reflect that change to the superproject and your working copy.

Then you need to go to the .git/modules/path_to_submodule dir and change its config file to update git path.

If repo history is different then you need to checkout new branch manually:

git submodule sync --recursive
cd <submodule_dir> 

git fetch
git checkout origin/master
git branch master -f
git checkout master

span with onclick event inside a tag

<a href="http://the.url.com/page.html">
    <span onclick="hide(); return false">Hide me</span>
</a>

This is the easiest solution.

Understanding PIVOT function in T-SQL

A pivot is used to convert one of the columns in your data set from rows into columns (this is typically referred to as the spreading column). In the example you have given, this means converting the PhaseID rows into a set of columns, where there is one column for each distinct value that PhaseID can contain - 1, 5 and 6 in this case.

These pivoted values are grouped via the ElementID column in the example that you have given.

Typically you also then need to provide some form of aggregation that gives you the values referenced by the intersection of the spreading value (PhaseID) and the grouping value (ElementID). Although in the example given the aggregation that will be used is unclear, but involves the Effort column.

Once this pivoting is done, the grouping and spreading columns are used to find an aggregation value. Or in your case, ElementID and PhaseIDX lookup Effort.

Using the grouping, spreading, aggregation terminology you will typically see example syntax for a pivot as:

WITH PivotData AS
(
    SELECT <grouping column>
        , <spreading column>
        , <aggregation column>
    FROM <source table>
)
SELECT <grouping column>, <distinct spreading values>
FROM PivotData
    PIVOT (<aggregation function>(<aggregation column>)
        FOR <spreading column> IN <distinct spreading values>));

This gives a graphical explanation of how the grouping, spreading and aggregation columns convert from the source to pivoted tables if that helps further.

How do I replace all the spaces with %20 in C#?

As commented on the approved story, the HttpServerUtility.UrlEncode method replaces spaces with + instead of %20. Use one of these two methods instead: Uri.EscapeUriString() or Uri.EscapeDataString()

Sample code:

HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//Output: "https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"

Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"

//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");    
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

Access to ES6 array element index inside for-of loop

es6 for...in

for(const index in [15, 64, 78]) {                        
    console.log(index);
}

Uncaught TypeError: Cannot read property 'top' of undefined

I had the same problem ("Uncaught TypeError: Cannot read property 'top' of undefined")

I tried every solution I could find and noting helped. But then I've spotted that my DIV had two IDs.

So, I removed second ID and it worked.

I just wish somebody told me to check my IDs earlier))

How do I get the different parts of a Flask request's url?

you should try:

request.url 

It suppose to work always, even on localhost (just did it).

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

No library, one line, properly padded

const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.

Local time instead of UTC

const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

Thanks for Ripon Al Wasim's answer. I did some improvement. because of network problems, I retry three times until break loop.

driver.get(url)
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
try_times = 0
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollBy(0,2000)")

    # Wait to load page
    time.sleep(scroll_delay)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")

    if last_height == new_height:
        try_times += 1

    if try_times > 3:
        try_times = 0
        break
    last_height = new_height

UIView frame, bounds and center

I think if you think it from the point of CALayer, everything is more clear.

Frame is not really a distinct property of the view or layer at all, it is a virtual property, computed from the bounds, position(UIView's center), and transform.

So basically how the layer/view layouts is really decided by these three property(and anchorPoint), and either of these three property won't change any other property, like changing transform doesn't change bounds.

How to remove non-alphanumeric characters?

For unicode characters, it is :

preg_replace("/[^[:alnum:][:space:]]/u", '', $string);

Style the first <td> column of a table differently

If you've to support IE7, a more compatible solution is:

/* only the cells with no cell before (aka the first one) */
td {
    padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
    padding-left: 0;
}

Also works fine with li; general sibling selector ~ may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.

How to zoom div content using jquery?

@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.

    var currentZoom = 1.0;

    $(document).ready(function () {
        $('#btn_ZoomIn').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
            })
        $('#btn_ZoomOut').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
            })
        $('#btn_ZoomReset').click(
            function () {
                currentZoom = 1.0
                $('#divName').animate({ 'zoom': 1 }, 'slow');
            })
    });

how to get value of selected item in autocomplete

To answer the question more generally, the answer is:

select: function( event , ui ) {
    alert( "You selected: " + ui.item.label );
}

Complete example :

_x000D_
_x000D_
$('#test').each(function(i, el) {_x000D_
    var that = $(el);_x000D_
    that.autocomplete({_x000D_
        source: ['apple','banana','orange'],_x000D_
        select: function( event , ui ) {_x000D_
            alert( "You selected: " + ui.item.label );_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
_x000D_
_x000D_

How to pass a list from Python, by Jinja2 to JavaScript

Make some invisible HTML tags like <label>, <p>, <input> etc. and name its id, and the class name is a pattern so that you can retrieve it later.

Let you have two lists maintenance_next[] and maintenance_block_time[] of the same length, and you want to pass these two list's data to javascript using the flask. So you take some invisible label tag and set its tag name is a pattern of list's index and set its class name as value at index.

_x000D_
_x000D_
{% for i in range(maintenance_next|length): %}_x000D_
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>_x000D_
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>_x000D_
{% endfor%}
_x000D_
_x000D_
_x000D_

Now you can retrieve the data in javascript using some javascript operation like below -

_x000D_
_x000D_
<script>_x000D_
var total_len = {{ total_len }};_x000D_
 _x000D_
for (var i = 0; i < total_len; i++) {_x000D_
    var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");_x000D_
    var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");_x000D_
    _x000D_
    //Do what you need to do with tm1 and tm2._x000D_
    _x000D_
    console.log(tm1);_x000D_
    console.log(tm2);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

Darkening an image with CSS (In any shape)

Webkit only solution

Quick solution, relies on the -webkit-mask-image property. -webkit-mask-image sets a mask image for an element.

There are a few gotchas with this method:

  • Obviously, only works in Webkit browsers
  • Requires an additional wrapper to apply the :after psuedo-element (IMG tags can't have :before/:after pseudo elements, grr)
  • Because there's an additional wrapper, I'm not sure how to use the attr(…) CSS function to get the IMG tag URL, so it's hard-coded into the CSS separately.

If you can look past those issues, this might be a possible solution. SVG filters will be even more flexible, and Canvas solutions will be even more flexible and have a wider range of support (SVG doesn't have Android 2.x support).

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

"replace" function examples

Here's two simple examples

> x <- letters[1:4]
> replace(x, 3, 'Z') #replacing 'c' by 'Z'
[1] "a" "b" "Z" "d"
> 
> y <- 1:10
> replace(y, c(4,5), c(20,30)) # replacing 4th and 5th elements by 20 and 30
 [1]  1  2  3 20 30  6  7  8  9 10

class << self idiom in Ruby

? singleton method is a method that is defined only for a single object.

Example:

class SomeClass
  class << self
    def test
    end
  end
end

test_obj = SomeClass.new

def test_obj.test_2
end

class << test_obj
  def test_3
  end
end

puts "Singleton's methods of SomeClass"
puts SomeClass.singleton_methods
puts '------------------------------------------'
puts "Singleton's methods of test_obj"
puts test_obj.singleton_methods

Singleton's methods of SomeClass

test


Singleton's methods of test_obj

test_2

test_3

Pretty-Print JSON Data to a File using Python

You can parse the JSON, then output it again with indents like this:

import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)

See http://docs.python.org/library/json.html for more info.

Set size of HTML page and browser window

This should work.

<!DOCTYPE html>
<html>
    <head>
        <title>Hello World</title>
        <style>
            html, body {
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 0;
                background-color: green;
            }
            #container {
                width: inherit;
                height: inherit;
                margin: 0;
                padding: 0;
                background-color: pink;
            }
            h1 {
                margin: 0;
                padding: 0;
            }
        </style>
    </head>
    <body>
        <div id="container">
            <h1>Hello World</h1>
        </div>
    </body>
</html>

The background colors are there so you can see how this works. Copy this code to a file and open it in your browser. Try playing around with the CSS a bit and see what happens.

The width: inherit; height: inherit; pulls the width and height from the parent element. This should be the default and is not truly necessary.

Try removing the h1 { ... } CSS block and see what happens. You might notice the layout reacts in an odd way. This is because the h1 element is influencing the layout of its container. You could prevent this by declaring overflow: hidden; on the container or the body.

I'd also suggest you do some reading on the CSS Box Model.

Android: How can I validate EditText input?

I have created this library for android where you can validate a material design EditText inside and EditTextLayout easily like this:

    compile 'com.github.TeleClinic:SmartEditText:0.1.0'

then you can use it like this:

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/passwordSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Password"
    app:setMandatoryErrorMsg="Mandatory field"
    app:setPasswordField="true"
    app:setRegexErrorMsg="Weak password"
    app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/ageSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Age"
    app:setMandatoryErrorMsg="Mandatory field"
    app:setRegexErrorMsg="Is that really your age :D?"
    app:setRegexString=".*\\d.*" />

Then you can check if it is valid like this:

    ageSmartEditText.check()

For more examples and customization check the repository https://github.com/TeleClinic/SmartEditText

Check time difference in Javascript

You can use moment js for this purpose. momentJs 'fromNow()' will give you any time difference from current time.

var m1 = any date time on moment format;

console.log(m1.fromNow());

Carriage return and Line feed... Are both required in C#?

I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.

The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.

Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).

This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.

Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications

Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)

How to add calendar events in Android?

Use this API in your code.. It will help u to insert event, event with reminder and event with meeting can be enabled... This api works for platform 2.1 and above Those who uses less then 2.1 instead of content://com.android.calendar/events use content://calendar/events

 public static long pushAppointmentsToCalender(Activity curActivity, String title, String addInfo, String place, int status, long startDate, boolean needReminder, boolean needMailService) {
    /***************** Event: note(without alert) *******************/

    String eventUriString = "content://com.android.calendar/events";
    ContentValues eventValues = new ContentValues();

    eventValues.put("calendar_id", 1); // id, We need to choose from
                                        // our mobile for primary
                                        // its 1
    eventValues.put("title", title);
    eventValues.put("description", addInfo);
    eventValues.put("eventLocation", place);

    long endDate = startDate + 1000 * 60 * 60; // For next 1hr

    eventValues.put("dtstart", startDate);
    eventValues.put("dtend", endDate);

    // values.put("allDay", 1); //If it is bithday alarm or such
    // kind (which should remind me for whole day) 0 for false, 1
    // for true
    eventValues.put("eventStatus", status); // This information is
    // sufficient for most
    // entries tentative (0),
    // confirmed (1) or canceled
    // (2):
    eventValues.put("eventTimezone", "UTC/GMT +2:00");
   /*Comment below visibility and transparency  column to avoid java.lang.IllegalArgumentException column visibility is invalid error */

    /*eventValues.put("visibility", 3); // visibility to default (0),
                                        // confidential (1), private
                                        // (2), or public (3):
    eventValues.put("transparency", 0); // You can control whether
                                        // an event consumes time
                                        // opaque (0) or transparent
                                        // (1).
      */
    eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

    Uri eventUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(eventUriString), eventValues);
    long eventID = Long.parseLong(eventUri.getLastPathSegment());

    if (needReminder) {
        /***************** Event: Reminder(with alert) Adding reminder to event *******************/

        String reminderUriString = "content://com.android.calendar/reminders";

        ContentValues reminderValues = new ContentValues();

        reminderValues.put("event_id", eventID);
        reminderValues.put("minutes", 5); // Default value of the
                                            // system. Minutes is a
                                            // integer
        reminderValues.put("method", 1); // Alert Methods: Default(0),
                                            // Alert(1), Email(2),
                                            // SMS(3)

        Uri reminderUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(reminderUriString), reminderValues);
    }

    /***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

    if (needMailService) {
        String attendeuesesUriString = "content://com.android.calendar/attendees";

        /********
         * To add multiple attendees need to insert ContentValues multiple
         * times
         ***********/
        ContentValues attendeesValues = new ContentValues();

        attendeesValues.put("event_id", eventID);
        attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
        attendeesValues.put("attendeeEmail", "[email protected]");// Attendee
                                                                            // E
                                                                            // mail
                                                                            // id
        attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
                                                        // Relationship_None(0),
                                                        // Organizer(2),
                                                        // Performer(3),
                                                        // Speaker(4)
        attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
                                                // Required(2), Resource(3)
        attendeesValues.put("attendeeStatus", 0); // NOne(0), Accepted(1),
                                                    // Decline(2),
                                                    // Invited(3),
                                                    // Tentative(4)

        Uri attendeuesesUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(attendeuesesUriString), attendeesValues);
    }

    return eventID;

}

Algorithm to generate all possible permutations of a list?

If anyone wonders how to be done in permutation in javascript.

Idea/pseudocode

  1. pick one element at a time
  2. permute rest of the element and then add the picked element to the all of the permutation

for example. 'a'+ permute(bc). permute of bc would be bc & cb. Now add these two will give abc, acb. similarly, pick b + permute (ac) will provice bac, bca...and keep going.

now look at the code

function permutations(arr){

   var len = arr.length, 
       perms = [],
       rest,
       picked,
       restPerms,
       next;

    //for one or less item there is only one permutation 
    if (len <= 1)
        return [arr];

    for (var i=0; i<len; i++)
    {
        //copy original array to avoid changing it while picking elements
        rest = Object.create(arr);

        //splice removed element change array original array(copied array)
        //[1,2,3,4].splice(2,1) will return [3] and remaining array = [1,2,4]
        picked = rest.splice(i, 1);

        //get the permutation of the rest of the elements
        restPerms = permutations(rest);

       // Now concat like a+permute(bc) for each
       for (var j=0; j<restPerms.length; j++)
       {
           next = picked.concat(restPerms[j]);
           perms.push(next);
       }
    }

   return perms;
}

Take your time to understand this. I got this code from (pertumation in JavaScript)

How to mute an html5 video player using jQuery

Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example

How can I add a username and password to Jenkins?

  • Try deleting the .jenkins folder from your system which is located ate the below path. C:\Users\"Your PC Name".jenkins

  • Now download a fresh and a stable version of .war file from official website of jenkins. For eg. 2.1 and follow the steps to install.

    • You will be able to do via this method

Swift: declare an empty dictionary

I'm playing with this too. It seems strange that you can just declare an empty dictionary and then add a key/value pair to it like so :

var emptyDictionary = Dictionary<String, Float>()
var flexDictionary = [:]
emptyDictionary["brian"] = 4.5
flexDictionary["key"] = "value" // ERROR : cannot assign to the result of this expression

But you can create a Dictionary that accepts different value types by using the "Any" type like so :

var emptyDictionary = Dictionary<String, Any>()
emptyDictionary["brian"] = 4.5
emptyDictionary["mike"] = "hello"

Is there a developers api for craigslist.org

Good news everybody! Craigslist has actually released a bulk posting api now!

Enjoy

pandas unique values multiple columns

pd.unique returns the unique values from an input array, or DataFrame column or index.

The input to this function needs to be one-dimensional, so multiple columns will need to be combined. The simplest way is to select the columns you want and then view the values in a flattened NumPy array. The whole operation looks like this:

>>> pd.unique(df[['Col1', 'Col2']].values.ravel('K'))
array(['Bob', 'Joe', 'Bill', 'Mary', 'Steve'], dtype=object)

Note that ravel() is an array method that returns a view (if possible) of a multidimensional array. The argument 'K' tells the method to flatten the array in the order the elements are stored in the memory (pandas typically stores underlying arrays in Fortran-contiguous order; columns before rows). This can be significantly faster than using the method's default 'C' order.


An alternative way is to select the columns and pass them to np.unique:

>>> np.unique(df[['Col1', 'Col2']].values)
array(['Bill', 'Bob', 'Joe', 'Mary', 'Steve'], dtype=object)

There is no need to use ravel() here as the method handles multidimensional arrays. Even so, this is likely to be slower than pd.unique as it uses a sort-based algorithm rather than a hashtable to identify unique values.

The difference in speed is significant for larger DataFrames (especially if there are only a handful of unique values):

>>> df1 = pd.concat([df]*100000, ignore_index=True) # DataFrame with 500000 rows
>>> %timeit np.unique(df1[['Col1', 'Col2']].values)
1 loop, best of 3: 1.12 s per loop

>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel('K'))
10 loops, best of 3: 38.9 ms per loop

>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel()) # ravel using C order
10 loops, best of 3: 49.9 ms per loop

Android - set TextView TextStyle programmatically?

This question is asked in a lot of places in a lot of different ways. I originally answered it here but I feel it's relevant in this thread as well (since i ended up here when I was searching for an answer).

There is no one line solution to this problem, but this worked for my use case. The problem is, the 'View(context, attrs, defStyle)' constructor does not refer to an actual style, it wants an attribute. So, we will:

  1. Define an attribute
  2. Create a style that you want to use
  3. Apply a style for that attribute on our theme
  4. Create new instances of our view with that attribute

In 'res/values/attrs.xml', define a new attribute:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="customTextViewStyle" format="reference"/>
    ...
</resources>    

In res/values/styles.xml' I'm going to create the style I want to use on my custom TextView

<style name="CustomTextView">
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:paddingLeft">14dp</item>
</style>

In 'res/values/themes.xml' or 'res/values/styles.xml', modify the theme for your application / activity and add the following style:

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <item name="@attr/customTextViewStyle">@style/CustomTextView</item>
    </style>
    ... 
</resources>

Finally, in your custom TextView, you can now use the constructor with the attribute and it will receive your style

public class CustomTextView extends TextView {

    public CustomTextView(Context context) {
       super(context, null, R.attr.customTextView);
    }
}

It's worth noting that I repeatedly used customTextView in different variants and different places, but it is in no way required that the name of the view match the style or the attribute or anything. Also, this technique should work with any custom view, not just TextViews.

jQuery.css() - marginLeft vs. margin-left?

when is marginLeft being used:

$("div").css({
    marginLeft:'12px',
    backgroundPosition:'10px -10px',
    minHeight: '40px'
});

As you can see, attributes that has a hyphen on it are converted to camelcased format. Using the margin-left from the previous code block above would make JavaScript bonkers because it will treat the hyphen as an operation for subtraction.

when is margin-left used:

$("div").css("margin-left","12px").css("background-position","10px -10px").css("min-height","40px");

Theoretically, both code blocks will do the same thing. We can allow hyphens on the second block because it is a string value while compared to the first block, it is somewhat an object.
Now that should make sense.

How to read file from relative path in Java project? java.io.File cannot find the path specified

For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem

how to display variable value in alert box?

$(document).ready(function(){

//    alert("test");
$("#name").click(function(){
var content = document.getElementById("ghufran").innerHTML ;
   alert(content);
  });

 //var content = $('#one').text();

})

there u go buddy this code actually works

Class method decorator with self arguments?

A more concise example might be as follows:

#/usr/bin/env python3
from functools import wraps

def wrapper(method):
    @wraps(method)
    def _impl(self, *method_args, **method_kwargs):
        method_output = method(self, *method_args, **method_kwargs)
        return method_output + "!"
    return _impl

class Foo:
    @wrapper
    def bar(self, word):
        return word

f = Foo()
result = f.bar("kitty")
print(result)

Which will print:

kitty!

Find the server name for an Oracle database

The query below demonstrates use of the package and some of the information you can get.

select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual

NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.

Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.

Format date with Moment.js

May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11

How can I get the named parameters from a URL using Flask?

Template Code

<table>
     <tr>
      <th style="min-width: 70px;">Sl No.</th>
      <th style="min-width: 350px;">Description</th>
      <th style="min-width: 100px;">Date</th>
      <th style="min-width: 50px;">Time</th>
      <th style="min-width: 50px;">Status</th>
      <th style="min-width: 50px;">Action</th>
      </tr>
      {% set count = [0] %}
      {% for val in data['todos']%}
      {% if count.append(count.pop() + 1) %}{% endif %}
      <tr>
      <td>{{count[0]}}</td>
      <td>{{val['description']}}</td>
      <td>{{val['date']}}</td>
      <td>{{val['time']}}</td>
      <td>{{val['status']}}</td>
      <td>
        <a class="fa fa-edit" href="#" style=" color: rgb(32, 252, 43);" ></a>
        <a class="fa fa-trash-alt" href="http://localhost:5000/delete?todoid={{val['_id']}}" onmouseout="this.style.color=' rgb(248, 153, 153)'" onmouseover="this.style.color='rgb(241, 74, 74)'" style="padding-left:8%; color: rgb(248, 153, 153);"></a>
      </td>
     </tr>
     {% endfor %}
    </table>

Route code

@app.route('/delete', methods=["GET"])
def deleteTodo():
id = request.args.get('todoid')
print(id)

How to exit a function in bash

If you want to return from an outer function with an error without exiting you can use this trick:

do-something-complex() {
  # Using `return` here would only return from `fail`, not from `do-something-complex`.
  # Using `exit` would close the entire shell.
  # So we (ab)use a different feature. :)
  fail() { : "${__fail_fast:?$1}"; }

  nested-func() {
      try-this || fail "This didn't work"
      try-that || fail "That didn't work"
  }
  nested-func
}

Trying it out:

$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work

This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex.

Note that this causes the outermost function to return 1.

How to get JavaScript variable value in PHP

You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.

Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.

If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.

<script type="text/javascript>
    var foo = <?php echo json_encode($somePhpVar); ?>
</script>

Make first letter of a string upper case (with maximum performance)

Recently I had a similar requirement and remembered that the LINQ function Select() provides an index:

string input;
string output;

input = "red house";
output = String.Concat(input.Select((currentChar, index) => index == 0 ? Char.ToUpper(currentChar) : currentChar));
//output = "Red house"

Since I need that very often I made an extension method for the string type:

public static class StringExtensions
{
    public static string FirstLetterToUpper(this string input)
    {
        if (string.IsNullOrEmpty(input))
            return string.Empty;
        return String.Concat(input.Select((currentChar, index) => index == 0 ? Char.ToUpper(currentChar) : currentChar));
    }
}

Please note that only the first letter is converted to upper case - all remaining characters are not touched. If you need the other characters to be lower case you may also call Char.ToLower(currentChar) for index > 0 or call ToLower() on the whole string in the first place.

Regarding performance I compared the code with the solution from Darren. On my machine Darren's code is about 2 times faster which is no surprise since he's directly editing only the first letter within a char array. So I suggest you take Darren's code if you need the fastest solution available. If you want to integrate other string manipulations as well it may be convenient to have the expressive power of a lambda function touching the characters of the input string - you can easily extend this function - so I leave this solution here.

How to COUNT rows within EntityFramework without loading contents?

This is my code:

IQueryable<AuctionRecord> records = db.AuctionRecord;
var count = records.Count();

Make sure the variable is defined as IQueryable then when you use Count() method, EF will execute something like

select count(*) from ...

Otherwise, if the records is defined as IEnumerable, the sql generated will query the entire table and count rows returned.

CronJob not running

Finally I found the solution. Following is the solution:-

  1. Never use relative path in python scripts to be executed via crontab. I did something like this instead:-

    import os
    import sys
    import time, datetime
    
    CLASS_PATH = '/srv/www/live/mainapp/classes'
    SETTINGS_PATH = '/srv/www/live/foodtrade'
    sys.path.insert(0, CLASS_PATH)
    sys.path.insert(1,SETTINGS_PATH)
    
    import other_py_files
    
  2. Never supress the crontab code instead use mailserver and check the mail for the user. That gives clearer insights of what is going.

Running .sh scripts in Git Bash

Let's say you have a script script.sh. To run it (using Git Bash), you do the following: [a] Add a "sh-bang" line on the first line (e.g. #!/bin/bash) and then [b]:

# Use ./ (or any valid dir spec):
./script.sh

Note: chmod +x does nothing to a script's executability on Git Bash. It won't hurt to run it, but it won't accomplish anything either.

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

If you have issue with writing into an existing xls file because it is already created you need to put checking part like below:

PATH='filename.xlsx'
if os.path.isfile(PATH):
    print "File exists and will be overwrite NOW"
else:
    print "The file is missing, new one is created"

... and here part with the data you want to add

Programmatically stop execution of python script?

You want sys.exit(). From Python's docs:

>>> import sys
>>> print sys.exit.__doc__
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).

So, basically, you'll do something like this:

from sys import exit

# Code!

exit(0) # Successful exit

how to split the ng-repeat data with three columns using bootstrap

m59's answer is pretty good. The one thing I don't like about it is that it uses divs for what could potentially be data for a table.

So in conjunction with m59's filter (answer somewhere above), here is how to display it in a table.

<table>
    <tr class="" ng-repeat="rows in foos | chunk:2">
        <td ng-repeat="item in rows">{{item}}</td>
    </tr>
</table>

How are cookies passed in the HTTP protocol?

create example script as resp :

#!/bin/bash

http_code=200
mime=text/html

echo -e "HTTP/1.1 $http_code OK\r"
echo "Content-type: $mime"
echo
echo "Set-Cookie: name=F"

then make executable and execute like this.

./resp | nc -l -p 12346

open browser and browse URL: http://localhost:1236 you will see Cookie value which is sent by Browser

    [aaa@bbbbbbbb ]$ ./resp | nc -l -p 12346
    GET / HTTP/1.1
    Host: xxx.xxx.xxx.xxx:12346
    Connection: keep-alive
    Cache-Control: max-age=0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8,ru;q=0.6
    Cookie: name=F

How to refresh a Page using react-route Link

Try like this.

You must give a function as value to onClick()

You button:

<button type="button" onClick={ refreshPage }> <span>Reload</span> </button> 

refreshPage function:

function refreshPage(){ 
    window.location.reload(); 
}

The property 'Id' is part of the object's key information and cannot be modified

I am using EF 4.0 and WPF and I had similar problem, and .... found the issue that solved it (at least for me) in a very simple way.

Because, like you, I thought it must be simple to update a field in a table (i.e. in your case: Contact) that is referenced to by a foreignkey from another table (i.e. in your case: ContactType).

However, the Error Message: ".... is part of the object's key information and cannot be modified." only appears when you try to update a Primary Key (which wasn't my intention at all).

Had a closer look at the XML code of my EntityModel and found it:

<EntityType Name="Contact">
    <Key>
        <PropertyRef Name="ID" />
        <PropertyRef Name="contactTypeID" />   <!-- This second line caused my problem -->
    </Key>
    <Property Name="ID" Type="int" Nullable="false" />
    ...
    ...
</EntityType>

For some reason (maybe I made some foolish mistake within my database), when Visual Studio autogenerated for me the DataModel from my database, it added in that very table (Contact), where I wanted to update the field (ContactTypeID) a second PropertyRef (second line).

I just deleted that second PropertyRef:

<PropertyRef Name="contactTypeID" />

in both, the store model and the conceptual model and .... issue was solved :-)

Hence, remains like:

<EntityType Name="Contact">
    <Key>
        <PropertyRef Name="ID" />
    </Key>
    <Property Name="ID" Type="int" Nullable="false" />
    ...
    ...
</EntityType>

Updates and Inserts are now running smoothly like a baby .... :-)

Hence, good idea to check the XML of the datamodel to verify that only your PK is listed as PropertyRef. Worked for me ... :-)

How do I diff the same file between two different commits on the same branch?

You can also compare two different files in two different revisions, like this:

git diff <revision_1>:<file_1> <revision_2>:<file_2>

UIButton: set image for selected-highlighted state

If you need the highlighted tint which the OS provides by default when you tap and hold on a custom button for the selected state as well, use this UIButton subclass. Written in Swift 5:

import Foundation
import UIKit
class HighlightOnSelectCustomButton: UIButton {
    override var isHighlighted: Bool {
        didSet {
            if (self.isSelected != isHighlighted) {
                self.isHighlighted = self.isSelected
            }
        }
    }
}

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

I just run into problem downloading google-services.json from Firebase console. Turns out I had to log out from all other google accounts than the one I was using for Firebase.

HTML 5 video or audio playlist

Try this solution, it takes an array of soundtracks and plays all of them, playlist-style, and even loops the playlist. The following uses a little Jquery to shorten getting the audio element. If you do not wish to use Jquery, replace the first line of the javascript with var audio = document.getElementById("audio"); and it will work the same.

Javascript:

var audio = $("#audio")[0];
var tracks = {
    list: ["track_01.mp3", "track_02.mp3", "track_03.mp3"], //Put any tracks you want in this array
    index: 0,
    next: function() {
        if (this.index == this.list.length - 1) this.index = 0;
        else {
            this.index += 1;
        }
    },
    play: function() {
        return this.list[this.index];
    }
}

audio.onended = function() {
    tracks.next();
    audio.src = tracks.play();
    audio.load();
    audio.play();
}

audio.src = tracks.play();

HTML:

<audio id="audio" controls>
    <source src="" />
</audio>

This will allow you to play as many songs as you want, in playlist style. Each song will start as soon as the previous one finishes. I do not believe this will work in Internet Explorer, but it's time to move on from that ancient thing anyways!

Just put any songs you want into the array tracks.list and it will play all of them one after the other. It also loops back to the first song once it's finished with the last one.

It's shorter than many of the answers, it accounts for as many tracks as you want, it's easily understandable, and it actually loads the audio before playing it (so it actually works), so I thought I would include it here. I could not find any sound files to use in a running snippet, but I tested it with 3 of my own soundtracks on Chrome and it works. The onended method, which detects the ended event, also works on all browsers except Internet Explorer according to caniuse.

NOTE: Just to be clear, this works with both audio and video.

Using OR operator in a jquery if statement

The logical OR '||' automatically short circuits if it meets a true condition once.

false || false || true || false = true, stops at second condition.

On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.

false && true && true && true = false, stops at first condition.

Specifying row names when reading in a file

See ?read.table. Basically, when you use read.table, you specify a number indicating the column:

##Row names in the first column
read.table(filname.txt, row.names=1)

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

In Apache Derby DB, refrain from using table names as "user" or so because they are reserved keywords on Apache Derby but will work fine on MySql.

In the Query, you must specify the name of the Entity class that you want to fetch the data from in the FROM clause of the Query.

List<User> users=session.createQuery("from User").list();

Here, User is the name of my Java Entity class(Consider the casing of the name as in Java it matters.)

How to delete files older than X hours

For SunOS 5.10

 Example 6 Selecting a File Using 24-hour Mode


 The descriptions of -atime, -ctime, and -mtime use the  ter-
 minology n ``24-hour periods''. For example, a file accessed
 at 23:59 is selected by:


   example% find . -atime -1 -print




 at 00:01 the next day (less than 24 hours  later,  not  more
 than one day ago). The midnight boundary between days has no
 effect on the 24-hour calculation.

adding multiple entries to a HashMap at once in one statement

Another approach may be writing special function to extract all elements values from one string by regular-expression:

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main (String[] args){
        HashMap<String,Integer> hashMapStringInteger = createHashMapStringIntegerInOneStat("'one' => '1', 'two' => '2' , 'three'=>'3'  ");

        System.out.println(hashMapStringInteger); // {one=1, two=2, three=3}
    }

    private static HashMap<String, Integer> createHashMapStringIntegerInOneStat(String str) {
        HashMap<String, Integer> returnVar = new HashMap<String, Integer>();

        String currentStr = str;
        Pattern pattern1 = Pattern.compile("^\\s*'([^']*)'\\s*=\\s*>\\s*'([^']*)'\\s*,?\\s*(.*)$");

        // Parse all elements in the given string.
        boolean thereIsMore = true;
        while (thereIsMore){
            Matcher matcher = pattern1.matcher(currentStr);
            if (matcher.find()) {
                returnVar.put(matcher.group(1),Integer.valueOf(matcher.group(2)));
                currentStr = matcher.group(3);
            }
            else{
                thereIsMore = false;
            }
        }

        // Validate that all elements in the given string were parsed properly
        if (currentStr.length() > 0){
            System.out.println("WARNING: Problematic string format. given String: " + str);
        }

        return returnVar;
    }
}

Checking if a number is a prime number in Python

def prime(x):
    # check that number is greater that 1
    if x > 1:
        for i in range(2, x + 1):
            # check that only x and 1 can evenly divide x
            if x % i == 0 and i != x and i != 1:
                return False
        else:
            return True
    else:
        return False # if number is negative

Checkout multiple git repos into same Jenkins workspace

Checking out more than one repo at a time in a single workspace is not possible with Jenkins + Git Plugin.

As a workaround, you can either have multiple upstream jobs which checkout a single repo each and then copy to your final project workspace (Problematic on a number of levels), or you can set up a shell scripting step which checks out each needed repo to the job workspace at build time.

Previously the Multiple SCM plugin could help with this issue but it is now deprecated. From the Multiple SCM plugin page: "Users should migrate to https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin . Pipeline offers a better way of checking out of multiple SCMs, and is supported by the Jenkins core development team."

PDF Editing in PHP?

Tcpdf is also a good liabrary for generating pdf in php http://www.tcpdf.org/

How to trim whitespace from a Bash variable?

Use:

var=`expr "$var" : "^\ *\(.*[^ ]\)\ *$"`

It removes leading and trailing spaces and is the most basic solution, I believe. Not Bash built-in, but 'expr' is a part of coreutils, so at least no standalone utilities are needed like sed or AWK.