Programs & Examples On #Scrubyt

How do I set up the database.yml file in Rails?

The database.yml is the file where you set up all the information to connect to the database. It differs depending on the kind of DB you use. You can find more information about this in the Rails Guide or any tutorial explaining how to setup a rails project.

The information in the database.yml file is scoped by environment, allowing you to get a different setting for testing, development or production. It is important that you keep those distinct if you don't want the data you use for development deleted by mistake while running your test suite.

Regarding source control, you should not commit this file but instead create a template file for other developers (called database.yml.template). When deploying, the convention is to create this database.yml file in /shared/config directly on the server.

With SVN: svn propset svn:ignore config "database.yml"

With Git: Add config/database.yml to the .gitignore file or with git-extra git ignore config/database.yml


... and now, some examples:

SQLite

adapter: sqlite3
database: db/db_dev_db.sqlite3
pool: 5
timeout: 5000

MYSQL

adapter: mysql
database: my_db
hostname: 127.0.0.1
username: root
password: 
socket: /tmp/mysql.sock
pool: 5
timeout: 5000

MongoDB with MongoID (called mongoid.yml, but basically the same thing)

host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
#   - host: slave1.local
#     port: 27018
#   - host: slave2.local
#     port: 27019

Options for HTML scraping?

In the .NET world, I recommend the HTML Agility Pack. Not near as simple as some of the above options (like HTMLSQL), but it's very flexible. It lets you maniuplate poorly formed HTML as if it were well formed XML, so you can use XPATH or just itereate over nodes.

http://www.codeplex.com/htmlagilitypack

How to get every first element in 2 dimensional list

Try using

for i in a :
  print(i[0])

i represents individual row in a.So,i[0] represnts the 1st element of each row.

Deep copy in ES6 using the spread syntax

I often use this:

function deepCopy(obj) {
    if(typeof obj !== 'object' || obj === null) {
        return obj;
    }

    if(obj instanceof Date) {
        return new Date(obj.getTime());
    }

    if(obj instanceof Array) {
        return obj.reduce((arr, item, i) => {
            arr[i] = deepCopy(item);
            return arr;
        }, []);
    }

    if(obj instanceof Object) {
        return Object.keys(obj).reduce((newObj, key) => {
            newObj[key] = deepCopy(obj[key]);
            return newObj;
        }, {})
    }
}

How can I extract a good quality JPEG image from a video file with ffmpeg?

Use -qscale:v to control quality

Use -qscale:v (or the alias -q:v) as an output option.

  • Normal range for JPEG is 2-31 with 31 being the worst quality.
  • The scale is linear with double the qscale being roughly half the bitrate.
  • Recommend trying values of 2-5.
  • You can use a value of 1 but you must add the -qmin 1 output option (because the default is -qmin 2).

To output a series of images:

ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg

See the image muxer documentation for more options involving image outputs.

To output a single image at ~60 seconds duration:

ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg

Also see

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

php $_GET and undefined index

Actually none of the proposed answers, although a good practice, would remove the warning.

For the sake of correctness, I'd do the following:

function getParameter($param, $defaultValue) {
    if (array_key_exists($param, $_GET)) {
        $value=$_GET[$param];
        return isSet($value)?$value:$defaultValue;
    }
    return $defaultValue;
}

This way, I check the _GET array for the key to exist without triggering the Warning. It's not a good idea to disable the warnings because a lot of times they are at least interesting to take a look.

To use the function you just do:

$myvar = getParameter("getparamer", "defaultValue")

so if the parameter exists, you get the value, and if it doesnt, you get the defaultValue.

How to do fade-in and fade-out with JavaScript and CSS

I like Ibu's one but, I think I have a better solution using his idea.

//Fade In.
element.style.opacity = 0;
var Op1 = 0;
var Op2 = 1;
var foo1, foo2;
foo1 = setInterval(Timer1, 20);
function Timer1()
{
    element.style.opacity = Op1;
    Op1 = Op1 + .01;
    console.log(Op1); //Option, but I recommend it for testing purposes.
    if (Op1 > 1)
    {
        clearInterval(foo1);
        foo2 = setInterval(Timer3, 20);
    }
}

This solution uses a additional equation unlike Ibu's solution, which used a multiplicative equation. The way it works is it takes a time increment (t), an opacity increment (o), and a opacity limit (l) in the equation, which is: (T = time of fade in miliseconds) [T = (l/o)*t]. the "20" represents the time increments or intervals (t), the ".01" represents the opacity increments (o), and the 1 represents the opacity limit (l). When you plug the numbers in the equation you get 2000 milliseconds (or 2 seconds). Here is the console log:

0.01
0.02
0.03
0.04
0.05
0.060000000000000005
0.07
0.08
0.09
0.09999999999999999
0.10999999999999999
0.11999999999999998
0.12999999999999998
0.13999999999999999
0.15
0.16
0.17
0.18000000000000002
0.19000000000000003
0.20000000000000004
0.21000000000000005
0.22000000000000006
0.23000000000000007
0.24000000000000007
0.25000000000000006
0.26000000000000006
0.2700000000000001
0.2800000000000001
0.2900000000000001
0.3000000000000001
0.3100000000000001
0.3200000000000001
0.3300000000000001
0.34000000000000014
0.35000000000000014
0.36000000000000015
0.37000000000000016
0.38000000000000017
0.3900000000000002
0.4000000000000002
0.4100000000000002
0.4200000000000002
0.4300000000000002
0.4400000000000002
0.45000000000000023
0.46000000000000024
0.47000000000000025
0.48000000000000026
0.49000000000000027
0.5000000000000002
0.5100000000000002
0.5200000000000002
0.5300000000000002
0.5400000000000003
0.5500000000000003
0.5600000000000003
0.5700000000000003
0.5800000000000003
0.5900000000000003
0.6000000000000003
0.6100000000000003
0.6200000000000003
0.6300000000000003
0.6400000000000003
0.6500000000000004
0.6600000000000004
0.6700000000000004
0.6800000000000004
0.6900000000000004
0.7000000000000004
0.7100000000000004
0.7200000000000004
0.7300000000000004
0.7400000000000004
0.7500000000000004
0.7600000000000005
0.7700000000000005
0.7800000000000005
0.7900000000000005
0.8000000000000005
0.8100000000000005
0.8200000000000005
0.8300000000000005
0.8400000000000005
0.8500000000000005
0.8600000000000005
0.8700000000000006
0.8800000000000006
0.8900000000000006
0.9000000000000006
0.9100000000000006
0.9200000000000006
0.9300000000000006
0.9400000000000006
0.9500000000000006
0.9600000000000006
0.9700000000000006
0.9800000000000006
0.9900000000000007
1.0000000000000007
1.0100000000000007

Notice how the opacity follows the opacity increment amount of .01 just like in the code. If you use the code Ibu made,

//I made slight edits but keeped the ESSENTIAL stuff in it.
var op = 0.01;  // initial opacity
var timer = setInterval(function () {
    if (op >= 1){
        clearInterval(timer);
    }
    element.style.opacity = op;
    op += op * 0.1;
}, 20);

you will get these numbers (or something similar) in you console log. Here is what I got.

0.0101
0.010201
0.01030301
0.0104060401
0.010510100501
0.010615201506009999
0.0107213535210701
0.0108285670562808
0.010936852726843608
0.011046221254112044
0.011156683466653165
0.011268250301319695
0.011380932804332892
0.01149474213237622
0.011609689553699983
0.011725786449236983
0.011843044313729352
0.011961474756866645
0.012081089504435313
0.012201900399479666
0.012323919403474463
0.012447158597509207
0.0125716301834843
0.012697346485319142
0.012824319950172334
0.012952563149674056
0.013082088781170797
0.013212909668982505
0.01334503876567233
0.013478489153329052
0.013613274044862343
0.013749406785310966
0.013886900853164076
0.014025769861695717
0.014166027560312674
0.014307687835915801
0.01445076471427496
0.01459527236141771
0.014741225085031886
0.014888637335882205
0.015037523709241028
0.015187898946333437
0.01533977793579677
0.015493175715154739
0.015648107472306286
0.01580458854702935
0.015962634432499644
0.01612226077682464
0.016283483384592887
0.016446318218438817
0.016610781400623206
0.01677688921462944
0.016944658106775732
0.01711410468784349
0.017285245734721923
0.017458098192069144
0.017632679173989835
0.01780900596572973
0.01798709602538703
0.018166966985640902
0.01834863665549731
0.018532123022052285
0.018717444252272807
0.018904618694795535
0.01909366488174349
0.019284601530560927
0.019477447545866538
0.0196722220213252
0.019868944241538455
0.02006763368395384
0.02026831002079338
0.020470993121001313
0.020675703052211326
0.02088246008273344
0.021091284683560776
0.021302197530396385
0.02151521950570035
0.021730371700757353
0.021947675417764927
0.022167152171942577
0.022388823693662
0.022612711930598623
0.022838839049904608
0.023067227440403654
0.02329789971480769
0.023530878711955767
0.023766187499075324
0.024003849374066077
0.02424388786780674
0.024486326746484807
0.024731190013949654
0.024978501914089152
0.025228286933230044
0.025480569802562344
0.025735375500587968
0.025992729255593847
0.026252656548149785
0.026515183113631283
0.026780334944767597
0.027048138294215273
0.027318619677157426
0.027591805873929
0.02786772393266829
0.028146401171994972
0.028427865183714922
0.02871214383555207
0.02899926527390759
0.029289257926646668
0.029582150505913136
0.029877972010972267
0.030176751731081992
0.030478519248392812
0.03078330444087674
0.031091137485285508
0.031402048860138365
0.03171606934873975
0.03203323004222715
0.03235356234264942
0.03267709796607591
0.03300386894573667
0.03333390763519403
0.03366724671154597
0.03400391917866143
0.03434395837044805
0.03468739795415253
0.03503427193369406
0.035384614653031
0.035738460799561306
0.03609584540755692
0.03645680386163249
0.03682137190024882
0.03718958561925131
0.03756148147544382
0.03793709629019826
0.03831646725310024
0.038699631925631243
0.03908662824488755
0.039477494527336426
0.03987226947260979
0.040270992167335894
0.04067370208900925
0.04108043910989934
0.04149124350099834
0.04190615593600832
0.042325217495368404
0.04274846967032209
0.04317595436702531
0.04360771391069556
0.044043791049802515
0.04448422896030054
0.04492907124990354
0.04537836196240258
0.045832145582026605
0.04629046703784687
0.04675337170822534
0.047220905425307595
0.04769311447956067
0.04817004562435628
0.04865174608059984
0.04913826354140584
0.0496296461768199
0.0501259426385881
0.05062720206497398
0.05113347408562372
0.05164480882647996
0.05216125691474476
0.05268286948389221
0.053209698178731134
0.05374179516051845
0.05427921311212363
0.05482200524324487
0.05537022529567732
0.05592392754863409
0.056483166824120426
0.05704799849236163
0.05761847847728525
0.0581946632620581
0.05877660989467868
0.059364375993625464
0.05995801975356172
0.060557599951097336
0.06116317595060831
0.06177480771011439
0.06239255578721554
0.0630164813450877
0.06364664615853857
0.06428311262012396
0.0649259437463252
0.06557520318378844
0.06623095521562633
0.0668932647677826
0.06756219741546042
0.06823781938961503
0.06892019758351117
0.06960939955934628
0.07030549355493974
0.07100854849048914
0.07171863397539403
0.07243582031514798
0.07316017851829945
0.07389178030348245
0.07463069810651728
0.07537700508758245
0.07613077513845827
0.07689208288984285
0.07766100371874128
0.0784376137559287
0.07922198989348798
0.08001420979242287
0.0808143518903471
0.08162249540925057
0.08243872036334307
0.0832631075669765
0.08409573864264626
0.08493669602907272
0.08578606298936345
0.08664392361925709
0.08751036285544966
0.08838546648400417
0.08926932114884421
0.09016201436033265
0.09106363450393598
0.09197427084897535
0.0928940135574651
0.09382295369303975
0.09476118322997015
0.09570879506226986
0.09666588301289256
0.09763254184302148
0.0986088672614517
0.09959495593406621
0.10059090549340688
0.10159681454834095
0.10261278269382436
0.1036389105207626
0.10467529962597022
0.10572205262222992
0.10677927314845222
0.10784706587993674
0.10892553653873611
0.11001479190412347
0.1111149398231647
0.11222608922139635
0.11334835011361032
0.11448183361474643
0.11562665195089389
0.11678291847040283
0.11795074765510685
0.11913025513165793
0.1203215576829745
0.12152477325980425
0.12274002099240229
0.12396742120232632
0.12520709541434957
0.12645916636849308
0.127723758032178
0.12900099561249978
0.13029100556862477
0.13159391562431103
0.13290985478055414
0.1342389533283597
0.13558134286164328
0.1369371562902597
0.1383065278531623
0.13968959313169393
0.14108648906301088
0.142497353953641
0.1439223274931774
0.14536155076810917
0.14681516627579025
0.14828331793854815
0.14976615111793362
0.15126381262911295
0.15277645075540408
0.15430421526295812
0.1558472574155877
0.15740572998974356
0.158979787289641
0.1605695851625374
0.16217528101416276
0.16379703382430438
0.16543500416254742
0.1670893542041729
0.16876024774621462
0.17044785022367676
0.17215232872591352
0.17387385201317265
0.17561259053330439
0.17736871643863744
0.1791424036030238
0.18093382763905405
0.1827431659154446
0.18457059757459904
0.18641630355034502
0.1882804665858485
0.19016327125170698
0.19206490396422404
0.19398555300386627
0.19592540853390494
0.197884662619244
0.19986350924543644
0.20186214433789082
0.20388076578126973
0.20591957343908243
0.20797876917347324
0.21005855686520797
0.21215914243386005
0.21428073385819865
0.21642354119678064
0.21858777660874845
0.22077365437483593
0.2229813909185843
0.22521120482777013
0.22746331687604782
0.2297379500448083
0.23203532954525638
0.23435568284070896
0.23669923966911605
0.2390662320658072
0.24145689438646528
0.24387146333032994
0.24631017796363325
0.24877327974326957
0.25126101254070227
0.2537736226661093
0.2563113588927704
0.2588744724816981
0.26146321720651505
0.2640778493785802
0.266718627872366
0.26938581415108964
0.27207967229260055
0.27480046901552657
0.27754847370568186
0.28032395844273866
0.28312719802716607
0.28595847000743774
0.2888180547075121
0.2917062352545872
0.2946232976071331
0.2975695305832044
0.3005452258890364
0.3035506781479268
0.3065861849294061
0.3096520467787002
0.3127485672464872
0.31587605291895204
0.31903481344814155
0.322225161582623
0.3254474131984492
0.3287018873304337
0.33198890620373805
0.33530879526577545
0.3386618832184332
0.34204850205061754
0.3454689870711237
0.34892367694183496
0.35241291371125333
0.35593704284836586
0.3594964132768495
0.363091377409618
0.3667222911837142
0.3703895140955513
0.37409340923650686
0.37783434332887195
0.38161268676216065
0.38542881362978226
0.3892831017660801
0.3931759327837409
0.3971076921115783
0.40107876903269407
0.405089556723021
0.4091404522902512
0.4132318568131537
0.41736417538128523
0.4215378171350981
0.42575319530644906
0.43001072725951356
0.43431083453210867
0.43865394287742976
0.4430404823062041
0.44747088712926614
0.4519455960005588
0.45646505196056436
0.46102970248017
0.4656399995049717
0.47029639950002144
0.47499936349502164
0.47974935712997185
0.48454685070127157
0.4893923192082843
0.4942862424003671
0.4992291048243708
0.5042213958726145
0.5092636098313407
0.5143562459296541
0.5194998083889507
0.5246948064728402
0.5299417545375685
0.5352411720829442
0.5405935838037736
0.5459995196418114
0.5514595148382295
0.5569741099866118
0.5625438510864779
0.5681692895973427
0.5738509824933161
0.5795894923182493
0.5853853872414317
0.5912392411138461
0.5971516335249846
0.6031231498602344
0.6091543813588367
0.615245925172425
0.6213983844241493
0.6276123682683908
0.6338884919510748
0.6402273768705855
0.6466296506392913
0.6530959471456843
0.6596269066171412
0.6662231756833126
0.6728854074401457
0.6796142615145472
0.6864104041296927
0.6932745081709896
0.7002072532526995
0.7072093257852266
0.7142814190430788
0.7214242332335097
0.7286384755658448
0.7359248603215033
0.7432841089247183
0.7507169500139654
0.7582241195141051
0.7658063607092461
0.7734644243163386
0.7811990685595019
0.789011059245097
0.7969011698375479
0.8048701815359234
0.8129188833512826
0.8210480721847955
0.8292585529066434
0.8375511384357098
0.8459266498200669
0.8543859163182677
0.8629297754814503
0.8715590732362648
0.8802746639686274
0.8890774106083137
0.8979681847143969
0.9069478665615408
0.9160173452271562
0.9251775186794278
0.9344292938662221
0.9437735868048843
0.9532113226729332
0.9627434358996625
0.9723708702586591
0.9820945789612456
0.9919155247508581
1.0018346799983666
1.0118530267983503

Notice that there is no discernible pattern. If you ran Ibu's code, you would never know how long the fade was. You would have to grab a timer and guess and check 2 seconds. Nonetheless, Ibu's code did make a pretty nice fade in (it probably works for fade out. I don't know because I didn't use a fade out yet). My code will also work for a fade out. Let's just say you wanted 2 seconds for a fade out. You can do that with my code. Here is how it would look:

//Fade out. (Continued from the fade in.
function Timer2()
{
    element.style.opacity = Op2;
    Op2 = Op2 - .01;
    console.log(Op2); //Option, but I recommend it for testing purposes.
    if (Op2 < 0)
    { 
        clearInterval(foo2);
    }
}

All I did was change the opacity to 1 (or fully opaque). I changed the opacity increment to -.01 so it would start turning invisible. Lastly, I changed the opacity limit to 0. When it hits the opacity limit, the timer will stop. Same as the last one, except it used 1 instead of 0. When you run the code, here is what the console log should relatively look like.

.99
0.98
0.97
0.96
0.95
0.94
0.9299999999999999
0.9199999999999999
0.9099999999999999
0.8999999999999999
0.8899999999999999
0.8799999999999999
0.8699999999999999
0.8599999999999999
0.8499999999999999
0.8399999999999999
0.8299999999999998
0.8199999999999998
0.8099999999999998
0.7999999999999998
0.7899999999999998
0.7799999999999998
0.7699999999999998
0.7599999999999998
0.7499999999999998
0.7399999999999998
0.7299999999999998
0.7199999999999998
0.7099999999999997
0.6999999999999997
0.6899999999999997
0.6799999999999997
0.6699999999999997
0.6599999999999997
0.6499999999999997
0.6399999999999997
0.6299999999999997
0.6199999999999997
0.6099999999999997
0.5999999999999996
0.5899999999999996
0.5799999999999996
0.5699999999999996
0.5599999999999996
0.5499999999999996
0.5399999999999996
0.5299999999999996
0.5199999999999996
0.5099999999999996
0.49999999999999956
0.48999999999999955
0.47999999999999954
0.46999999999999953
0.4599999999999995
0.4499999999999995
0.4399999999999995
0.4299999999999995
0.4199999999999995
0.4099999999999995
0.39999999999999947
0.38999999999999946
0.37999999999999945
0.36999999999999944
0.35999999999999943
0.3499999999999994
0.3399999999999994
0.3299999999999994
0.3199999999999994
0.3099999999999994
0.2999999999999994
0.28999999999999937
0.27999999999999936
0.26999999999999935
0.25999999999999934
0.24999999999999933
0.23999999999999932
0.22999999999999932
0.2199999999999993
0.2099999999999993
0.1999999999999993
0.18999999999999928
0.17999999999999927
0.16999999999999926
0.15999999999999925
0.14999999999999925
0.13999999999999924
0.12999999999999923
0.11999999999999923
0.10999999999999924
0.09999999999999924
0.08999999999999925
0.07999999999999925
0.06999999999999926
0.059999999999999255
0.04999999999999925
0.03999999999999925
0.02999999999999925
0.019999999999999248
0.009999999999999247
-7.528699885739343e-16
-0.010000000000000753

As you can see, the .01 pattern still exists in the fade out. Both fades are smooth and precise. I hope these codes helped you or gave you insight on the topic. If you have any additions or suggestions let me know. Thank you for taking the time to view this!

How to give Jenkins more heap space when it´s started as a service under Windows?

From the Jenkins wiki:

The JVM launch parameters of these Windows services are controlled by an XML file jenkins.xml and jenkins-slave.xml respectively. These files can be found in $JENKINS_HOME and in the slave root directory respectively, after you've install them as Windows services.

The file format should be self-explanatory. Tweak the arguments for example to give JVM a bigger memory.

https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+as+a+Windows+service

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

How to delete a file from SD card?

This works for me: (Delete image from Gallery)

File file = new File(photoPath);
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));

CSS vertical alignment of inline/inline-block elements

Give vertical-align:top; in a & span. Like this:

a, span{
 vertical-align:top;
}

Check this http://jsfiddle.net/TFPx8/10/

Convert PEM to PPK file format

I had the same issue with PuttyGen not wanting to import an openSSH private key. I tried everything and what I found out was the old version of PuttyGen did not support importing OpenSSH. Once I downloaded the latest Putty, puttygen then allowed it to import the openssh private key just fine. I now have a hole in the side of my desk for pounding my head against it for the past hour.

Error: could not find function ... in R

I got the same, error, I was running version .99xxx, I checked for updates from help menu and updated My RStudio to 1.0x, then the error did not come

So simple solution, just update your R Studio

indexOf method in an object array?

This works without custom code

var arr, a, found;
arr = [{x: 1, y: 2}];
a = {x: 1, y: 2};
found = JSON.stringify(arr).indexOf(JSON.stringify(a)) > - 1;
// found === true

Note: this does not give the actual index, it only tells if your object exists in the current data structure

Is there a “not in” operator in JavaScript for checking object properties?

Personally I find

if (id in tutorTimes === false) { ... }

easier to read than

if (!(id in tutorTimes)) { ... }

but both will work.

How to Select Every Row Where Column Value is NOT Distinct

How about

SELECT EmailAddress, CustomerName FROM Customers a
WHERE Exists ( SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress)

Why are my PowerShell scripts not running?

We can bypass execution policy in a nice way (inside command prompt):

type file.ps1 | powershell -command -

Or inside powershell:

gc file.ps1|powershell -c -

Python how to exit main function

You can't return because you're not in a function. You can exit though.

import sys
sys.exit(0)

0 (the default) means success, non-zero means failure.

Why use Select Top 100 Percent?

Just try this, it explains it pretty much itself. You can't create a view with an ORDER BY except if...

CREATE VIEW v_Test
         AS
           SELECT name
             FROM sysobjects
         ORDER BY name
        GO

Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","

How to run a single test with Mocha?

Looking into https://mochajs.org/#usage we see that simply use

mocha test/myfile

will work. You can omit the '.js' at the end.

Could not obtain information about Windows NT group user

I just got this error and it turns out my AD administrator deleted the service account used by EVERY SQL Server instance in the entire company. Thank goodness AD has its own recycle bin.

See if you can run the Active Directory Users and Computers utility (%SystemRoot%\system32\dsa.msc), and check to make sure the account you are relying on still exists.

batch to copy files with xcopy

You must specify your file in the copy:

xcopy C:\source\myfile.txt C:\target

Or if you want to copy all txt files for example

xcopy C:\source\*.txt C:\target

List names of all tables in a SQL Server 2012 schema

SELECT *
FROM sys.tables t
INNER JOIN sys.objects o on o.object_id = t.object_id
WHERE o.is_ms_shipped = 0;

Histogram with Logarithmic Scale and custom breaks

Another option would be to use the package ggplot2.

ggplot(mydata, aes(x = V3)) + geom_histogram() + scale_x_log10()

Undo a Git merge that hasn't been pushed yet

See chapter 4 in the Git book and the original post by Linus Torvalds.

To undo a merge that was already pushed:

git revert -m 1 commit_hash

Be sure to revert the revert if you're committing the branch again, like Linus said.

What is __future__ in Python used for and how/when to use it, and how it works

__future__ is a pseudo-module which programmers can use to enable new language features which are not compatible with the current interpreter. For example, the expression 11/4 currently evaluates to 2. If the module in which it is executed had enabled true division by executing:

from __future__ import division

the expression 11/4 would evaluate to 2.75. By importing the __future__ module and evaluating its variables, you can see when a new feature was first added to the language and when it will become the default:

  >>> import __future__
  >>> __future__.division
  _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

Extracting .jar file with command line

jar xf myFile.jar
change myFile to name of your file
this will save the contents in the current folder of .jar file
that should do :)

Android load from URL to Bitmap

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}

Check file uploaded is in csv format

simple use "accept" and "required" in and avoiding so much typical and unwanted coding.

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

How to write hello world in assembler under Windows?

Unless you call some function this is not at all trivial. (And, seriously, there's no real difference in complexity between calling printf and calling a win32 api function.)

Even DOS int 21h is really just a function call, even if its a different API.

If you want to do it without help you need to talk to your video hardware directly, likely writing bitmaps of the letters of "Hello world" into a framebuffer. Even then the video card is doing the work of translating those memory values into DisplayPort/HDMI/DVI/VGA signals.

Note that, really, none of this stuff all the way down to the hardware is any more interesting in ASM than in C. A "hello world" program boils down to a function call. One nice thing about ASM is that you can use any ABI you want fairly easily; you just need to know what that ABI is.

Export and import table dump (.sql) using pgAdmin

Using PgAdmin step 1: select schema and right click and go to Backup..enter image description here

step 2: Give the file name and click the backup button.

enter image description here

step 3: In detail message copy the backup file path.

enter image description here

step 4:

Go to other schema and right click and go to Restore. (see step 1)

step 5:

In popup menu paste aboved file path to filename category and click Restore button.

enter image description here

React Checkbox not sending onChange

In the scenario you would NOT like to use the onChange handler on the input DOM, you can use the onClick property as an alternative. The defaultChecked, the condition may leave a fixed state for v16 IINM.

 class CrossOutCheckbox extends Component {
      constructor(init){
          super(init);
          this.handleChange = this.handleChange.bind(this);
      }
      handleChange({target}){
          if (target.checked){
             target.removeAttribute('checked');
             target.parentNode.style.textDecoration = "";
          } else {
             target.setAttribute('checked', true);
             target.parentNode.style.textDecoration = "line-through";
          }
      }
      render(){
         return (
            <span>
              <label style={{textDecoration: this.props.complete?"line-through":""}}>
                 <input type="checkbox"
                        onClick={this.handleChange}
                        defaultChecked={this.props.complete}
                  />
              </label>
                {this.props.text}
            </span>
        )
    }
 }

I hope this helps someone in the future.

Entityframework Join using join method and lambdas

You can find a few examples here:

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contacts = ds.Tables["Contact"];
DataTable orders = ds.Tables["SalesOrderHeader"];

var query =
    contacts.AsEnumerable().Join(orders.AsEnumerable(),
    order => order.Field<Int32>("ContactID"),
    contact => contact.Field<Int32>("ContactID"),
    (contact, order) => new
    {
        ContactID = contact.Field<Int32>("ContactID"),
        SalesOrderID = order.Field<Int32>("SalesOrderID"),
        FirstName = contact.Field<string>("FirstName"),
        Lastname = contact.Field<string>("Lastname"),
        TotalDue = order.Field<decimal>("TotalDue")
    });


foreach (var contact_order in query)
{
    Console.WriteLine("ContactID: {0} "
                    + "SalesOrderID: {1} "
                    + "FirstName: {2} "
                    + "Lastname: {3} "
                    + "TotalDue: {4}",
        contact_order.ContactID,
        contact_order.SalesOrderID,
        contact_order.FirstName,
        contact_order.Lastname,
        contact_order.TotalDue);
}

Or just google for 'linq join method syntax'.

Maven compile with multiple src directories

Used the build-helper-maven-plugin from the post - and update src/main/generated. And mvn clean compile works on my ../common/src/main/java, or on ../common, so kept the latter. Then yes, confirming that IntelliJ IDEA (ver 10.5.2) level of the compilation failed as David Phillips mentioned. The issue was that IDEA did not add another source root to the project. Adding it manually solved the issue. It's not nice as editing anything in the project should come from maven and not from direct editing of IDEA's project options. Yet I will be able to live with it until they support build-helper-maven-plugin directly such that it will auto add the sources.

Then needed another workaround to make this work though. Since each time IDEA re-imported maven settings after a pom change me newly added source was kept on module, yet it lost it's Source Folders selections and was useless. So for IDEA - need to set these once:

  • Select - Project Settings / Maven / Importing / keep source and test folders on reimport.
  • Add - Project Structure / Project Settings / Modules / {Module} / Sources / Add Content Root.

Now keeping those folders on import is not the best practice in the world either, ..., but giving it a try.

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

[Joke mode on]

You can fix this by adding this:

https://github.com/donavon/undefined-is-a-function

import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.

[joke mode off]

Is there a difference between `continue` and `pass` in a for loop in python?

Consider it this way:

Pass: Python works purely on indentation! There are no empty curly braces, unlike other languages.

So, if you want to do nothing in case a condition is true there is no option other than pass.

Continue: This is useful only in case of loops. In case, for a range of values, you don't want to execute the remaining statements of the loop after that condition is true for that particular pass, then you will have to use continue.

Ordering by specific field value first

This works for me using Postgres 9+:

SELECT *
FROM your_table
ORDER BY name = 'core' DESC, priority DESC

How to push a docker image to a private repository

First go to your Docker Hub account and make the repo. Here is a screenshot of my Docker Hub account: enter image description here

From the pic, you can see my repo is “chuangg”

Now go into the repo and make it private by clicking on your image’s name. So for me, I clicked on “chuangg/gene_commited_image”, then I went to Settings -> Make Private. Then I followed the on screen instructions enter image description here

HOW TO UPLOAD YOUR DOCKER IMAGE ONTO DOCKER HUB

Method #1= Pushing your image through the command line (cli)

1) docker commit <container ID> <repo name>/<Name you want to give the image>

Yes, I think it has to be the container ID. It probably cannot be the image ID.

For example= docker commit 99e078826312 chuangg/gene_commited_image

2) docker run -it chaung/gene_commited_image

3) docker login --username=<user username> --password=<user password>

For example= docker login --username=chuangg [email protected]

Yes, you have to login first. Logout using “docker logout”

4) docker push chuangg/gene_commited_image

Method #2= Pushing your image using pom.xml and command line.

Note, I used a Maven Profile called “build-docker”. If you don’t want to use a profile, just remove the <profiles>, <profile>, and <id>build-docker</id> elements.

Inside the parent pom.xml:

<profiles>
        <profile>
            <id>build-docker</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>io.fabric8</groupId>
                        <artifactId>docker-maven-plugin</artifactId>
                        <version>0.18.1</version>
                        <configuration>
                            <images>
                                <image>
                                    <name>chuangg/gene_project</name>
                                    <alias>${docker.container.name}</alias>
                                    <!-- Configure build settings -->
                                    <build>
                                        <dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
                                        <assembly>
                                            <inline>
                                                <fileSets>
                                                    <fileSet>
                                                        <directory>${project.basedir}\target</directory>
                                                        <outputDirectory>.</outputDirectory>
                                                        <includes>
                                                            <include>*.jar</include>
                                                        </includes>
                                                    </fileSet>
                                                </fileSets>
                                            </inline>
                                        </assembly>
                                    </build>
                                </image>
                            </images>
                        </configuration>
                        <executions>
                            <execution>
                                <id>docker:build</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>build</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

Docker Terminal Command to deploy the Docker Image (from the directory where your pom.xml is located)= mvn clean deploy -Pbuild-docker docker:push

Note, the difference between Method #2 and #3 is that Method #3 has an extra <execution> for the deployment.

Method #3= Using Maven to automatically deploy to Docker Hub

Add this stuff to your parent pom.xml:

    <distributionManagement>
        <repository>
            <id>gene</id>
            <name>chuangg</name>
            <uniqueVersion>false</uniqueVersion>
            <layout>legacy</layout>
            <url>https://index.docker.io/v1/</url>
        </repository>
    </distributionManagement>


    <profiles>
        <profile>
            <id>build-docker</id>
            <build>
                <plugins>

                    <plugin>
                        <groupId>io.fabric8</groupId>
                        <artifactId>docker-maven-plugin</artifactId>
                        <version>0.18.1</version>
                        <configuration>
                            <images>
                                <image>
                                    <name>chuangg/gene_project1</name>
                                    <alias>${docker.container.name}</alias>
                                    <!-- Configure build settings -->
                                    <build>
                                        <dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
                                        <assembly>
                                            <inline>
                                                <fileSets>
                                                    <fileSet>
                                                        <directory>${project.basedir}\target</directory>
                                                        <outputDirectory>.</outputDirectory>
                                                        <includes>
                                                            <include>*.jar</include>
                                                        </includes>
                                                    </fileSet>
                                                </fileSets>
                                            </inline>
                                        </assembly>
                                    </build>
                                </image>
                            </images>
                        </configuration>
                        <executions>
                            <execution>
                                <id>docker:build</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>build</goal>
                                </goals>
                            </execution>
                            <execution>
                                <id>docker:push</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>push</goal>
                                </goals>
                            </execution>

                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

Go to C:\Users\Gene.docker\ directory and add this to your config.json file: enter image description here

Now in your Docker Quickstart Terminal type= mvn clean install -Pbuild-docker

For those of you not using Maven Profiles, just type mvn clean install

Here is the screenshot of the success message: enter image description here

Here is my full pom.xml and a screenshot of my directory structure:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gene.app</groupId>
<artifactId>VendingMachineDockerMavenPlugin</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Maven Quick Start Archetype</name>
<url>www.gene.com</url>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.gene.sample.Customer_View</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>

                    <source>1.7</source>
                    <target>1.7</target>

                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>


<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>

</dependencies>

<distributionManagement>
    <repository>
        <id>gene</id>
        <name>chuangg</name>
        <uniqueVersion>false</uniqueVersion>
        <layout>legacy</layout>
        <url>https://index.docker.io/v1/</url>
    </repository>
</distributionManagement>


<profiles>
    <profile>
        <id>build-docker</id>
        <properties>
            <java.docker.version>1.8.0</java.docker.version>
        </properties>
        <build>
            <plugins>

                <plugin>
                    <groupId>io.fabric8</groupId>
                    <artifactId>docker-maven-plugin</artifactId>
                    <version>0.18.1</version>
                    <configuration>
                        <images>
                            <image>
                                <name>chuangg/gene_project1</name>
                                <alias>${docker.container.name}</alias>
                                <!-- Configure build settings -->
                                <build>
                                    <dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
                                    <assembly>
                                        <inline>
                                            <fileSets>
                                                <fileSet>
                                                    <directory>${project.basedir}\target</directory>
                                                    <outputDirectory>.</outputDirectory>
                                                    <includes>
                                                        <include>*.jar</include>
                                                    </includes>
                                                </fileSet>
                                            </fileSets>
                                        </inline>
                                    </assembly>
                                </build>
                            </image>
                        </images>
                    </configuration>
                    <executions>
                        <execution>
                            <id>docker:build</id>
                            <phase>package</phase>
                            <goals>
                                <goal>build</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>docker:push</id>
                            <phase>install</phase>
                            <goals>
                                <goal>push</goal>
                            </goals>
                        </execution>

                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

Here is my Eclipse Directory: enter image description here

Here is my Dockerfile:

FROM java:8

MAINTAINER Gene Chuang
RUN echo Running Dockerfile in src/docker/vending_machine_emulator/Dockerfile directory

ADD maven/VendingMachineDockerMavenPlugin-1.0-SNAPSHOT.jar /bullshitDirectory/gene-app-1.0-SNAPSHOT.jar 

CMD ["java", "-classpath", "/bullshitDirectory/gene-app-1.0-SNAPSHOT.jar", "com/gene/sample/Customer_View" ] 

Common Error #1: enter image description here

Solution for Error #1= Do not sync the <execution> with maven deploy phase because then maven tries to deploy the image 2x and puts a timestamp on the jar. That’s why I used <phase>install</phase>.

Is it better to use NOT or <> when comparing values?

Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.

If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.

What's the CMake syntax to set and use variables?

Here are a couple basic examples to get started quick and dirty.

One item variable

Set variable:

SET(INSTALL_ETC_DIR "etc")

Use variable:

SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")

Multi-item variable (ie. list)

Set variable:

SET(PROGRAM_SRCS
        program.c
        program_utils.c
        a_lib.c
        b_lib.c
        config.c
        )

Use variable:

add_executable(program "${PROGRAM_SRCS}")

CMake docs on variables

Undefined symbols for architecture armv7

Another possible cause of "undefined symbol" linker errors is attempting to call a C function from a .mm file. In this case you'll need to use extern "C" {...} when you import the header files.

Linker error calling C-Function from Objective-C++

Skipping error in for-loop

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Share link on Google+

<meta property="og:title" content="Ali Umair"/>
<meta property="og:description" content="Ali UMair is a web developer"/><meta property="og:image" content="../image" />

<a target="_blank" href="https://plus.google.com/share?url=<? echo urlencode('http://www..'); ?>"><img src="../gplus-black_icon.png" alt="" /></a>

this code will work with image text and description please put meta into head tag

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

Media Player called in state 0, error (-38,0)

i tested below code. working fine

public class test extends Activity implements OnErrorListener, OnPreparedListener {

private MediaPlayer player;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        player.setDataSource("http://www.hubharp.com/web_sound/BachGavotte.mp3");
        player.setOnErrorListener(this);
        player.setOnPreparedListener(this);
        player.prepareAsync();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
}
@Override
public void onDestroy() {
    super.onDestroy();
    player.release();
    player = null;
}
@Override
public void onPrepared(MediaPlayer play) {
    play.start();
}
@Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
    return false;
}
}

How to make a loop in x86 assembly language?

I was looking for same answer & found this info from wiki useful: Loop Instructions

The loop instruction decrements ECX and jumps to the address specified by arg unless decrementing ECX caused its value to become zero. For example:

 mov ecx, 5
 start_loop:
 ; the code here would be executed 5 times
 loop start_loop

loop does not set any flags.

loopx arg

These loop instructions decrement ECX and jump to the address specified by arg if their condition is satisfied (that is, a specific flag is set), unless decrementing ECX caused its value to become zero.

  • loope loop if equal

  • loopne loop if not equal

  • loopnz loop if not zero

  • loopz loop if zero

Source: X86 Assembly, Control Flow

How can I get the height and width of an uiimage?

Some of the anwsers above, don't work well when rotating device.

Try:

CGRect imageContent = self.myUIImage.bounds;
CGFloat imageWidth = imageContent.size.width;
CGFloat imageHeight = imageContent.size.height;

How to use select/option/NgFor on an array of objects in Angular2

I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:

interface TestObject {
  name:string;
  value:number;
}

@Component({
  selector: 'app',
  template: `
      <h4>Select Object via 2-way binding</h4>

      <select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
      </select>

      <h4>You selected:</h4> {{selectedObject }}
  `,
  directives: [FORM_DIRECTIVES]
})
export class App {
  objArray:TestObject[];
  selectedObject:TestObject;
  constructor(){
    this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
    this.selectedObject = this.objArray[1];
  }
  updateSelectedValue(event:string): void{
    this.selectedObject = JSON.parse(event);
  }
}

How to export JSON from MongoDB using Robomongo

Solution:

mongoexport --db test --collection traffic --out traffic.json<br><br>

enter image description here

Where:
database -> mock-server
collection name -> api_defs
output file name -> childChoreRequest.json

Can I get div's background-image url?

I'm using this one

  function getBackgroundImageUrl($element) {
    if (!($element instanceof jQuery)) {
      $element = $($element);
    }

    var imageUrl = $element.css('background-image');
    return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
  }

Is there a conditional ternary operator in VB.NET?

Depends upon the version. The If operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement

Example:

Dim foo as String = If(bar = buz, cat, dog)

[EDIT]

Prior to 2008 it was IIf, which worked almost identically to the If operator described Above.

Example:

Dim foo as String = IIf(bar = buz, cat, dog)

Add querystring parameters to link_to

The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?

link_to can also produce links with anchors or query strings:

link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>

link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>

link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>

Using SSH keys inside docker container

If you don't care about the security of your SSH keys, there are many good answers here. If you do, the best answer I found was from a link in a comment above to this GitHub comment by diegocsandrim. So that others are more likely to see it, and just in case that repo ever goes away, here is an edited version of that answer:

Most solutions here end up leaving the private key in the image. This is bad, as anyone with access to the image has access to your private key. Since we don't know enough about the behavior of squash, this may still be the case even if you delete the key and squash that layer.

We generate a pre-sign URL to access the key with aws s3 cli, and limit the access for about 5 minutes, we save this pre-sign URL into a file in repo directory, then in dockerfile we add it to the image.

In dockerfile we have a RUN command that do all these steps: use the pre-sing URL to get the ssh key, run npm install, and remove the ssh key.

By doing this in one single command the ssh key would not be stored in any layer, but the pre-sign URL will be stored, and this is not a problem because the URL will not be valid after 5 minutes.

The build script looks like:

# build.sh
aws s3 presign s3://my_bucket/my_key --expires-in 300 > ./pre_sign_url
docker build -t my-service .

Dockerfile looks like this:

FROM node

COPY . .

RUN eval "$(ssh-agent -s)" && \
    wget -i ./pre_sign_url -q -O - > ./my_key && \
    chmod 700 ./my_key && \
    ssh-add ./my_key && \
    ssh -o StrictHostKeyChecking=no [email protected] || true && \
    npm install --production && \
    rm ./my_key && \
    rm -rf ~/.ssh/*

ENTRYPOINT ["npm", "run"]

CMD ["start"]

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The only difference is that CHARACTER VARYING is more human friendly than VARCHAR

Difference between Inheritance and Composition

The answer given by @Michael Rodrigues is not correct (I apologize; I'm not able to comment directly), and could lead to some confusion.

Interface implementation is a form of inheritance... when you implement an interface, you're not only inheriting all the constants, you are committing your object to be of the type specified by the interface; it's still an "is-a" relationship. If a car implements Fillable, the car "is-a" Fillable, and can be used in your code wherever you would use a Fillable.

Composition is fundamentally different from inheritance. When you use composition, you are (as the other answers note) making a "has-a" relationship between two objects, as opposed to the "is-a" relationship that you make when you use inheritance.

So, from the car examples in the other questions, if I wanted to say that a car "has-a" gas tank, I would use composition, as follows:

public class Car {

private GasTank myCarsGasTank;

}

Hopefully that clears up any misunderstanding.

Graph visualization library in JavaScript

I've just put together what you may be looking for: http://www.graphdracula.net

It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:

var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");

I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!


You may want to have a look at other projects, too! Below are two meta-comparisons:

  • SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.

  • DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":Selection DataVisualization.ch

Here's a list of similar projects (some have been already mentioned here):

Pure JavaScript Libraries

  • vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.

  • Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.

  • The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.

  • D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.

  • Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.

  • sigma.js Lightweight but powerful library for drawing graphs

  • jsPlumb jQuery plug-in for creating interactive connected graphs

  • Springy - a force-directed graph layout algorithm

  • Processing.js Javascript port of the Processing library by John Resig

  • JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.

  • RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.

  • JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package

  • mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.

Commercial libraries

Abandoned libraries

  • Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)

  • Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.

  • arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.

  • jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.

  • jsdot Client side graph drawing application. Abandoned in 2011.

  • Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.

  • Moo Wheel Interactive JS representation for connections and relations (2008)

  • JSViz 2007-era graph visualization script

  • dagre Graph layout for JavaScript

Non-Javascript Libraries

Counting the number of True Booleans in a Python List

After reading all the answers and comments on this question, I thought to do a small experiment.

I generated 50,000 random booleans and called sum and count on them.

Here are my results:

>>> a = [bool(random.getrandbits(1)) for x in range(50000)]
>>> len(a)
50000
>>> a.count(False)
24884
>>> a.count(True)
25116
>>> def count_it(a):
...   curr = time.time()
...   counting = a.count(True)
...   print("Count it = " + str(time.time() - curr))
...   return counting
... 
>>> def sum_it(a):
...   curr = time.time()
...   counting = sum(a)
...   print("Sum it = " + str(time.time() - curr))
...   return counting
... 
>>> count_it(a)
Count it = 0.00121307373046875
25015
>>> sum_it(a)
Sum it = 0.004102230072021484
25015

Just to be sure, I repeated it several more times:

>>> count_it(a)
Count it = 0.0013530254364013672
25015
>>> count_it(a)
Count it = 0.0014507770538330078
25015
>>> count_it(a)
Count it = 0.0013344287872314453
25015
>>> sum_it(a)
Sum it = 0.003480195999145508
25015
>>> sum_it(a)
Sum it = 0.0035257339477539062
25015
>>> sum_it(a)
Sum it = 0.003350496292114258
25015
>>> sum_it(a)
Sum it = 0.003744363784790039
25015

And as you can see, count is 3 times faster than sum. So I would suggest to use count as I did in count_it.

Python version: 3.6.7
CPU cores: 4
RAM size: 16 GB
OS: Ubuntu 18.04.1 LTS

Correct way to work with vector of arrays

Use:

vector<vector<float>> vecArray; //both dimensions are open!

What version of MongoDB is installed on Ubuntu

In the terminal just enter the traditional command:

mongod --version

SQL Server : SUM() of multiple rows including where clauses

Use a common table expression to add grand total row, top 100 is required for order by to work.

With Detail as 
(
    SELECT  top 100 propertyId, SUM(Amount) as TOTAL_COSTS
    FROM MyTable
    WHERE EndDate IS NULL
    GROUP BY propertyId
    ORDER BY TOTAL_COSTS desc
)

Select * from Detail
Union all
Select ' Total ', sum(TOTAL_COSTS) from Detail

Prime numbers between 1 to 100 in C Programming Language

#include <stdio.h>

int main () {

   int i, j;

   for(i = 2; i<100; i++) {

      for(j = 2; j <= (i/j); j++) 
      if(!(i%j)) break; // if factor found, not prime
      if(j > (i/j)) printf("%d is prime", i);
   }

   return 0;
}

How to sum array of numbers in Ruby?

Try this:

array.inject(0){|sum,x| sum + x }

See Ruby's Enumerable Documentation

(note: the 0 base case is needed so that 0 will be returned on an empty array instead of nil)

Validating URL in Java

Thanks. Opening the URL connection by passing the Proxy as suggested by NickDK works fine.

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

System properties however doesn't work as I had mentioned earlier.

Thanks again.

Regards, Keya

Get epoch for a specific date using Javascript

new Date("2016-3-17").valueOf() 

will return a long epoch

Making view resize to its parent when added with addSubview

You can always do it in your UIViews - (void)didMoveToSuperview method. It will get called when added or removed from your parent (nil when removed). At that point in time just set your size to that of your parent. From that point on the autoresize mask should work properly.

Search for one value in any column of any table inside a database

I expanded the code, because it's not told me the 'record number', and I must to refind it.

CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

-- Copyright @ 2012 Gyula Kulifai. All rights reserved.
-- Extended By: Gyula Kulifai
-- Purpose: To put key values, to exactly determine the position of search
-- Resources: Anatoly Lubarsky
-- Date extension: 19th October 2012 12:24 GMT
-- Tested on: SQL Server 10.0.5500 (SQL Server 2008 SP3)

CREATE TABLE #Results (TableName nvarchar(370), KeyValues nvarchar(3630), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    ,@TableShortName nvarchar(256)
    ,@TableKeys nvarchar(512)
    ,@SQL nvarchar(3830)

SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''

    -- Scan Tables
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
    Set @TableShortName=PARSENAME(@TableName, 1)
    -- print @TableName + ';' + @TableShortName +'!' -- *** DEBUG LINE ***

        -- LOOK Key Fields, Set Key Columns
        SET @TableKeys=''
        SELECT @TableKeys = @TableKeys + '''' + QUOTENAME([name]) + ': '' + CONVERT(nvarchar(250),' + [name] + ') + ''' + ',' + ''' + '
         FROM syscolumns 
         WHERE [id] IN (
            SELECT [id] 
             FROM sysobjects 
             WHERE [name] = @TableShortName)
           AND colid IN (
            SELECT SIK.colid 
             FROM sysindexkeys SIK 
             JOIN sysobjects SO ON 
                SIK.[id] = SO.[id]  
             WHERE 
                SIK.indid = 1
                AND SO.[name] = @TableShortName)
        If @TableKeys<>''
            SET @TableKeys=SUBSTRING(@TableKeys,1,Len(@TableKeys)-8)
        -- Print @TableName + ';' + @TableKeys + '!' -- *** DEBUG LINE ***

    -- Search in Columns
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        ) -- Set ColumnName

        IF @ColumnName IS NOT NULL
        BEGIN
            SET @SQL='
                SELECT 
                    ''' + @TableName + '''
                    ,'+@TableKeys+'
                    ,''' + @ColumnName + '''
                ,LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            --Print @SQL -- *** DEBUG LINE ***
            INSERT INTO #Results
                Exec (@SQL)
        END -- IF ColumnName
    END -- While Table and Column
END --While Table

SELECT TableName, KeyValues, ColumnName, ColumnValue FROM #Results
END

delete map[key] in go?

Copied from Go 1 release notes

In the old language, to delete the entry with key k from the map represented by m, one wrote the statement,

m[k] = value, false

This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.

In Go 1, that syntax has gone; instead there is a new built-in function, delete. The call

delete(m, k)

will delete the map entry retrieved by the expression m[k]. There is no return value. Deleting a non-existent entry is a no-op.

Updating: Running go fix will convert expressions of the form m[k] = value, false into delete(m, k) when it is clear that the ignored value can be safely discarded from the program and false refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.

How to change color in markdown cells ipython/jupyter notebook?

Similarly to Jakob's answer, you can use HTML tags. Just a note that the color attribute of font (<font color=...>) is deprecated in HTML5. The following syntax would be HTML5-compliant:

This <span style="color:red">word</span> is not black.

Same caution that Jakob made probably still applies:

Be aware that this will not survive a conversion of the notebook to latex.

'Incomplete final line' warning when trying to read a .csv file into R

I have solved this problem with changing encoding in read.table argument from fileEncoding = "UTF-16" to fileEncoding = "UTF-8".

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

How to create a data file for gnuplot?

I was having the exact same issue. The problem that I was having is that I hadn't saved the .plt file that I was typing into yet. The fix: I saved the .plt file in the same directory as the data that I was trying to plot and suddenly it worked! If they are in the same directory, you don't even need to specify a path, you can just put in the file name.

Below is exactly what was happening to me, and how I fixed it. The first line shows the problem we were both having. I saved in the second line, and the third line worked!

gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
         warning: Skipping unreadable file c:/Documents and Settings/User/Desktop/data.dat
         No data in plot

gnuplot> save 'c:/Documents and Settings/User/Desktop/myfile.plt'

gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'

AppCompat v7 r21 returning error in values.xml?

I vote whoever can solve like me. I had this same problem as u , I spent many hours to get correct . Please test .

Upgrade entire SDK , the update 21.0.2 build also has updates from Google Services play . Upgrade everything. In your workspace delete folders ( android -support- v7 - AppCompat ) and ( google -play - services_lib )

Re-import these projects into the IDE and select to copy them to your workspace again.

The project ( google -play - services_lib ) to perform the action of Refresh and Build

**** ***** Problem The project ( android -support- v7 - AppCompat ) mark the 5.0 API then Refresh and Build .

In his project , in properties , android , import libraries ( android -support- v7 - AppCompat ) and ( google -play - services_lib ) then Refresh and Build .

jQuery - Add active class and remove active from other element on click

You can remove class active from all .tab and use $(this) to target current clicked .tab:

$(document).ready(function() {
    $(".tab").click(function () {
        $(".tab").removeClass("active");
        $(this).addClass("active");     
    });
});

Your code won't work because after removing class active from all .tab, you also add class active to all .tab again. So you need to use $(this) instead of $('.tab') to add the class active only to the clicked .tab anchor

Updated Fiddle

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

Firebase FCM notifications click_action payload

This falls into workaround category, containing some extra information too:

Since the notifications are handled differently depending on the state of the app (foreground/background/not launched) I've seen the best way to implement a helper class where the selected activity is launched based on the custom data sent in the notification message.

  • when the app is on foreground use the helper class in onMessageReceived
  • when the app is on background use the helper class for handling the intent in main activity's onNewIntent (check for specific custom data)
  • when the app is not running use the helper class for handling the intent in main activity's onCreate (call getIntent for the intent).

This way you do not need the click_action or intent filter specific to it. Also you write the code just once and can reasonably easily start any activity.

So the minimum custom data would look something like this:

Key: run_activity
Value: com.mypackage.myactivity

And the code for handling it:

if (intent.hasExtra("run_activity")) {
    handleFirebaseNotificationIntent(intent);
}


private void handleFirebaseNotificationIntent(Intent intent){
    String className = intent.getStringExtra("run_activity");
    startSelectedActivity(className, intent.getExtras());
}

private void startSelectedActivity(String className, Bundle extras){
    Class cls;
    try {
        cls = Class.forName(className);
    }catch(ClassNotFoundException e){
        ...
    }
    Intent i = new Intent(context, cls);

    if (i != null) {
        i.putExtras(extras);
        this.startActivity(i);
    } 
}

That is the code for the last two cases, startSelectedActivity would be called also from onMessageReceived (first case).

The limitation is that all the data in the intent extras are strings, so you may need to handle that somehow in the activity itself. Also, this is simplified, you probably don't what to change the Activity/View on an app that is on the foreground without warning your user.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

Regular expression to match a line that doesn't contain a word

If you're just using it for grep, you can use grep -v hede to get all lines which do not contain hede.

ETA Oh, rereading the question, grep -v is probably what you meant by "tools options".

How to get data from observable in angular2

Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http it returns observable instead of promise, like you did

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()

.map() is used to convert the observable (received from http request)to any form like .json(), .text() as stated in Angular's official website,

.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

Why is it bad style to `rescue Exception => e` in Ruby?

That's a specific case of the rule that you shouldn't catch any exception you don't know how to handle. If you don't know how to handle it, it's always better to let some other part of the system catch and handle it.

PHP upload image

The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.

You may wish to review a simple example at:

http://www.w3schools.com/php/php_file_upload.asp

Why can't variables be declared in a switch statement?

The entire section of the switch is a single declaration context. You can't declare a variable in a case statement like that. Try this instead:

switch (val)  
{  
case VAL:
{
  // This will work
  int newVal = 42;
  break;
}
case ANOTHER_VAL:  
  ...
  break;
}

How do you set up use HttpOnly cookies in PHP

Explanation here from Ilia... 5.2 only though

httpOnly cookie flag support in PHP 5.2

As stated in that article, you can set the header yourself in previous versions of PHP

header("Set-Cookie: hidden=value; httpOnly");

Equivalent of jQuery .hide() to set visibility: hidden

There isn't one built in but you could write your own quite easily:

(function($) {
    $.fn.invisible = function() {
        return this.each(function() {
            $(this).css("visibility", "hidden");
        });
    };
    $.fn.visible = function() {
        return this.each(function() {
            $(this).css("visibility", "visible");
        });
    };
}(jQuery));

You can then call this like so:

$("#someElem").invisible();
$("#someOther").visible();

Here's a working example.

Querying DynamoDB by date

Given your current table structure this is not currently possible in DynamoDB. The huge challenge is to understand that the Hash key of the table (partition) should be treated as creating separate tables. In some ways this is really powerful (think of partition keys as creating a new table for each user or customer, etc...).

Queries can only be done in a single partition. That's really the end of the story. This means if you want to query by date (you'll want to use msec since epoch), then all the items you want to retrieve in a single query must have the same Hash (partition key).

I should qualify this. You absolutely can scan by the criterion you are looking for, that's no problem, but that means you will be looking at every single row in your table, and then checking if that row has a date that matches your parameters. This is really expensive, especially if you are in the business of storing events by date in the first place (i.e. you have a lot of rows.)

You may be tempted to put all the data in a single partition to solve the problem, and you absolutely can, however your throughput will be painfully low, given that each partition only receives a fraction of the total set amount.

The best thing to do is determine more useful partitions to create to save the data:

  • Do you really need to look at all the rows, or is it only the rows by a specific user?

  • Would it be okay to first narrow down the list by Month, and do multiple queries (one for each month)? Or by Year?

  • If you are doing time series analysis there are a couple of options, change the partition key to something computated on PUT to make the query easier, or use another aws product like kinesis which lends itself to append-only logging.

Fast Bitmap Blur For Android SDK

Nicolas POMEPUY advice. I think this link will be helpful: Blur effect for Android design

Sample project at github

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private static Bitmap fastblur16(Bitmap source, int radius, Context ctx) {    
    Bitmap bitmap = source.copy(source.getConfig(), true);    
    RenderScript rs = RenderScript.create(ctx);
    Allocation input = Allocation.createFromBitmap(rs, source, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
    Allocation output = Allocation.createTyped(rs, input.getType());
    ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    script.setRadius(radius);
    script.setInput(input);
    script.forEach(output);
    output.copyTo(bitmap);
    return bitmap;
}

react-native :app:installDebug FAILED

open avd manager click on the arrow next to the pencil icon and wipe data works for me...

Rollback to last git commit

If you want to just uncommit the last commit use this:

git reset HEAD~

work like charm for me.

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Redirect on select option in select box

I'd strongly suggest moving away from inline JavaScript, to something like the following:

function redirect(goto){
    var conf = confirm("Are you sure you want to go elswhere?");
    if (conf && goto != '') {
        window.location = goto;
    }
}

var selectEl = document.getElementById('redirectSelect');

selectEl.onchange = function(){
    var goto = this.value;
    redirect(goto);

};

JS Fiddle demo (404 linkrot victim).
JS Fiddle demo via Wayback Machine.
Forked JS Fiddle for current users.

In the mark-up in the JS Fiddle the first option has no value assigned, so clicking it shouldn't trigger the function to do anything, and since it's the default value clicking the select and then selecting that first default option won't trigger the change event anyway.

Update:
The latest example's (2017-08-09) redirect URLs required swapping out due to errors regarding mixed content between JS Fiddle and both domains, as well as both domains requiring 'sameorigin' for framed content. - Albert

Including .cpp files

There are many reasons to discourage including a .cpp file, but it isn't strictly disallowed. Your example should compile fine.

The problem is probably that you're compiling both main.cpp and foop.cpp, which means two copies of foop.cpp are being linked together. The linker is complaining about the duplication.

How do I use HTML as the view engine in Express?

The answers at the other link will work, but to serve out HTML, there is no need to use a view engine at all, unless you want to set up funky routing. Instead, just use the static middleware:

app.use(express.static(__dirname + '/public'));

Objective-C for Windows

I have mixed feelings about the Cocotron project. I'm glad they are releasing source code and sharing but I don't feel that they are doing things the easiest way.

Examples.
Apple has released the source code to the objective-c runtime, which includes properties and garbage collection. The Cocotron project however has their own implementation of the objective-c runtime. Why bother to duplicate the effort? There is even a Visual Studio Project file that can be used to build an objc.dll file. Or if you're really lazy, you can just copy the DLL file from an installation of Safari on Windows.

They also did not bother to leverage CoreFoundation, which is also open sourced by Apple. I posted a question about this but did not receive an answer.

I think the current best solution is to take source code from multiple sources (Apple, CocoTron, GnuStep) and merge it together to what you need. You'll have to read a lot of source but it will be worth the end result.

Kubernetes service external ip pending

If you are not using GCE or EKS (you used kubeadm) you can add an externalIPs spec to your service YAML. You can use the IP associated with your node's primary interface such as eth0. You can then access the service externally, using the external IP of the node.

...
spec:
  type: LoadBalancer
  externalIPs:
  - 192.168.0.10

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Found the flex magic.

Here's an example of how to do a fixed header and a scrollable content. Code:

<!DOCTYPE html>
<html style="height: 100%">
  <head>
    <meta charset=utf-8 />
    <title>Holy Grail</title>
    <!-- Reset browser defaults -->
    <link rel="stylesheet" href="reset.css">
  </head>
  <body style="display: flex; height: 100%; flex-direction: column">
    <div>HEADER<br/>------------
    </div>
    <div style="flex: 1; overflow: auto">
        CONTENT - START<br/>
        <script>
        for (var i=0 ; i<1000 ; ++i) {
          document.write(" Very long content!");
        }
        </script>
        <br/>CONTENT - END
    </div>
  </body>
</html>

* The advantage of the flex solution is that the content is independent of other parts of the layout. For example, the content doesn't need to know height of the header.

For a full Holy Grail implementation (header, footer, nav, side, and content), using flex display, go to here.

Ruby convert Object to Hash

To do this without Rails, a clean way is to store attributes on a constant.

class Gift
  ATTRIBUTES = [:name, :price]
  attr_accessor(*ATTRIBUTES)
end

And then, to convert an instance of Gift to a Hash, you can:

class Gift
  ...
  def to_h
    ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
      memo[attribute_name] = send(attribute_name)
    end
  end
end

This is a good way to do this because it will only include what you define on attr_accessor, and not every instance variable.

class Gift
  ATTRIBUTES = [:name, :price]
  attr_accessor(*ATTRIBUTES)

  def create_random_instance_variable
    @xyz = 123
  end

  def to_h
    ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
      memo[attribute_name] = send(attribute_name)
    end
  end
end

g = Gift.new
g.name = "Foo"
g.price = 5.25
g.to_h
#=> {:name=>"Foo", :price=>5.25}

g.create_random_instance_variable
g.to_h
#=> {:name=>"Foo", :price=>5.25}

Query to get all rows from previous month

SELECT *  FROM table  
WHERE  YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

select *
from user
left join edge
on user.userid = edge.tailuser
and edge.headuser = 5043

Django Server Error: port is already in use

Type 'fg' as command after that ctl-c.
Command:
Fg will show which is running on background. After that ctl-c will stop it.

fg
ctl-c

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

Your else statement should look like this (note the ^):

{{^avatar}}
 ...
{{/avatar}}

In mustache this is called 'Inverted sections'.

How to empty a Heroku database

If you are logged in from the console, this will do the job in the latest heroku toolbelt,

heroku pg:reset --confirm database-name

INSERT INTO @TABLE EXEC @query with SQL Server 2000

The documentation is misleading.
I have the following code running in production

DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
   SET @sql = 'SELECT UserID FROM UserTable'
*/

INSERT INTO @table
EXEC(@sql)

SELECT * FROM @table

Observable Finally on Subscribe

The current "pipable" variant of this operator is called finalize() (since RxJS 6). The older and now deprecated "patch" operator was called finally() (until RxJS 5.5).

I think finalize() operator is actually correct. You say:

do that logic only when I subscribe, and after the stream has ended

which is not a problem I think. You can have a single source and use finalize() before subscribing to it if you want. This way you're not required to always use finalize():

let source = new Observable(observer => {
  observer.next(1);
  observer.error('error message');
  observer.next(3);
  observer.complete();
}).pipe(
  publish(),
);

source.pipe(
  finalize(() => console.log('Finally callback')),
).subscribe(
  value => console.log('#1 Next:', value),
  error => console.log('#1 Error:', error),
  () => console.log('#1 Complete')
);

source.subscribe(
  value => console.log('#2 Next:', value),
  error => console.log('#2 Error:', error),
  () => console.log('#2 Complete')
);

source.connect();

This prints to console:

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message

Jan 2019: Updated for RxJS 6

SQL, How to Concatenate results?

In mysql you'd use the following function:

SELECT GROUP_CONCAT(ModuleValue, ",") FROM Table_X WHERE ModuleID=@ModuleID

I am not sure which dialect you are using.

Two onClick actions one button

Additional attributes (in this case, the second onClick) will be ignored. So, instead of onclick calling both fbLikeDump(); and WriteCookie();, it will only call fbLikeDump();. To fix, simply define a single onclick attribute and call both functions within it:

<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />

MySQL high CPU usage

First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.

Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.

Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.

Some other things you can check would be to run the following query while the CPU load is high:

SHOW PROCESSLIST;

This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).

You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.

You'll also probably want to give the following a read over as they contain some good information.

It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.

How to loop through each and every row, column and cells in a GridView and get its value

The easiest would be using a foreach:

foreach(GridViewRow row in GridView2.Rows)
{
    // here you'll get all rows with RowType=DataRow
    // others like Header are omitted in a foreach
}

Edit: According to your edits, you are accessing the column incorrectly, you should start with 0:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

Key hash for Android-Facebook app

As answered on a similar issue i found this to be working for me:

  • Copy the apkname.apk file you want to know the hash of to the 'Java\jdk1.7.0_79\bin' folder
  • Run this command keytool -list -printcert -jarfile apkname.apk
  • Copy the SHA1 value and convert it using this site
  • Use the converted Keyhash value (ex. zaHqo1xcaPv6CmvlWnJk3SaNRIQ=)

Extracting the last n characters from a string in R

I use substr too, but in a different way. I want to extract the last 6 characters of "Give me your food." Here are the steps:

(1) Split the characters

splits <- strsplit("Give me your food.", split = "")

(2) Extract the last 6 characters

tail(splits[[1]], n=6)

Output:

[1] " " "f" "o" "o" "d" "."

Each of the character can be accessed by splits[[1]][x], where x is 1 to 6.

How to pass in parameters when use resource service?

I suggest you to use provider. Provide is good when you want to configure it first before to use (against Service/Factory)

Something like:

.provider('Magazines', function() {

    this.url = '/';
    this.urlArray = '/';
    this.organId = 'Default';

    this.$get = function() {
        var url = this.url;
        var urlArray = this.urlArray;
        var organId = this.organId;

        return {
            invoke: function() {
                return ......
            }
        }
    };

    this.setUrl  = function(url) {
        this.url = url;
    };

   this.setUrlArray  = function(urlArray) {
        this.urlArray = urlArray;
    };

    this.setOrganId  = function(organId) {
        this.organId = organId;
    };
});

.config(function(MagazinesProvider){
    MagazinesProvider.setUrl('...');
    MagazinesProvider.setUrlArray('...');
    MagazinesProvider.setOrganId('...');
});

And now controller:

function MyCtrl($scope, Magazines) {        

        Magazines.invoke();

       ....

}

Environment variable substitution in sed

VAR=8675309
echo "abcde:jhdfj$jhbsfiy/.hghi$jh:12345:dgve::" |\
sed 's/:[0-9]*:/:'$VAR':/1' 

where VAR contains what you want to replace the field with

How to change working directory in Jupyter Notebook?

it is similar to jason lee as he mentioned earlier:

in Jupyter notebook, you can access the current working directory by

pwd()

or by import OS from library and running os.getcwd()

i.e. for example

In[ ]: import os

       os.getcwd( )

out[ ]: :c\\users\\admin\\Desktop\\python    

        (#This is my working directory)

Changing Working Directory

For changing the Working Directory (much more similar to current W.d just you need to change from os.getcwd() to os.chdir('desired location')

In[ ]: import os

       os.chdir('c:user/chethan/Desktop')        (#This is where i want to update my w.d, 
                                                  like that choose your desired location)
out[  ]: 'c:user\\chethan\\Desktop'

Get gateway ip address in android

Try the following:

ConnectivityManager connectivityManager = ...;
LinkProperties linkProperties = connectivityManager.getLinProperties(connectivityManager.GetActiveNetwork());
for (RouteInfo routeInfo: linkProperties.getRoutes()) {
    if (routeInfo.IsDefaultRoute() && routeInfo.hasGateway()) {
        return routeInfo.getGateway();
    }
}

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

If you are connecting from Windows Machine A to Windows Machine B (server with SQL Server installed) and are getting this error, you need to do the following:

On Machine B:

  1. Turn on the Windows service called "SQL Server Browser" and start the service Windows Services
  2. In Windows Firewall:
    • enable incoming port UDP 1434 (in case SQL Server Management Studio on machine A is connecting or a program on machine A is connecting)
    • enable incoming port TCP 1433 (in case there is a telnet connection) Windows firewall
  3. In SQL Server Configuration Manager:
    • enable TCP/IP protocol for port 1433 Sql Server Configuration Manager

Make a dictionary with duplicate keys in Python

You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:

class Dictlist(dict):
    def __setitem__(self, key, value):
        try:
            self[key]
        except KeyError:
            super(Dictlist, self).__setitem__(key, [])
        self[key].append(value)

Output example:

>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}

Could someone explain this for me - for (int i = 0; i < 8; i++)

for (int i = 0; i < 8; i++)

It's a for loop, which will execute the next statement a number of times, depending on the conditions inside the parenthesis.

for (int i = 0; i < 8; i++)

Start by setting i = 0

for (int i = 0; i < 8; i++)

Continue looping while i < 8.

for (int i = 0; i < 8; i++)

Every time you've been around the loop, increase i by 1.

For example;

for (int i = 0; i < 8; i++)
    do(i);

will call do(0), do(1), ... do(7) in order, and stop when i reaches 8 (ie i < 8 is false)

Add views below toolbar in CoordinatorLayout

To use collapsing top ToolBar or using ScrollFlags of your own choice we can do this way:From Material Design get rid of FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleGravity="top"
            app:layout_scrollFlags="scroll|enterAlways">


        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/ic_back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_arrow_back" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="back"
                android:textSize="16sp"
                android:textStyle="bold" />

        </androidx.appcompat.widget.Toolbar>


        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/post_details_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="5dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

How to unstage large number of files without deleting the content

2019 update

As pointed out by others in related questions (see here, here, here, here, here, here, and here), you can now unstage a file with git restore --staged <file>.

To unstage all the files in your project, run the following from the root of the repository (the command is recursive):

git restore --staged .

If you only want to unstage the files in a directory, navigate to it before running the above or run:

git restore --staged <directory-path>

Notes

  • git restore was introduced in July 2019 and released in version 2.23.
    With the --staged flag, it restores the content of the working tree from HEAD (so it does the opposite of git add and does not delete any change).

  • This is a new command, but the behaviour of the old commands remains unchanged. So the older answers with git reset or git reset HEAD are still perfectly valid.

  • When running git status with staged uncommitted file(s), this is now what Git suggests to use to unstage file(s) (instead of git reset HEAD <file> as it used to prior to v2.23).

What does the PHP error message "Notice: Use of undefined constant" mean?

<?php 
  ${test}="test information";
  echo $test;
?>

Notice: Use of undefined constant test - assumed 'test' in D:\xampp\htdocs\sp\test\envoirnmentVariables.php on line 3 test information

How do I calculate the MD5 checksum of a file in Python?

In Python 3.8+ you can do

import hashlib

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

On Python 3.7 and below:

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    chunk = f.read(8192)
    while chunk:
        file_hash.update(chunk)
        chunk = f.read(8192)

print(file_hash.hexdigest())

This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read() to use less memory.


Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippets). It's cryptographically secure and faster than MD5.

dropping infinite values from dataframes in pandas?

With option context, this is possible without permanently setting use_inf_as_na. For example:

with pd.option_context('mode.use_inf_as_na', True):
    df = df.dropna(subset=['col1', 'col2'], how='all')

Of course it can be set to treat inf as NaN permanently with

pd.set_option('use_inf_as_na', True)

For older versions, replace use_inf_as_na with use_inf_as_null.

How do I stop a program when an exception is raised in Python?

import sys

try:
  print("stuff")
except:
  sys.exit(1) # exiing with a non zero value is better for returning from an error

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

Convert a matrix to a 1 dimensional array

From ?matrix: "A matrix is the special case of a two-dimensional 'array'." You can simply change the dimensions of the matrix/array.

Elts_int <- as.matrix(tmp_int)  # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)

Android device does not show up in adb list

On Android 7.1 Nougat (in my case, a Moto G), manually re-enabling USB debugging on Developer Options did the trick:

Settings > Developer Options > USB debugging

enter image description here

PS C:\> adb devices
List of devices attached
myDeviceNumber      device

Access elements of parent window from iframe

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

What is the default initialization of an array in Java?

Java says that the default length of a JAVA array at the time of initialization will be 10.

private static final int DEFAULT_CAPACITY = 10;

But the size() method returns the number of inserted elements in the array, and since at the time of initialization, if you have not inserted any element in the array, it will return zero.

private int size;

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

public void add(int index, E element) {
    rangeCheckForAdd(index);
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,size - index);
    elementData[index] = element;
    size++;
}

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

Graphical user interface Tutorial in C

My favourite UI tutorials all come from zetcode.com:

These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.

Property 'value' does not exist on type EventTarget in TypeScript

The way I do it is the following (better than type assertion imho):

onFieldUpdate(event: { target: HTMLInputElement }) {
  this.$emit('onFieldUpdate', event.target.value);
}

This assumes you are only interested in the target property, which is the most common case. If you need to access the other properties of event, a more comprehensive solution involves using the & type intersection operator:

event: Event & { target: HTMLInputElement }

This is a Vue.js version but the concept applies to all frameworks. Obviously you can go more specific and instead of using a general HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.

jQuery scrollTop not working in Chrome but working in Firefox

maybe you mean top: 0

$('a#gotop').click(function() {
  $("html").animate({ top: 0 }, "slow", function() { 
                                           alert('Animation complete.'); });
  //return false;
});

from animate docs

.animate( properties, [ duration ], [ easing ], [ callback ] )
properties A map of CSS properties that the animation will move toward.
...

or $(window).scrollTop() ?

$('a#gotop').click(function() {
  $("html").animate({ top: $(window).scrollTop() }, "slow", function() { 
                                                              alert('Animation complete.'); });
  //return false;
});

Linq Select Group By

var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();

I have converted it to int because my Price field was int and Average method return double .I hope this will help

Usage of sys.stdout.flush() method

As per my understanding, When ever we execute print statements output will be written to buffer. And we will see the output on screen when buffer get flushed(cleared). By default buffer will be flushed when program exits. BUT WE CAN ALSO FLUSH THE BUFFER MANUALLY by using "sys.stdout.flush()" statement in the program. In the below code buffer will be flushed when value of i reaches 5.

You can understand by executing the below code.

chiru@online:~$ cat flush.py
import time
import sys

for i in range(10):
    print i
    if i == 5:
        print "Flushing buffer"
        sys.stdout.flush()
    time.sleep(1)

for i in range(10):
    print i,
    if i == 5:
        print "Flushing buffer"
        sys.stdout.flush()
chiru@online:~$ python flush.py 
0 1 2 3 4 5 Flushing buffer
6 7 8 9 0 1 2 3 4 5 Flushing buffer
6 7 8 9

Oracle SQL Developer and PostgreSQL

I managed to connect to postgres with SQL Developer. I downloaded postgres jdbc driver and saved it in a folder. I run SQL Developer -> Tools -> Preferences -> Search -> JDBC I defined postgres jdbc driver for the Database and Data Modeler (optional).

This is the trick. When creating new connection define Hostname like localhost/crm? where crm is the database name. Test the connection, works fine.

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

Cancel split window in Vim

Press Control+w, then hit q to close each window at a time.

Update: Also consider eckes answer which may be more useful to you, involving :on (read below) if you don't want to do it one window at a time.

Getting JSONObject from JSONArray

{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]

The get companyid, username, date;

jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date

How to add image that is on my computer to a site in css or html?

If you just want to see the image on your local browser, this can be done if you have a server running locally. You just need to reference the local server via http (not file://), like:

http://localhost/my_picture.jpg

if picture.jpg is in your local server's webroot folder. You can do this for any site if you open your browser's developer tools and change the img element's src attribute to the local server's URL for the image. If you have access to the HTML of your site, then change it there. But obviously if someone not on your local computer/server accesses the site, they will get a broken image unless they happen to be running a local server as well and have an image with the same filename, which would be weird.

"Application tried to present modally an active controller"?

I have the same problem. I try to present view controller just after dismissing.

[self dismissModalViewControllerAnimated:YES];

When I try to do it without animation it works perfectly so the problem is that controller is still alive. I think that the best solution is to use dismissViewControllerAnimated:completion: for iOS5

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

Failed to serialize the response in Web API with Json

Add the below line

this.Configuration.ProxyCreationEnabled = false;

Two way to use ProxyCreationEnabled as false.

  1. Add it inside of DBContext Constructor

    public ProductEntities() : base("name=ProductEntities")
    {
        this.Configuration.ProxyCreationEnabled = false;
    }
    

OR

  1. Add the line inside of Get method

    public IEnumerable<Brand_Details> Get()
    {
        using (ProductEntities obj = new ProductEntities())
        {
            this.Configuration.ProxyCreationEnabled = false;
            return obj.Brand_Details.ToList();
        }
    }
    

Redirect HTTP to HTTPS on default virtual host without ServerName

This is the complete way to omit unneeded redirects, too ;)

These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.

RewriteEngine on
RewriteCond %{HTTPS} off [OR] 
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

Eplanations:

RewriteEngine on

==> enable the engine at all

RewriteCond %{HTTPS} off [OR]

==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)

RewriteCond %{HTTP:X-Forwarded-Proto} !https

==> match on forwarded connections (proxy, loadbalancer, etc.) without https

RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.

How to remove item from list in C#?

List<T> has two methods you can use.

RemoveAt(int index) can be used if you know the index of the item. For example:

resultlist.RemoveAt(1);

Or you can use Remove(T item):

var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);

When you are not sure the item really exists you can use SingleOrDefault. SingleOrDefault will return null if there is no item (Single will throw an exception when it can't find the item). Both will throw when there is a duplicate value (two items with the same id).

var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
    resultList.Remove(itemToRemove);

What is the difference between smoke testing and sanity testing?

Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.

Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.

In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.

onchange event for html.dropdownlist

If you don't want jquery then you can do it with javascript :-

@Html.DropDownList("Sortby", new SelectListItem[] 
{ 
     new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, 
     new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
     new { @onchange="callChangefunc(this.value)" 
});

<script>
    function callChangefunc(val){
        window.location.href = "/Controller/ActionMethod?value=" + val;
    }
</script>

Is it possible to run an .exe or .bat file on 'onclick' in HTML

Here's what I did. I wanted a HTML page setup on our network so I wouldn't have to navigate to various folders to install or upgrade our apps. So what I did was setup a .bat file on our "shared" drive that everyone has access to, in that .bat file I had this code:

start /d "\\server\Software\" setup.exe

The HTML code was:

<input type="button" value="Launch Installer" onclick="window.open('file:///S:Test/Test.bat')" />

(make sure your slashes are correct, I had them the other way and it didn't work)

I preferred to launch the EXE directly but that wasn't possible, but the .bat file allowed me around that. Wish it worked in FF or Chrome, but only IE.

TypeError: $.browser is undefined

$().live(function(){}); and jQuery.browser is undefined in jquery 1.9.0 - $.browser was deprecated in jquery update

sounds like you are using a different version of jquery 1.9 in godaddy so either change your code or include the migrate plugin http://code.jquery.com/jquery-migrate-1.0.0.js

Make footer stick to bottom of page correctly

the easiest hack is to set a min-height to your page container at 400px assuming your footer come at the end. you dont even have to put css for the footer or just a width:100% assuming your footer is direct child of your <body>

Hide axis and gridlines Highcharts

Just add

xAxis: {
   ...  
   lineWidth: 0,
   minorGridLineWidth: 0,
   lineColor: 'transparent',
   ...          
   labels: {
       enabled: false
   },
   minorTickLength: 0,
   tickLength: 0
}

to the xAxis definition.

Since Version 4.1.9 you can simply use the axis attribute visible:

xAxis: {
    visible: false,
}

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

How to sum a list of integers with java streams?

You can use collect method to add list of integers.

List<Integer> list = Arrays.asList(2, 4, 5, 6);
int sum = list.stream().collect(Collectors.summingInt(Integer::intValue));

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

What does the C++ standard state the size of int, long type to be?

If you need fixed size types, use types like uint32_t (unsigned integer 32 bits) defined in stdint.h. They are specified in C99.

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

I tried some of the script here, but they didn't work for me, as I have my tables in schemas. So I put together the following. Note that this script takes a list of schemas, and drops then in sequence. You need to make sure that you have a complete ordering in your schemas. If there are any circular dependencies, then it will fail.

PRINT 'Dropping whole database'
GO

------------------------------------------
-- Drop constraints
------------------------------------------
DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE ['+tc2.CONSTRAINT_SCHEMA+'].[' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
Exec (@Sql)
FETCH NEXT FROM @Cursor INTO @Sql
END

CLOSE @Cursor DEALLOCATE @Cursor
GO


------------------------------------------
-- Drop views
------------------------------------------

DECLARE @sql VARCHAR(MAX) = ''
        , @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;

SELECT @sql = @sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(v.name) +';' + @crlf
FROM   sys.views v

PRINT @sql;
EXEC(@sql);
GO
------------------------------------------
-- Drop procs
------------------------------------------
PRINT 'Dropping all procs ...'
GO

DECLARE @sql VARCHAR(MAX) = ''
        , @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;

SELECT @sql = @sql + 'DROP PROC ' + QUOTENAME(SCHEMA_NAME(p.schema_id)) + '.' + QUOTENAME(p.name) +';' + @crlf
FROM   [sys].[procedures] p

PRINT @sql;
EXEC(@sql);
GO

------------------------------------------
-- Drop tables
------------------------------------------
PRINT 'Dropping all tables ...'
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO

------------------------------------------
-- Drop sequences
------------------------------------------

PRINT 'Dropping all sequences ...'
GO
DECLARE @DropSeqSql varchar(1024)
DECLARE DropSeqCursor CURSOR FOR
SELECT DISTINCT 'DROP SEQUENCE ' + s.SEQUENCE_SCHEMA + '.' + s.SEQUENCE_NAME
    FROM INFORMATION_SCHEMA.SEQUENCES s

OPEN DropSeqCursor

FETCH NEXT FROM DropSeqCursor INTO @DropSeqSql

WHILE ( @@FETCH_STATUS <> -1 )
BEGIN
    PRINT @DropSeqSql
    EXECUTE( @DropSeqSql )
    FETCH NEXT FROM DropSeqCursor INTO @DropSeqSql
END

CLOSE DropSeqCursor
DEALLOCATE DropSeqCursor
GO

------------------------------------------
-- Drop Schemas
------------------------------------------


DECLARE @schemas as varchar(1000) = 'StaticData,Ird,DataImport,Collateral,Report,Cds,CommonTrade,MarketData,TypeCode'
DECLARE @schemasXml as xml = cast(('<schema>'+replace(@schemas,',' ,'</schema><schema>')+'</schema>') as xml)

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT sql = 'DROP SCHEMA ['+schemaName+']' FROM 
(SELECT CAST(T.schemaName.query('text()') as VARCHAR(200)) as schemaName FROM @schemasXml.nodes('/schema') T(schemaName)) as X
JOIN information_schema.schemata S on S.schema_name = X.schemaName

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
Exec (@Sql)
FETCH NEXT FROM @Cursor INTO @Sql
END

CLOSE @Cursor DEALLOCATE @Cursor
GO

Initializing a dictionary in python with a key value and no corresponding values

Use the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don't have a default value in mind.

empty_dict = dict.fromkeys(['apple','ball'])

this will initialize empty_dict as:

empty_dict = {'apple': None, 'ball': None}

As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:

default_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)

PostgreSQL visual interface similar to phpMyAdmin?

I would also highly recommend Adminer - http://www.adminer.org/

It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.

Function vs. Stored Procedure in SQL Server

SQL Server functions, like cursors, are meant to be used as your last weapon! They do have performance issues and therefore using a table-valued function should be avoided as much as possible. Talking about performance is talking about a table with more than 1,000,000 records hosted on a server on a middle-class hardware; otherwise you don't need to worry about the performance hit caused by the functions.

  1. Never use a function to return a result-set to an external code (like ADO.Net)
  2. Use views/stored procs combination as much as possible. you can recover from future grow-performance issues using the suggestions DTA (Database Tuning Adviser) would give you (like indexed views and statistics) --sometimes!

for further reference see: http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html

Detecting when the 'back' button is pressed on a navbar

While viewWillAppear() and viewDidDisappear() are called when the back button is tapped, they are also called at other times. See end of answer for more on that.

Using UIViewController.parent

Detecting the back button is better done when the VC is removed from it's parent (the NavigationController) with the help of willMoveToParentViewController(_:) OR didMoveToParentViewController()

If parent is nil, the view controller is being popped off the navigation stack and dismissed. If parent is not nil, it is being added to the stack and presented.

// Objective-C
-(void)willMoveToParentViewController:(UIViewController *)parent {
     [super willMoveToParentViewController:parent];
    if (!parent){
       // The back button was pressed or interactive gesture used
    }
}


// Swift
override func willMove(toParent parent: UIViewController?) {
    super.willMove(toParent: parent)
    if parent == nil {
        // The back button was pressed or interactive gesture used
    }
}

Swap out willMove for didMove and check self.parent to do work after the view controller is dismissed.

Stopping the dismiss

Do note, checking the parent doesn't allow you to "pause" the transition if you need to do some sort of async save. To do that you could implement the following. Only downside here is you lose the fancy iOS styled/animated back button. Also be careful here with the interactive swipe gesture. Use the following to handle this case.

var backButton : UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()

     // Disable the swipe to make sure you get your chance to save
     self.navigationController?.interactivePopGestureRecognizer.enabled = false

     // Replace the default back button
    self.navigationItem.setHidesBackButton(true, animated: false)
    self.backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
    self.navigationItem.leftBarButtonItem = backButton
}

// Then handle the button selection
func goBack() {
    // Here we just remove the back button, you could also disabled it or better yet show an activityIndicator
    self.navigationItem.leftBarButtonItem = nil
    someData.saveInBackground { (success, error) -> Void in
        if success {
            self.navigationController?.popViewControllerAnimated(true)
            // Don't forget to re-enable the interactive gesture
            self.navigationController?.interactivePopGestureRecognizer.enabled = true
        }
        else {
            self.navigationItem.leftBarButtonItem = self.backButton
            // Handle the error
        }
    }
}


More on view will/did appear

If you didn't get the viewWillAppear viewDidDisappear issue, Let's run through an example. Say you have three view controllers:

  1. ListVC: A table view of things
  2. DetailVC: Details about a thing
  3. SettingsVC: Some options for a thing

Lets follow the calls on the detailVC as you go from the listVC to settingsVC and back to listVC

List > Detail (push detailVC) Detail.viewDidAppear <- appear
Detail > Settings (push settingsVC) Detail.viewDidDisappear <- disappear

And as we go back...
Settings > Detail (pop settingsVC) Detail.viewDidAppear <- appear
Detail > List (pop detailVC) Detail.viewDidDisappear <- disappear

Notice that viewDidDisappear is called multiple times, not only when going back, but also when going forward. For a quick operation that may be desired, but for a more complex operation like a network call to save, it may not.

Difference between Dictionary and Hashtable

Want to add a difference:

Trying to acess a inexistent key gives runtime error in Dictionary but no problem in hashtable as it returns null instead of error.

e.g.

       //No strict type declaration
        Hashtable hash = new Hashtable();
        hash.Add(1, "One");
        hash.Add(2, "Two");
        hash.Add(3, "Three");
        hash.Add(4, "Four");
        hash.Add(5, "Five"); 
        hash.Add(6, "Six");
        hash.Add(7, "Seven");
        hash.Add(8, "Eight");
        hash.Add(9, "Nine");
        hash.Add("Ten", 10);// No error as no strict type

        for(int i=0;i<=hash.Count;i++)//=>No error for index 0
        {
            //Can be accessed through indexers
            Console.WriteLine(hash[i]);
        }
        Console.WriteLine(hash["Ten"]);//=> No error in Has Table

here no error for key 0 & also for key "ten"(note: t is small)

//Strict type declaration
        Dictionary<int,string> dictionary= new Dictionary<int, string>();
        dictionary.Add(1, "One");
        dictionary.Add(2, "Two");
        dictionary.Add(3, "Three");
        dictionary.Add(4, "Four");
        dictionary.Add(5, "Five");
        dictionary.Add(6, "Six");
        dictionary.Add(7, "Seven");
        dictionary.Add(8, "Eight");
        dictionary.Add(9, "Nine");
        //dictionary.Add("Ten", 10);// error as only key, value pair of type int, string can be added

        //for i=0, key doesn't  exist error
        for (int i = 1; i <= dictionary.Count; i++)
        {
            //Can be accessed through indexers
            Console.WriteLine(dictionary[i]);
        }
        //Error : The given key was not present in the dictionary.
        //Console.WriteLine(dictionary[10]);

here error for key 0 & also for key 10 as both are inexistent in dictionary, runtime error, while try to acess.

How to make android listview scrollable?

Practically its not good to do. But if you want to do like this, just make listview's height fixed to wrap_content.

android:layout_height="wrap_content"

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

MySQL Event Scheduler on a specific time everyday

DROP EVENT IF EXISTS xxxEVENTxxx;
CREATE EVENT xxxEVENTxxx
  ON SCHEDULE
    EVERY 1 DAY
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
  DO
    --process;

¡IMPORTANT!->

SET GLOBAL event_scheduler = ON;

Get the first element of each tuple in a list in Python

The functional way of achieving this is to unzip the list using:

sample = [(2, 9), (2, 9), (8, 9), (10, 9), (23, 26), (1, 9), (43, 44)]
first,snd = zip(*sample)
print(first,snd)

(2, 2, 8, 10, 23, 1, 43) (9, 9, 9, 9, 26, 9, 44)

Check if input is integer type in C

num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).

As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d\n"), but here's a trick to do it:

int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
    printf("failure\n");
else
    printf("valid integer followed by enter key\n");

Nullable type as a generic parameter possible?

Just do two things to your original code – remove the where constraint, and change the last return from return null to return default(T). This way you can return whatever type you want.

By the way, you can avoid the use of is by changing your if statement to if (columnValue != DBNull.Value).

Setting the selected value on a Django forms.ChoiceField

Dave - any luck finding a solution to the browser problem? Is there a way to force a refresh?

As for the original problem, try the following when initializing the form:

def __init__(self, *args, **kwargs):
  super(MyForm, self).__init__(*args, **kwargs)   
  self.base_fields['MyChoiceField'].initial = initial_value

How to use Bootstrap in an Angular project?

There are several ways to configure angular2 with Bootstrap, one of the most complete ways to get the most of it is to use ng-bootstrap, using this configuration we give to algular2 complete control over our DOM, avoiding the need to use JQuery and Boostrap.js.

1-Take as a starting point a new project created with Angular-CLI and using the command line, install ng-bootstrap:

npm install @ng-bootstrap/ng-bootstrap --save

Note: More info at https://ng-bootstrap.github.io/#/getting-started

2-Then we need to install bootstrap for the css and the grid system.

npm install [email protected] --save

Note: More info at https://getbootstrap.com/docs/4.0/getting-started/download/

Now we have the setup the environment and for that we have to change the .angular-cli.json adding to the style:

"../node_modules/bootstrap/dist/css/bootstrap.min.css"

Here is an example:

"apps": [
    {
      "root": "src",
        ...
      ],
      "index": "index.html",
       ...
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ]

The next step is to add the ng-boostrap module to our project, to do so we need to add on the app.module.ts:

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

Then add the new module to the application app: NgbModule.forRoot()

Example:

@NgModule({
  declarations: [
    AppComponent,
    AppNavbarComponent
  ],
  imports: [
    BrowserModule,
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Now we can start using bootstrap4 on our angular2/5 project.

How to make the background image to fit into the whole page without repeating using plain css?

try something like

background: url(bgimage.jpg) no-repeat;
background-size: 100%;

Maven: mvn command not found

mvn -version

export PATH=$PATH:/opt/apache-maven-3.6.0/bin

Space between two rows in a table?

You can use line-height in the table:

<table style="width: 400px; line-height:50px;">

Update Fragment from ViewPager

Update Fragment from ViewPager

You need to implement getItemPosition(Object obj) method.

This method is called when you call

notifyDataSetChanged()

on your ViewPagerAdaper. Implicitly this method returns POSITION_UNCHANGED value that means something like this: "Fragment is where it should be so don't change anything."

So if you need to update Fragment you can do it with:

  • Always return POSITION_NONE from getItemPosition() method. It which means: "Fragment must be always recreated"
  • You can create some update() method that will update your Fragment(fragment will handle updates itself)

Example of second approach:

public interface Updateable {
   public void update();
}


public class MyFragment extends Fragment implements Updateable {

   ...

   public void update() {
     // do your stuff
   }
}

And in FragmentPagerAdapter you'll do something like this:

@Override
public int getItemPosition(Object object) {
   MyFragment f = (MyFragment ) object;
   if (f != null) {
      f.update();
   }
  return super.getItemPosition(object);
}

And if you'll choose first approach it can looks like:

@Override
public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Note: It's worth to think a about which approach you'll pick up.

git commit error: pathspec 'commit' did not match any file(s) known to git

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

Kafka consumer list

High level consumers are registered into Zookeeper, so you can fetch a list from ZK, similarly to the way kafka-topics.sh fetches the list of topics. I don't think there's a way to collect all consumers; any application sending in a few consume requests is actually a "consumer", and you cannot tell whether they are done already.

On the consumer side, there's a JMX metric exposed to monitor the lag. Also, there is Burrow for lag monitoring.

How to check whether a string is a valid HTTP URL?

    public static bool CheckURLValid(this string source)
    {
        Uri uriResult;
        return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
    }

Usage:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

UPDATE: (single line of code) Thanks @GoClimbColorado

public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;

Usage:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

Returning null in a method whose signature says return int?

Change your return type to java.lang.Integer . This way you can safely return null

How to fix committing to the wrong Git branch?

So if your scenario is that you've committed to master but meant to commit to another-branch (which may or not may not already exist) but you haven't pushed yet, this is pretty easy to fix.

// if your branch doesn't exist, then add the -b argument 
git checkout -b another-branch
git branch --force master origin/master

Now all your commits to master will be on another-branch.

Sourced with love from: http://haacked.com/archive/2015/06/29/git-migrate/

Extracting double-digit months and days from a Python date

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

Difference between binary tree and binary search tree

Binary tree

Binary tree can be anything which has 2 child and 1 parent. It can be implemented as linked list or array, or with your custom API. Once you start to add more specific rules into it, it becomes more specialized tree. Most common known implementation is that, add smaller nodes on left and larger ones on right.

For example, a labeled binary tree of size 9 and height 3, with a root node whose value is 2. Tree is unbalanced and not sorted. https://en.wikipedia.org/wiki/Binary_tree

enter image description here

For example, in the tree on the left, A has the 6 children {B,C,D,E,F,G}. It can be converted into the binary tree on the right.

enter image description here

Binary Search

Binary Search is technique/algorithm which is used to find specific item on node chain. Binary search works on sorted arrays.

Binary search compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful or the remaining half is empty. https://en.wikipedia.org/wiki/Binary_search_algorithm

enter image description here

A tree representing binary search. The array being searched here is [20, 30, 40, 50, 90, 100], and the target value is 40.

enter image description here

Binary search tree

This is one of the implementations of binary tree. This is specialized for searching.

Binary search tree and B-tree data structures are based on binary search.

Binary search trees (BST), sometimes called ordered or sorted binary trees, are a particular type of container: data structures that store "items" (such as numbers, names etc.) in memory. https://en.wikipedia.org/wiki/Binary_search_tree

A binary search tree of size 9 and depth 3, with 8 at the root. The leaves are not drawn.

enter image description here

And finally great schema for performance comparison of well-known data-structures and algorithms applied:

enter image description here

Image taken from Algorithms (4th Edition)

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

I am running laravel 5.8 and i experienced the same problem. The solution that worked for me is as follows :

  1. I used bigIncrements('id') to define my primary key.
  2. I used unsignedBigInteger('user_id') to define the foreign referenced key.

        Schema::create('generals', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('general_name');
            $table->string('status');
            $table->timestamps();
        });
    
    
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('general_id');
            $table->foreign('general_id')->references('id')->on('generals');
            $table->string('category_name');
            $table->string('status');
            $table->timestamps();
        });
    

I hope this helps out.

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

How to convert date to timestamp in PHP?


This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.

If you don't care about timezone, or want to use the time zone your server uses:

$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093324 (This will differ depending on your server time zone...)


If you want to specify in which time zone, here EST. (Same as New York.)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('EST')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093305


Or if you want to use UTC. (Same as "GMT".)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('UTC')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093289


Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.

Programmatically center TextView text

You can use the following to programmatically center TextView text in Kotlin:

textview.gravity = Gravity.CENTER

how to change any data type into a string in python

Use the str built-in:

x = str(something)

Examples:

>>> str(1)
'1'
>>> str(1.0)
'1.0'
>>> str([])
'[]'
>>> str({})
'{}'

...

From the documentation:

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

Creating a simple login form

Check it - You can try this code for your login form design as you ask thank you.

Explain css -

First, we define property font style and width And after that I have defined form id to set background image and the border And after that I have to define the header text in tag and after that I have added new and define by.New to set background properties and width. Thanks

Create a file index.html

<!DOCTYPE html>
<html>
   <head>
      <link rel="stylesheet" href="style.css">
   </head>
   <body>
      <div id="login_form">
         <div class="new"><span>enter login details</span></div>
         <!-- This is your header text-->
         <form name="f1" method="post" action="login.php" id="f1">
            <table>
               <tr>
                  <td class="f1_label">User Name :</td>
                  <!-- This is your first Input Box Label-->
                  <td>
                     <input type="text" name="username" value="" /><!-- This is your first Input Box-->
                  </td>
               </tr>
               <tr>
                  <td class="f1_label">Password  :</td>
                  <!-- This is your Second Input Box Label-->
                  <td>
                     <input type="password" name="password" value=""  /><!-- This is your Second Input Box -->
                  </td>
               </tr>
               <tr>
                  <td>
                     <input type="submit" name="login" value="Log In" style="font-size:18px; " /><!-- This is your submit button -->
                  </td>
               </tr>
            </table>
         </form>
      </div>
   </body>
</html>

Create css file style.css

body {
    font-style: italic;
    width: 50%;
    margin: 0px auto;
}

#login_form {}

#f1 {
    background-color: #FFF;
    border-style: solid;
    border-width: 1px;
    padding: 23px 1px 20px 114px;
}

.f1_label {
    white-space: nowrap;
}

span {
    color: white;
}

.new {
    background: black;
    text-align: center;
}

How to resolve 'unrecognized selector sent to instance'?

1) Is the synthesize within @implementation block?

2) Should you refer to self.classA = [[ClassA alloc] init]; and self.classA.downloadUrl = @"..." instead of plain classA?

3) In your myApp.m file you need to import ClassA.h, when it's missing it will default to a number, or pointer? (in C variables default to int if not found by compiler):

#import "ClassA.h".

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

When the plugin detects that you're using an API that's no longer supported, it can now provide more-detailed information to help you determine where that API is being used. To see the additional info, you need to include the following in your project's gradle.properties file:

android.debug.obsoleteApi=true

git: fatal: I don't handle protocol '??http'

Please Check URL you have pasted and It takes additional h after clone.

So either you have paste full git clone http://<URL>.git or just remove additional letter before git repository URL.

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

Make sure you have closed your MSAccess file before running the java program.

Unable to read repository at http://download.eclipse.org/releases/indigo

Check if you are able to connect to eclipse market place url (http://marketplace.eclipse.org/) from browser. If its working then the issue is because of proxy server using in your network. We have to update eclipse with proxy server details used in our network.

Go to :- Windows-> Preference -> General -> Network Connections.

enter image description here

And edit HTTP ,with proxy details.

enter image description here

Click OK

Done.

How to list all `env` properties within jenkins pipeline job?

I use Blue Ocean plugin and did not like each environment entry getting its own block. I want one block with all the lines.

Prints poorly:

sh 'echo `env`'

Prints poorly:

sh 'env > env.txt'
for (String i : readFile('env.txt').split("\r?\n")) {
    println i
}

Prints well:

sh 'env > env.txt'
sh 'cat env.txt'

Prints well: (as mentioned by @mjfroehlich)

echo sh(script: 'env', returnStdout: true)

Python can't find module in the same folder

I ran into this issue. I had three folders in the same directory so I had to specify which folder. Ex: from Folder import script

jQuery UI - Draggable is not a function?

I went through both your question and a another duplicate.
In the end, the following answer helped me sorting things out:
uncaught-typeerror-draggable-is-not-a-function

To get rid of :

$(".draggable").draggable is not a function anymore

I had to put links to Javascript libraries above the script tag I expected to be working.

My code:

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js" />
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" />

<script>
    $(function(){
        $("#container-speed").draggable();
    });
</script>

<div class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="rowbackground"style="width: 600px; height: 400px; margin: 0 auto">
                <div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
                <div id="container-rpm" style="width: 300px; height: 200px; float: left"></div>
            </div>
        </div>
    </div>
</div>

R: Comment out block of code

I have dealt with this at talkstats.com in posts 94, 101 & 103 found in the thread: Share Your Code. As others have said Rstudio may be a better way to go. I store these functions in my .Rprofile and actually use them a but to automatically block out lines of code quickly.

Not quite as nice as you were hoping for but may be an approach.