Programs & Examples On #Livecycle

Adobe LiveCycle is a SOA solution from Adobe Systems, mainly used for business process management. It offers services for data capture,PDF processing, digital signatures, document security, content services, process management. The services can be orchestrated with a workflow manager.

port 8080 is already in use and no process using 8080 has been listed

If no other process is using the port 8080, Eventhough eclipse shows the port 8080 is used while starting the server in eclipse, first you have to stop the server by hitting the stop button in "Configure Tomcat"(which you can find in your start menu under tomcat folder), then try to start the server in eclipse then it will be started.

If any other process is using the port 8080 and as well as you no need to disturb it. then you can change the port.

List of All Locales and Their Short Codes?

While accepted answer is pretty complete (I used myself in similar question that arised to me), I think it is worth to put the whole supported language codes and variations, as well as encodings, and point user to a file which is present in almost any linux distributions, in case he simply wants a quicker answer and no internet for example.

This is the file /usr/share/i18n/SUPPORTED and its contents:

aa_DJ.UTF-8 UTF-8
aa_DJ ISO-8859-1
aa_ER UTF-8
aa_ER@saaho UTF-8
aa_ET UTF-8
af_ZA.UTF-8 UTF-8
af_ZA ISO-8859-1
am_ET UTF-8
an_ES.UTF-8 UTF-8
an_ES ISO-8859-15
ar_AE.UTF-8 UTF-8
ar_AE ISO-8859-6
ar_BH.UTF-8 UTF-8
ar_BH ISO-8859-6
ar_DZ.UTF-8 UTF-8
ar_DZ ISO-8859-6
ar_EG.UTF-8 UTF-8
ar_EG ISO-8859-6
ar_IN UTF-8
ar_IQ.UTF-8 UTF-8
ar_IQ ISO-8859-6
ar_JO.UTF-8 UTF-8
ar_JO ISO-8859-6
ar_KW.UTF-8 UTF-8
ar_KW ISO-8859-6
ar_LB.UTF-8 UTF-8
ar_LB ISO-8859-6
ar_LY.UTF-8 UTF-8
ar_LY ISO-8859-6
ar_MA.UTF-8 UTF-8
ar_MA ISO-8859-6
ar_OM.UTF-8 UTF-8
ar_OM ISO-8859-6
ar_QA.UTF-8 UTF-8
ar_QA ISO-8859-6
ar_SA.UTF-8 UTF-8
ar_SA ISO-8859-6
ar_SD.UTF-8 UTF-8
ar_SD ISO-8859-6
ar_SY.UTF-8 UTF-8
ar_SY ISO-8859-6
ar_TN.UTF-8 UTF-8
ar_TN ISO-8859-6
ar_YE.UTF-8 UTF-8
ar_YE ISO-8859-6
az_AZ UTF-8
as_IN UTF-8
ast_ES.UTF-8 UTF-8
ast_ES ISO-8859-15
be_BY.UTF-8 UTF-8
be_BY CP1251
be_BY@latin UTF-8
bem_ZM UTF-8
ber_DZ UTF-8
ber_MA UTF-8
bg_BG.UTF-8 UTF-8
bg_BG CP1251
bho_IN UTF-8
bn_BD UTF-8
bn_IN UTF-8
bo_CN UTF-8
bo_IN UTF-8
br_FR.UTF-8 UTF-8
br_FR ISO-8859-1
br_FR@euro ISO-8859-15
brx_IN UTF-8
bs_BA.UTF-8 UTF-8
bs_BA ISO-8859-2
byn_ER UTF-8
ca_AD.UTF-8 UTF-8
ca_AD ISO-8859-15
ca_ES.UTF-8 UTF-8
ca_ES ISO-8859-1
ca_ES@euro ISO-8859-15
ca_FR.UTF-8 UTF-8
ca_FR ISO-8859-15
ca_IT.UTF-8 UTF-8
ca_IT ISO-8859-15
crh_UA UTF-8
cs_CZ.UTF-8 UTF-8
cs_CZ ISO-8859-2
csb_PL UTF-8
cv_RU UTF-8
cy_GB.UTF-8 UTF-8
cy_GB ISO-8859-14
da_DK.UTF-8 UTF-8
da_DK ISO-8859-1
de_AT.UTF-8 UTF-8
de_AT ISO-8859-1
de_AT@euro ISO-8859-15
de_BE.UTF-8 UTF-8
de_BE ISO-8859-1
de_BE@euro ISO-8859-15
de_CH.UTF-8 UTF-8
de_CH ISO-8859-1
de_DE.UTF-8 UTF-8
de_DE ISO-8859-1
de_DE@euro ISO-8859-15
de_LU.UTF-8 UTF-8
de_LU ISO-8859-1
de_LU@euro ISO-8859-15
dv_MV UTF-8
dz_BT UTF-8
el_GR.UTF-8 UTF-8
el_GR ISO-8859-7
el_CY.UTF-8 UTF-8
el_CY ISO-8859-7
en_AG UTF-8
en_AU.UTF-8 UTF-8
en_AU ISO-8859-1
en_BW.UTF-8 UTF-8
en_BW ISO-8859-1
en_CA.UTF-8 UTF-8
en_CA ISO-8859-1
en_DK.UTF-8 UTF-8
en_DK ISO-8859-1
en_GB.UTF-8 UTF-8
en_GB ISO-8859-1
en_HK.UTF-8 UTF-8
en_HK ISO-8859-1
en_IE.UTF-8 UTF-8
en_IE ISO-8859-1
en_IE@euro ISO-8859-15
en_IN UTF-8
en_NG UTF-8
en_NZ.UTF-8 UTF-8
en_NZ ISO-8859-1
en_PH.UTF-8 UTF-8
en_PH ISO-8859-1
en_SG.UTF-8 UTF-8
en_SG ISO-8859-1
en_US.UTF-8 UTF-8
en_US ISO-8859-1
en_ZA.UTF-8 UTF-8
en_ZA ISO-8859-1
en_ZM UTF-8
en_ZW.UTF-8 UTF-8
en_ZW ISO-8859-1
es_AR.UTF-8 UTF-8
es_AR ISO-8859-1
es_BO.UTF-8 UTF-8
es_BO ISO-8859-1
es_CL.UTF-8 UTF-8
es_CL ISO-8859-1
es_CO.UTF-8 UTF-8
es_CO ISO-8859-1
es_CR.UTF-8 UTF-8
es_CR ISO-8859-1
es_CU UTF-8
es_DO.UTF-8 UTF-8
es_DO ISO-8859-1
es_EC.UTF-8 UTF-8
es_EC ISO-8859-1
es_ES.UTF-8 UTF-8
es_ES ISO-8859-1
es_ES@euro ISO-8859-15
es_GT.UTF-8 UTF-8
es_GT ISO-8859-1
es_HN.UTF-8 UTF-8
es_HN ISO-8859-1
es_MX.UTF-8 UTF-8
es_MX ISO-8859-1
es_NI.UTF-8 UTF-8
es_NI ISO-8859-1
es_PA.UTF-8 UTF-8
es_PA ISO-8859-1
es_PE.UTF-8 UTF-8
es_PE ISO-8859-1
es_PR.UTF-8 UTF-8
es_PR ISO-8859-1
es_PY.UTF-8 UTF-8
es_PY ISO-8859-1
es_SV.UTF-8 UTF-8
es_SV ISO-8859-1
es_US.UTF-8 UTF-8
es_US ISO-8859-1
es_UY.UTF-8 UTF-8
es_UY ISO-8859-1
es_VE.UTF-8 UTF-8
es_VE ISO-8859-1
et_EE.UTF-8 UTF-8
et_EE ISO-8859-1
et_EE.ISO-8859-15 ISO-8859-15
eu_ES.UTF-8 UTF-8
eu_ES ISO-8859-1
eu_ES@euro ISO-8859-15
fa_IR UTF-8
ff_SN UTF-8
fi_FI.UTF-8 UTF-8
fi_FI ISO-8859-1
fi_FI@euro ISO-8859-15
fil_PH UTF-8
fo_FO.UTF-8 UTF-8
fo_FO ISO-8859-1
fr_BE.UTF-8 UTF-8
fr_BE ISO-8859-1
fr_BE@euro ISO-8859-15
fr_CA.UTF-8 UTF-8
fr_CA ISO-8859-1
fr_CH.UTF-8 UTF-8
fr_CH ISO-8859-1
fr_FR.UTF-8 UTF-8
fr_FR ISO-8859-1
fr_FR@euro ISO-8859-15
fr_LU.UTF-8 UTF-8
fr_LU ISO-8859-1
fr_LU@euro ISO-8859-15
fur_IT UTF-8
fy_NL UTF-8
fy_DE UTF-8
ga_IE.UTF-8 UTF-8
ga_IE ISO-8859-1
ga_IE@euro ISO-8859-15
gd_GB.UTF-8 UTF-8
gd_GB ISO-8859-15
gez_ER UTF-8
gez_ER@abegede UTF-8
gez_ET UTF-8
gez_ET@abegede UTF-8
gl_ES.UTF-8 UTF-8
gl_ES ISO-8859-1
gl_ES@euro ISO-8859-15
gu_IN UTF-8
gv_GB.UTF-8 UTF-8
gv_GB ISO-8859-1
ha_NG UTF-8
he_IL.UTF-8 UTF-8
he_IL ISO-8859-8
hi_IN UTF-8
hne_IN UTF-8
hr_HR.UTF-8 UTF-8
hr_HR ISO-8859-2
hsb_DE ISO-8859-2
hsb_DE.UTF-8 UTF-8
ht_HT UTF-8
hu_HU.UTF-8 UTF-8
hu_HU ISO-8859-2
hy_AM UTF-8
hy_AM.ARMSCII-8 ARMSCII-8
id_ID.UTF-8 UTF-8
id_ID ISO-8859-1
ig_NG UTF-8
ik_CA UTF-8
is_IS.UTF-8 UTF-8
is_IS ISO-8859-1
it_CH.UTF-8 UTF-8
it_CH ISO-8859-1
it_IT.UTF-8 UTF-8
it_IT ISO-8859-1
it_IT@euro ISO-8859-15
iu_CA UTF-8
iw_IL.UTF-8 UTF-8
iw_IL ISO-8859-8
ja_JP.EUC-JP EUC-JP
ja_JP.UTF-8 UTF-8
ka_GE.UTF-8 UTF-8
ka_GE GEORGIAN-PS
kk_KZ.UTF-8 UTF-8
kk_KZ PT154
kl_GL.UTF-8 UTF-8
kl_GL ISO-8859-1
km_KH UTF-8
kn_IN UTF-8
ko_KR.EUC-KR EUC-KR
ko_KR.UTF-8 UTF-8
kok_IN UTF-8
ks_IN UTF-8
ks_IN@devanagari UTF-8
ku_TR.UTF-8 UTF-8
ku_TR ISO-8859-9
kw_GB.UTF-8 UTF-8
kw_GB ISO-8859-1
ky_KG UTF-8
lb_LU UTF-8
lg_UG.UTF-8 UTF-8
lg_UG ISO-8859-10
li_BE UTF-8
li_NL UTF-8
lij_IT UTF-8
lo_LA UTF-8
lt_LT.UTF-8 UTF-8
lt_LT ISO-8859-13
lv_LV.UTF-8 UTF-8
lv_LV ISO-8859-13
mag_IN UTF-8
mai_IN UTF-8
mg_MG.UTF-8 UTF-8
mg_MG ISO-8859-15
mhr_RU UTF-8
mi_NZ.UTF-8 UTF-8
mi_NZ ISO-8859-13
mk_MK.UTF-8 UTF-8
mk_MK ISO-8859-5
ml_IN UTF-8
mn_MN UTF-8
mr_IN UTF-8
ms_MY.UTF-8 UTF-8
ms_MY ISO-8859-1
mt_MT.UTF-8 UTF-8
mt_MT ISO-8859-3
my_MM UTF-8
nan_TW@latin UTF-8
nb_NO.UTF-8 UTF-8
nb_NO ISO-8859-1
nds_DE UTF-8
nds_NL UTF-8
ne_NP UTF-8
nl_AW UTF-8
nl_BE.UTF-8 UTF-8
nl_BE ISO-8859-1
nl_BE@euro ISO-8859-15
nl_NL.UTF-8 UTF-8
nl_NL ISO-8859-1
nl_NL@euro ISO-8859-15
nn_NO.UTF-8 UTF-8
nn_NO ISO-8859-1
nr_ZA UTF-8
nso_ZA UTF-8
oc_FR.UTF-8 UTF-8
oc_FR ISO-8859-1
om_ET UTF-8
om_KE.UTF-8 UTF-8
om_KE ISO-8859-1
or_IN UTF-8
os_RU UTF-8
pa_IN UTF-8
pa_PK UTF-8
pap_AN UTF-8
pl_PL.UTF-8 UTF-8
pl_PL ISO-8859-2
ps_AF UTF-8
pt_BR.UTF-8 UTF-8
pt_BR ISO-8859-1
pt_PT.UTF-8 UTF-8
pt_PT ISO-8859-1
pt_PT@euro ISO-8859-15
ro_RO.UTF-8 UTF-8
ro_RO ISO-8859-2
ru_RU.KOI8-R KOI8-R
ru_RU.UTF-8 UTF-8
ru_RU ISO-8859-5
ru_UA.UTF-8 UTF-8
ru_UA KOI8-U
rw_RW UTF-8
sa_IN UTF-8
sc_IT UTF-8
sd_IN UTF-8
sd_IN@devanagari UTF-8
se_NO UTF-8
shs_CA UTF-8
si_LK UTF-8
sid_ET UTF-8
sk_SK.UTF-8 UTF-8
sk_SK ISO-8859-2
sl_SI.UTF-8 UTF-8
sl_SI ISO-8859-2
so_DJ.UTF-8 UTF-8
so_DJ ISO-8859-1
so_ET UTF-8
so_KE.UTF-8 UTF-8
so_KE ISO-8859-1
so_SO.UTF-8 UTF-8
so_SO ISO-8859-1
sq_AL.UTF-8 UTF-8
sq_AL ISO-8859-1
sq_MK UTF-8
sr_ME UTF-8
sr_RS UTF-8
sr_RS@latin UTF-8
ss_ZA UTF-8
st_ZA.UTF-8 UTF-8
st_ZA ISO-8859-1
sv_FI.UTF-8 UTF-8
sv_FI ISO-8859-1
sv_FI@euro ISO-8859-15
sv_SE.UTF-8 UTF-8
sv_SE ISO-8859-1
sw_KE UTF-8
sw_TZ UTF-8
ta_IN UTF-8
ta_LK UTF-8
te_IN UTF-8
tg_TJ.UTF-8 UTF-8
tg_TJ KOI8-T
th_TH.UTF-8 UTF-8
th_TH TIS-620
ti_ER UTF-8
ti_ET UTF-8
tig_ER UTF-8
tk_TM UTF-8
tl_PH.UTF-8 UTF-8
tl_PH ISO-8859-1
tn_ZA UTF-8
tr_CY.UTF-8 UTF-8
tr_CY ISO-8859-9
tr_TR.UTF-8 UTF-8
tr_TR ISO-8859-9
ts_ZA UTF-8
tt_RU UTF-8
tt_RU@iqtelif UTF-8
ug_CN UTF-8
uk_UA.UTF-8 UTF-8
uk_UA KOI8-U
unm_US UTF-8
ur_IN UTF-8
ur_PK UTF-8
uz_UZ ISO-8859-1
uz_UZ@cyrillic UTF-8
ve_ZA UTF-8
vi_VN UTF-8
wa_BE ISO-8859-1
wa_BE@euro ISO-8859-15
wa_BE.UTF-8 UTF-8
wae_CH UTF-8
wal_ET UTF-8
wo_SN UTF-8
xh_ZA.UTF-8 UTF-8
xh_ZA ISO-8859-1
yi_US.UTF-8 UTF-8
yi_US CP1255
yo_NG UTF-8
yue_HK UTF-8
zh_CN.GB18030 GB18030
zh_CN.GBK GBK
zh_CN.UTF-8 UTF-8
zh_CN GB2312
zh_HK.UTF-8 UTF-8
zh_HK BIG5-HKSCS
zh_SG.UTF-8 UTF-8
zh_SG.GBK GBK
zh_SG GB2312
zh_TW.EUC-TW EUC-TW
zh_TW.UTF-8 UTF-8
zh_TW BIG5
zu_ZA.UTF-8 UTF-8
zu_ZA ISO-8859-1

How do I subtract minutes from a date in javascript?

You can also use get and set minutes to achieve it:

var endDate = somedate;

var startdate = new Date(endDate);

var durationInMinutes = 20;

startdate.setMinutes(endDate.getMinutes() - durationInMinutes);

JavaScript - Use variable in string match

For example:

let myString = "Hello World"
let myMatch = myString.match(/H.*/)
console.log(myMatch)

Or

let myString = "Hello World"
let myVariable = "H"
let myReg = new RegExp(myVariable + ".*")
let myMatch = myString.match(myReg)
console.log(myMatch)

Get the value in an input text box

There is one important thing to mention:

$("#txt_name").val();

will return the current real value of a text field, for example if the user typed something there after a page load.

But:

$("#txt_name").attr('value')

will return value from DOM/HTML.

CSS Child vs Descendant selectors

div p 

Selects all 'p' elements where the parent is a 'div' element

div > p

It means immediate children Selects all 'p' elements where the parent is a 'div' element

Git: Create a branch from unstaged/uncommitted changes on master

If you are using the GitHub Windows client (as I am) and you are in the situation of having made uncommitted changes that you wish to move to a new branch, you can simply "Crate a new branch" via the GitHub client. It will switch to the newly created branch and preserve your changes.

enter image description here

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

Extract directory path and filename

dirname "/usr/home/theconjuring/music/song.mp3" will yield /usr/home/theconjuring/music.

C# DateTime to UTC Time without changing the time

You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Mongodb: failed to connect to server on first connect

Local MongoDb problem solution

solve it by following the below steps:

Changed

mongodb://localhost:27017/local

to

localhost/local

And the error gone

Get unique values from arraylist in java

If you have an array of a some kind of object (bean) you can do this:

List<aBean> gasList = createDuplicateGasBeans();
Set<aBean> uniqueGas = new HashSet<aBean>(gasList);

like said Mathias Schwarz above, but you have to provide your aBean with the methods hashCode() and equals(Object obj) that can be done easily in Eclipse by dedicated menu 'Generate hashCode() and equals()' (while in the bean Class). Set will evaluate the overridden methods to discriminate equals objects.

How to Sort Multi-dimensional Array by Value?

One approach to achieve this would be like this

    $new = [
              [
                'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
                'title' => 'Flower',
                'order' => 3,
              ],

              [
                'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
                'title' => 'Free',
                'order' => 2,
              ],

              [
                'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
                'title' => 'Ready',
                'order' => 1,
              ],
    ];

    $keys = array_column($new, 'order');

    array_multisort($keys, SORT_ASC, $new);

    var_dump($new);

Result:

    Array
    (
        [0] => Array
            (
                [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
                [title] => Ready
                [order] => 1
            )

        [1] => Array
            (
                [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
                [title] => Free
                [order] => 2
            )

        [2] => Array
            (
                [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
                [title] => Flower
                [order] => 3
            )

    )

How to install a specific version of a ruby gem?

As others have noted, in general use the -v flag for the gem install command.

If you're developing a gem locally, after cutting a gem from your gemspec:

$ gem install gemname-version.gem

Assuming version 0.8, it would look like this:

$ gem install gemname-0.8.gem

Encrypt and Decrypt in Java

If you use a static key, encrypt and decrypt always give the same result;

public static final String CRYPTOR_KEY = "your static key here";
byte[] keyByte = Base64.getDecoder().decode(CRYPTOR_KEY);
key = new SecretKeySpec(keyByte, "AES");

Android: adb pull file on desktop

On Windows, start up Command Prompt (cmd.exe) or PowerShell (powershell.exe). To do this quickly, open a Run Command window by pressing Windows Key + R. In the Run Command window, type "cmd.exe" to launch Command Prompt; However, to start PowerShell instead, then type "powershell". If you are connecting your Android device to your computer using a USB cable, then you will need to check whether your device is communicating with adb by entering the command below:

# adb devices -l  

Next, pull (copy) the file from your Android device over to Windows. This can be accomplished by entering the following command:

# adb pull /sdcard/log.txt %HOME%\Desktop\log.txt  

Optionally, you may enter this command instead:

# adb pull /sdcard/log.txt C:\Users\admin\Desktop\log.txt 

Why not inherit from List<T>?

Design > Implementation

What methods and properties you expose is a design decision. What base class you inherit from is an implementation detail. I feel it's worth taking a step back to the former.

An object is a collection of data and behaviour.

So your first questions should be:

  • What data does this object comprise in the model I'm creating?
  • What behaviour does this object exhibit in that model?
  • How might this change in future?

Bear in mind that inheritance implies an "isa" (is a) relationship, whereas composition implies a "has a" (hasa) relationship. Choose the right one for your situation in your view, bearing in mind where things might go as your application evolves.

Consider thinking in interfaces before you think in concrete types, as some people find it easier to put their brain in "design mode" that way.

This isn't something everyone does consciously at this level in day to day coding. But if you're mulling this sort of topic, you're treading in design waters. Being aware of it can be liberating.

Consider Design Specifics

Take a look at List<T> and IList<T> on MSDN or Visual Studio. See what methods and properties they expose. Do these methods all look like something someone would want to do to a FootballTeam in your view?

Does footballTeam.Reverse() make sense to you? Does footballTeam.ConvertAll<TOutput>() look like something you want?

This isn't a trick question; the answer might genuinely be "yes". If you implement/inherit List<Player> or IList<Player>, you're stuck with them; if that's ideal for your model, do it.

If you decide yes, that makes sense, and you want your object to be treatable as a collection/list of players (behaviour), and you therefore want to implement ICollection or IList, by all means do so. Notionally:

class FootballTeam : ... ICollection<Player>
{
    ...
}

If you want your object to contain a collection/list of players (data), and you therefore want the collection or list to be a property or member, by all means do so. Notionally:

class FootballTeam ...
{
    public ICollection<Player> Players { get { ... } }
}

You might feel that you want people to be able to only enumerate the set of players, rather than count them, add to them or remove them. IEnumerable<Player> is a perfectly valid option to consider.

You might feel that none of these interfaces are useful in your model at all. This is less likely (IEnumerable<T> is useful in many situations) but it's still possible.

Anyone who attempts to tell you that one of these it is categorically and definitively wrong in every case is misguided. Anyone who attempts to tell you it is categorically and definitively right in every case is misguided.

Move on to Implementation

Once you've decided on data and behaviour, you can make a decision about implementation. This includes which concrete classes you depend on via inheritance or composition.

This may not be a big step, and people often conflate design and implementation since it's quite possible to run through it all in your head in a second or two and start typing away.

A Thought Experiment

An artificial example: as others have mentioned, a team is not always "just" a collection of players. Do you maintain a collection of match scores for the team? Is the team interchangable with the club, in your model? If so, and if your team isa collection of players, perhaps it also isa collection of staff and/or a collection of scores. Then you end up with:

class FootballTeam : ... ICollection<Player>, 
                         ICollection<StaffMember>,
                         ICollection<Score>
{
    ....
}

Design notwithstanding, at this point in C# you won't be able to implement all of these by inheriting from List<T> anyway, since C# "only" supports single inheritance. (If you've tried this malarky in C++, you may consider this a Good Thing.) Implementing one collection via inheritance and one via composition is likely to feel dirty. And properties such as Count become confusing to users unless you implement ILIst<Player>.Count and IList<StaffMember>.Count etc. explicitly, and then they're just painful rather than confusing. You can see where this is going; gut feeling whilst thinking down this avenue may well tell you it feels wrong to head in this direction (and rightly or wrongly, your colleagues might also if you implemented it this way!)

The Short Answer (Too Late)

The guideline about not inheriting from collection classes isn't C# specific, you'll find it in many programming languages. It is received wisdom not a law. One reason is that in practice composition is considered to often win out over inheritance in terms of comprehensibility, implementability and maintainability. It's more common with real world / domain objects to find useful and consistent "hasa" relationships than useful and consistent "isa" relationships unless you're deep in the abstract, most especially as time passes and the precise data and behaviour of objects in code changes. This shouldn't cause you to always rule out inheriting from collection classes; but it may be suggestive.

What is the idiomatic Go equivalent of C's ternary operator?

No Go doesn't have a ternary operator, using if/else syntax is the idiomatic way.

Why does Go not have the ?: operator?

There is no ternary testing operation in Go. You may use the following to achieve the same result:

if expr {
    n = trueVal
} else {
    n = falseVal
}

The reason ?: is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.

— Frequently Asked Questions (FAQ) - The Go Programming Language

Constructors in Go

Golang is not OOP language in its official documents. All fields of Golang struct has a determined value(not like c/c++), so constructor function is not so necessary as cpp. If you need assign some fields some special values, use factory functions. Golang's community suggest New.. pattern names.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

This is LITERALLY 1 google query away, but here goes:

http://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx

Understanding legacy document modes

Use the following value to display the webpage in edge mode, which is the highest standards mode supported by Internet Explorer, from Internet Explorer 6 through IE11.

<meta http-equiv="x-ua-compatible" content="IE=edge"

Note that this is functionally equivalent to using the HTML5 doctype. It places Internet Explorer into the highest supported document mode. Edge most is most useful for regularly maintained websites that are routinely tested for interoperability between multiple browsers, including Internet Explorer.

Note Starting with IE11, edge mode is considered the preferred document mode. (In earlier versions, it was considered experimental.) To learn more, see Document modes are deprecated. Starting with Windows Internet Explorer 8, some web developers used the edge mode meta element to hide the Compatibility View button on the address bar. As of IE11, this is no longer necessary as the button has been removed from the address bar. Because it forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use edge mode for all pages viewed with Internet Explorer. Don't do this, as the X-UA-Compatible header is only supported starting with Internet Explorer 8.

Tip If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration, as shown in the earlier example.

Also among the search results is:

How to wait for async method to complete?

Best Solution to wait AsynMethod till complete the task is

var result = Task.Run(async() => await yourAsyncMethod()).Result;

How to set a time zone (or a Kind) of a DateTime value?

While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.

Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter

Display PDF file inside my android application

you can use webview to show the pdf inside an application , for that you have to :

  1. convert the pdf to html file and store it in asset folder
  2. load the html file to the web view ,

Many pdf to html online converter available.

Example:

    consent_web = (WebView) findViewById(R.id.consentweb);
    consent_web.getSettings().setLoadWithOverviewMode(true);
    consent_web.getSettings().setUseWideViewPort(true);
    consent_web.loadUrl("file:///android_asset/spacs_html.html");

dataframe: how to groupBy/count then filter on count in Scala

So, is that a behavior to expect, a bug

Truth be told I am not sure. It looks like parser is interpreting count not as a column name but a function and expects following parentheses. Looks like a bug or at least a serious limitation of the parser.

is there a canonical way to go around?

Some options have been already mentioned by Herman and mattinbits so here more SQLish approach from me:

import org.apache.spark.sql.functions.count

df.groupBy("x").agg(count("*").alias("cnt")).where($"cnt"  > 2)

Stashing only staged changes in git - is it possible?

Stashing just the index (staged changes) in Git is more difficult than it should be. I've found @Joe's answer to work well, and turned a minor variation of it into this alias:

stash-index = "!f() { \
  git stash push --quiet --keep-index -m \"temp for stash-index\" && \
  git stash push \"$@\" && \
  git stash pop --quiet stash@{1} && \
  git stash show -p | git apply -R; }; f"

It pushes both the staged and unstaged changes into a temporary stash, leaving the staged changes alone. It then pushes the staged changes into the stash, which is the stash we want to keep. Arguments passed to the alias, such as --message "whatever" will be added to this stash command. Finally, it pops the temporary stash to restore the original state and remove the temporary stash, and then finally "removes" the stashed changes from the working directory via a reverse patch application.

For the opposite problem of stashing just the unstaged changes (alias stash-working) see this answer.

Using GCC to produce readable assembly?

Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:

gcc -O2 -S foo.c

will leave the generated assembly code on the file foo.s.

Ripped straight from http://www.delorie.com/djgpp/v2faq/faq8_20.html (but removing erroneous -c)

Force uninstall of Visual Studio

Microsoft now has this:

https://github.com/Microsoft/VisualStudioUninstaller/releases

I allowed a windows 10 update to go through that completely f****d VS2015 so I am trying this before having to resort to a rebuild. WT*. :-(

https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/3487794-create-a-remove-all-remnants-of-visual-studio-fro

Multiple simultaneous downloads using Wget?

Another program that can do this is axel.

axel -n <NUMBER_OF_CONNECTIONS> URL

For baisic HTTP Auth,

axel -n <NUMBER_OF_CONNECTIONS> "user:password@https://domain.tld/path/file.ext"

Ubuntu man page.

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

It's not fancy I known but you could use a callback class, create a hostbuilder and set the configuration to a static property.

For asp core 2.2:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;

namespace Project
{
    sealed class Program
    {
        #region Variables
        /// <summary>
        /// Last loaded configuration
        /// </summary>
        private static IConfiguration _Configuration;
        #endregion

        #region Properties
        /// <summary>
        /// Default application configuration
        /// </summary>
        internal static IConfiguration Configuration
        {
            get
            {
                // None configuration yet?
                if (Program._Configuration == null)
                {
                    // Create the builder using a callback class
                    IWebHostBuilder builder = WebHost.CreateDefaultBuilder().UseStartup<CallBackConfiguration>();

                    // Build everything but do not initialize it
                    builder.Build();
                }

                // Current configuration
                return Program._Configuration;
            }

            // Update configuration
            set => Program._Configuration = value;
        }
        #endregion

        #region Public
        /// <summary>
        /// Start the webapp
        /// </summary>
        public static void Main(string[] args)
        {
            // Create the builder using the default Startup class
            IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

            // Build everything and run it
            using (IWebHost host = builder.Build())
                host.Run();
        }
        #endregion


        #region CallBackConfiguration
        /// <summary>
        /// Aux class to callback configuration
        /// </summary>
        private class CallBackConfiguration
        {
            /// <summary>
            /// Callback with configuration
            /// </summary>
            public CallBackConfiguration(IConfiguration configuration)
            {
                // Update the last configuration
                Program.Configuration = configuration;
            }

            /// <summary>
            /// Do nothing, just for compatibility
            /// </summary>
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                //
            }
        }
        #endregion
    }
}

So now on you just use the static Program.Configuration at any other class you need it.

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

You need to create own PCH file
Add New file -> Other-> PCH file

Then add the path of this PCH file to your build setting->prefix header->path

($(SRCROOT)/filename.pch)

enter image description here

How to maximize a plt.show() window using Python

In my versions (Python 3.6, Eclipse, Windows 7), snippets given above didn't work, but with hints given by Eclipse/pydev (after typing: mng.), I found:

mng.full_screen_toggle()

It seems that using mng-commands is ok only for local development...

ERROR 2003 (HY000): Can't connect to MySQL server (111)

errno 111 is ECONNREFUSED, I suppose something is wrong with the router's DNAT.

It is also possible that your ISP is filtering that port.

Volley - POST/GET parameters

For Future Readers

I love to work with Volley. To save development time i tried to write small handy library Gloxey Netwok Manager to setup Volley with my project. It includes JSON parser and different other methods that helps to check network availability.

Use ConnectionManager.class in which different methods for Volley String and Volley JSON request are available. You can make requests of GET, PUT, POST, DELETE with or without header. You can read full documentation here.

Just put this line in your gradle file.

  dependencies { 

       compile 'io.gloxey.gnm:network-manager:1.0.1'
   }

Volley StringRequest

Method GET (without header)

    ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, volleyResponseInterface);

How to use?

     Configuration                Description

     Context                      Context 
     isDialog                     If true dialog will appear, otherwise not.
     progressView                 For custom progress view supply your progress view id and make isDialog true. otherwise pass null. 
     requestURL                   Pass your API URL.  
     volleyResponseInterface      Callback for response.  

Example

    ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
    @Override
    public void onResponse(String _response) {

        /**
         * Handle Response
         */
    }

    @Override
     public void onErrorResponse(VolleyError error) {

        /**
         * handle Volley Error
         */
    }

    @Override
    public void isNetwork(boolean connected) {

        /**
         * True if internet is connected otherwise false
         */
    }
});

Volley StringRequest

Method POST/PUT/DELETE (without header)

    ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, requestMethod, params, volleyResponseInterface);

Example

Use Method : Request.Method.POST
             Request.Method.PUT
             Request.Method.DELETE

Your params : 

HashMap<String, String> params = new HashMap<>();
params.put("param 1", "value");
params.put("param 2", "value");

ConnectionManager.volleyStringRequest(this, true, null, "url", Request.Method.POST, params, new VolleyResponse() {
    @Override
    public void onResponse(String _response) {

        /**
         * Handle Response
         */
    }

    @Override
    public void onErrorResponse(VolleyError error) {

        /**
         * handle Volley Error
         */
    }

    @Override
    public void isNetwork(boolean connected) {

        /**
         * True if internet is connected otherwise false
         */
    }
});

Bonus

Gloxey JSON Parser

Feel free to use gloxey json parser to parse your api response.

  YourModel yourModel = GloxeyJsonParser.getInstance().parse(stringResponse, YourModel.class);

Example

ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
    @Override
    public void onResponse(String _response) {

        /**
         * Handle Response
         */

         try {

          YourModel yourModel = GloxeyJsonParser.getInstance().parse(_response, YourModel.class);

            } catch (Exception e) {
                e.printStackTrace();
            }

    }

    @Override
     public void onErrorResponse(VolleyError error) {

        /**
         * handle Volley Error
         */
         if (error instanceof TimeoutError || error instanceof NoConnectionError) {

                showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                     //handle retry button

                    }
                });

            } else if (error instanceof AuthFailureError) {
            } else if (error instanceof ServerError) {
            } else if (error instanceof NetworkError) {
            } else if (error instanceof ParseError) {
            }

    }

    @Override
    public void isNetwork(boolean connected) {

        /**
         * True if internet is connected otherwise false
         */
          if (!connected) {
                showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //Handle retry button
                    }
                });
    }
});


     public void showSnackBar(View view, String message) {
            Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
     }

     public void showSnackBar(View view, String message, String actionText, View.OnClickListener onClickListener) {
            Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction(actionText, onClickListener).show();
     }

How to use getJSON, sending data with post method?

$.getJSON() is pretty handy for sending an AJAX request and getting back JSON data as a response. Alas, the jQuery documentation lacks a sister function that should be named $.postJSON(). Why not just use $.getJSON() and be done with it? Well, perhaps you want to send a large amount of data or, in my case, IE7 just doesn’t want to work properly with a GET request.

It is true, there is currently no $.postJSON() method, but you can accomplish the same thing by specifying a fourth parameter (type) in the $.post() function:

My code looked like this:

$.post('script.php', data, function(response) {
  // Do something with the request
}, 'json');

Converting any string into camel case

I ended up crafting a slightly more aggressive solution:

function toCamelCase(str) {
  const [first, ...acc] = str.replace(/[^\w\d]/g, ' ').split(/\s+/);
  return first.toLowerCase() + acc.map(x => x.charAt(0).toUpperCase() 
    + x.slice(1).toLowerCase()).join('');
}

This one, above, will remove all non-alphanumeric characters and lowercase parts of words that would otherwise remain uppercased, e.g.

  • Size (comparative) => sizeComparative
  • GDP (official exchange rate) => gdpOfficialExchangeRate
  • hello => hello

How can I debug a Perl script?

If you want to do remote debugging (for CGI or if you don't want to mess output with debug command line), use this:

Given test:

use v5.14;
say 1;
say 2;
say 3;

Start a listener on whatever host and port on terminal 1 (here localhost:12345):

$ nc -v -l localhost -p 12345

For readline support use rlwrap (you can use on perl -d too):

$ rlwrap nc -v -l localhost -p 12345

And start the test on another terminal (say terminal 2):

$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test

Input/Output on terminal 1:

Connection from 127.0.0.1:42994

Loading DB routines from perl5db.pl version 1.49
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(test:2):    say 1;
  DB<1> n
main::(test:3):    say 2;
  DB<1> select $DB::OUT

  DB<2> n
2
main::(test:4):    say 3;
  DB<2> n
3
Debugged program terminated.  Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
  DB<2>

Output on terminal 2:

1

Note the sentence if you want output on debug terminal

select $DB::OUT

If you are Vim user, install this plugin: dbg.vim which provides basic support for Perl.

How to display HTML in TextView?

String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)

Writing to a new file if it doesn't exist, and appending to a file if it does

It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".

import os
player = 'bob'

filename = player+'.txt'

if os.path.exists(filename):
    append_write = 'a' # append if already exists
else:
    append_write = 'w' # make a new file if not

highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()

How to format strings in Java

This solution worked for me. I needed to create urls for a REST client dynamically so I created this method, so you just have to pass the restURL like this

/customer/{0}/user/{1}/order

and add as many params as you need:

public String createURL (String restURL, Object ... params) {       
    return new MessageFormat(restURL).format(params);
}

You just have to call this method like this:

createURL("/customer/{0}/user/{1}/order", 123, 321);

The output

"/customer/123/user/321/order"

Importing .py files in Google Colab

Below are the steps that worked for me

  1. Mount your google drive in google colab

    from google.colab import drive drive.mount('/content/drive')

  2. Insert the directory

    import sys sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)

  3. check the current directory path

    %cd drive/MyDrive/ColabNotebooks %pwd

  4. Import your module or file

    import my_module

  5. If you get the following error 'Name Null is not defined' then do the following

    5.1 Download my_module.ipynb from colab as my_module.py file (file->Download .py)

    5.2 Upload the *.py file to drive/MyDrive/ColabNotebooks in Google drive

    5.3 import my_module will work now

Reference: https://medium.com/analytics-vidhya/importing-your-own-python-module-or-python-file-into-colab-3e365f0a35ec

https://github.com/googlecolab/colabtools/issues/1358

Correct path for img on React.js

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

If image is in 'public' directory

Example: \public\charts\a.png

In html:

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

In JavaScript:

Create image to new img, dynamically:

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

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

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

If image is in 'src' directory:

Example: \src\logo.svg

In JavaScript:

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

In jsx:

<img src={logo} /> 

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

I would do something like:

$(documento).on('click', '#answer', function() {
  feedback('hey there');
});

How do I add space between items in an ASP.NET RadioButtonList

Use css to add a right margin to those particular elements. Generally I would build the control, then run it to see what the resulting html structure is like, then make the css alter just those elements.

Preferably you do this by setting the class. Add the CssClass="myrblclass" attribute to your list declaration.

You can also add attributes to the items programmatically, which will come out the other side.

rblMyRadioButtonList.Items[x].Attributes.CssStyle.Add("margin-right:5px;")

This may be better for you since you can add that attribute for all but the last one.

How can I correctly format currency using jquery?

Another option (If you are using ASP.Net razor view) is, On your view you can do

<div>@String.Format("{0:C}", Model.total)</div>

This would format it correctly. note (item.total is double/decimal)

if in jQuery you can also use Regex

$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());

Apply CSS rules to a nested class inside a div

Use Css Selector for this, or learn more about Css Selector just go here https://www.w3schools.com/cssref/css_selectors.asp

#main_text > .title {
  /* Style goes here */
}

#main_text .title {
  /* Style goes here */
}

How can I lookup a Java enum from its String value?

You can use the Enum::valueOf() function as suggested by Gareth Davis & Brad Mace above, but make sure you handle the IllegalArgumentException that would be thrown if the string used is not present in the enum.

Detecting a long press with Android

I found one solution and it does not require to define runnable or other things and it's working fine.

    var lastTouchTime: Long = 0

    // ( ViewConfiguration.#.DEFAULT_LONG_PRESS_TIMEOUT =500)
    val longPressTime = 500

    var lastTouchX = 0f
    var lastTouchY = 0f

    view.setOnTouchListener { v, event ->

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastTouchTime = SystemClock.elapsedRealtime()
                lastTouchX = event.x
                lastTouchY = event.y
                return@setOnTouchListener true
            }
            MotionEvent.ACTION_UP -> {
                if (SystemClock.elapsedRealtime() - lastTouchTime > longPressTime
                        && Math.abs(event.x - lastTouchX) < 3
                        && Math.abs(event.y - lastTouchY) < 3) {
                    Log.d(TAG, "Long press")
                }
                return@setOnTouchListener true
            }
            else -> {
                return@setOnTouchListener false
            }
        }

    }

How to pass object with NSNotificationCenter

Swift 5

func post() {
    NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"), 
        object: nil, 
        userInfo:["key0": "value", "key1": 1234])
}

func addObservers() {
    NotificationCenter.default.addObserver(self, 
        selector: #selector(someMethod), 
        name: Notification.Name("SomeNotificationName"), 
        object: nil)
}

@objc func someMethod(_ notification: Notification) {
    let info0 = notification.userInfo?["key0"]
    let info1 = notification.userInfo?["key1"]
}

Bonus (that you should definitely do!) :

Replace Notification.Name("SomeNotificationName") with .someNotificationName:

extension Notification.Name {
    static let someNotificationName = Notification.Name("SomeNotificationName")
}

Replace "key0" and "key1" with Notification.Key.key0 and Notification.Key.key1:

extension Notification {
  enum Key: String {
    case key0
    case key1
  }
}

Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...

Authentication issues with WWW-Authenticate: Negotiate

The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.

This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):

  • either NTLM
  • or Kerberos.

See:

Test if string begins with a string?

Judging by the declaration and description of the startsWith Java function, the "most straight forward way" to implement it in VBA would either be with Left:

Public Function startsWith(str As String, prefix As String) As Boolean
    startsWith = Left(str, Len(prefix)) = prefix
End Function

Or, if you want to have the offset parameter available, with Mid:

Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
    startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
End Function

Managing SSH keys within Jenkins for Git

It looks like the github.com host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts. Jenkins runs on most distros as the user jenkins and hence has its own .ssh directory to store the list of public keys and known_hosts.

The easiest solution I can think of to fix this problem is:

# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash

cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL

# Allow adding the SSH host key to your known_hosts

# Exit from su
exit

Wait for all promises to resolve

You can use "await" in an "async function".

app.controller('MainCtrl', async function($scope, $q, $timeout) {
  ...
  var all = await $q.all([one.promise, two.promise, three.promise]); 
  ...
}

NOTE: I'm not 100% sure you can call an async function from a non-async function and have the right results.

That said this wouldn't ever be used on a website. But for load-testing/integration test...maybe.

Example code:

_x000D_
_x000D_
async function waitForIt(printMe) {_x000D_
  console.log(printMe);_x000D_
  console.log("..."+await req());_x000D_
  console.log("Legendary!")_x000D_
}_x000D_
_x000D_
function req() {_x000D_
  _x000D_
  var promise = new Promise(resolve => {_x000D_
    setTimeout(() => {_x000D_
      resolve("DARY!");_x000D_
    }, 2000);_x000D_
    _x000D_
  });_x000D_
_x000D_
    return promise;_x000D_
}_x000D_
_x000D_
waitForIt("Legen-Wait For It");
_x000D_
_x000D_
_x000D_

Install numpy on python3.3 - Install pip for python3

My issue was the failure to import numpy into my python files. I was receiving the "ModuleNotFoundError: No module named 'numpy'". I ran into the same issue and I was not referencing python3 on the installation of numpy. I inputted the following into my terminal for OSX and my problems were solved:

python3 -m pip install numpy

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

Basically what everybody is looking for is:

LESS:

input:focus:required{
    &:invalid{ color: red; border-color: red; box-shadow: 0 0 6px red;}
    &:valid,
    &:placeholder-shown{ border-color: green; box-shadow: 0 0 8px green;}
}

Pure CSS:

input:focus:required:invalid{ color: red; border-color: red; box-shadow: 0 0 6px red;}
input:focus:required:valid,
input:focus:required:placeholder-shown{ border-color: green; box-shadow: 0 0 8px green;}

How can I include a YAML file inside another?

I make some examples for your reference.

import yaml

main_yaml = """
Package:
 - !include _shape_yaml    
 - !include _path_yaml
"""

_shape_yaml = """
# Define
Rectangle: &id_Rectangle
    name: Rectangle
    width: &Rectangle_width 20
    height: &Rectangle_height 10
    area: !product [*Rectangle_width, *Rectangle_height]

Circle: &id_Circle
    name: Circle
    radius: &Circle_radius 5
    area: !product [*Circle_radius, *Circle_radius, pi]

# Setting
Shape:
    property: *id_Rectangle
    color: red
"""

_path_yaml = """
# Define
Root: &BASE /path/src/

Paths: 
    a: &id_path_a !join [*BASE, a]
    b: &id_path_b !join [*BASE, b]

# Setting
Path:
    input_file: *id_path_a
"""


# define custom tag handler
def yaml_import(loader, node):
    other_yaml_file = loader.construct_scalar(node)
    return yaml.load(eval(other_yaml_file), Loader=yaml.SafeLoader)


def yaml_product(loader, node):
    import math
    list_data = loader.construct_sequence(node)
    result = 1
    pi = math.pi
    for val in list_data:
        result *= eval(val) if isinstance(val, str) else val
    return result


def yaml_join(loader, node):
    seq = loader.construct_sequence(node)
    return ''.join([str(i) for i in seq])


def yaml_ref(loader, node):
    ref = loader.construct_sequence(node)
    return ref[0]


def yaml_dict_ref(loader: yaml.loader.SafeLoader, node):
    dict_data, key, const_value = loader.construct_sequence(node)
    return dict_data[key] + str(const_value)


def main():
    # register the tag handler
    yaml.SafeLoader.add_constructor(tag='!include', constructor=yaml_import)
    yaml.SafeLoader.add_constructor(tag='!product', constructor=yaml_product)
    yaml.SafeLoader.add_constructor(tag='!join', constructor=yaml_join)
    yaml.SafeLoader.add_constructor(tag='!ref', constructor=yaml_ref)
    yaml.SafeLoader.add_constructor(tag='!dict_ref', constructor=yaml_dict_ref)

    config = yaml.load(main_yaml, Loader=yaml.SafeLoader)

    pk_shape, pk_path = config['Package']
    pk_shape, pk_path = pk_shape['Shape'], pk_path['Path']
    print(f"shape name: {pk_shape['property']['name']}")
    print(f"shape area: {pk_shape['property']['area']}")
    print(f"shape color: {pk_shape['color']}")

    print(f"input file: {pk_path['input_file']}")


if __name__ == '__main__':
    main()

output

shape name: Rectangle
shape area: 200
shape color: red
input file: /path/src/a

Update 2

and you can combine it, like this

# xxx.yaml
CREATE_FONT_PICTURE:
  PROJECTS:
    SUNG: &id_SUNG
      name: SUNG
      work_dir: SUNG
      output_dir: temp
      font_pixel: 24


  DEFINE: &id_define !ref [*id_SUNG]  # you can use config['CREATE_FONT_PICTURE']['DEFINE'][name, work_dir, ... font_pixel]
  AUTO_INIT:
    basename_suffix: !dict_ref [*id_define, name, !product [5, 3, 2]]  # SUNG30

# ? This is not correct.
# basename_suffix: !dict_ref [*id_define, name, !product [5, 3, 2]]  # It will build by Deep-level. id_define is Deep-level: 2. So you must put it after 2. otherwise, it can't refer to the correct value.

How to set the JDK Netbeans runs on?

It does not exactly answer your question, but to get around the problem,

  1. you can either create a .cmd file with following content:

    start netbeans --jdkhome c:\path\to\jdk

  2. or in the shortcut of Netbeans set the above option.

Insert variable values in the middle of a string

Use String.Format

Pre C# 6.0

string data = "FlightA, B,C,D";
var str = String.Format("Hi We have these flights for you: {0}. Which one do you want?", data);

C# 6.0 -- String Interpolation

string data = "FlightA, B,C,D";
var str = $"Hi We have these flights for you: {data}. Which one do you want?";

http://www.informit.com/articles/article.aspx?p=2422807

Can the Unix list command 'ls' output numerical chmod permissions?

it almost can ..

 ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
             *2^(8-i));if(k)printf("%0o ",k);print}'

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

How to add an action to a UIAlertView button using Swift iOS

UIAlertViews use a delegate to communicate with you, the client.

You add a second button, and you create an object to receive the delegate messages from the view:

class LogInErrorDelegate : UIAlertViewDelegate {

    init {}

    // not sure of the prototype of this, you should look it up
    func alertView(view :UIAlertView, clickedButtonAtIndex :Integer) -> Void {
        switch clickedButtonAtIndex {
            case 0: 
               userClickedOK() // er something
            case 1:
               userClickedRetry()
              /* Don't use "retry" as a function name, it's a reserved word */

            default:
               userClickedRetry()
        }
    }

    /* implement rest of the delegate */
}
logInErrorAlert.addButtonWithTitle("Retry")

var myErrorDelegate = LogInErrorDelegate()
logInErrorAlert.delegate = myErrorDelegate

Associative arrays in Shell scripts

Adding another option, if jq is available:

export NAMES="{
  \"Mary\":\"100\",
  \"John\":\"200\",
  \"Mary\":\"50\",
  \"John\":\"300\",
  \"Paul\":\"100\",
  \"Paul\":\"400\",
  \"David\":\"100\"
}"
export NAME=David
echo $NAMES | jq --arg v "$NAME" '.[$v]' | tr -d '"' 

How to ignore SSL certificate errors in Apache HttpClient 4.0

We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.

some method to call when making post requests....

SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
    HttpPost postRequest = new HttpPost(url);

continue your request in the normal form

jquery save json data object in cookie

It is not good practice to save the value that is returned from JSON.stringify(userData) to a cookie; it can lead to a bug in some browsers.

Before using it, you should convert it to base64 (using btoa), and when reading it, convert from base64 (using atob).

val = JSON.stringify(userData)
val = btoa(val)

write_cookie(val)

Issue pushing new code in Github

This is happen when you try to push initially.Because in your GitHub repo have readMe.md or any other new thing which is not in your local repo. First you have to merge unrelated history of your github repo.To do that

git pull origin master --allow-unrelated-histories

then you can get the other files from repo(readMe.md or any)using this

git pull origin master

After that

git push -u origin master

Now you successfully push your all the changes into Github repo.I'm not expert in git but every time these step work for me.

Query comparing dates in SQL

Try like this

select id,numbers_from,created_date,amount_numbers,SMS_text 
from Test_Table
where 
created_date <= '2013-12-04'

How do you add a Dictionary of items into another Dictionary

import Foundation

let x = ["a":1]
let y = ["b":2]

let out = NSMutableDictionary(dictionary: x)
out.addEntriesFromDictionary(y)

The result is an NSMutableDictionary not a Swift typed dictionary, but the syntax to use it is the same (out["a"] == 1 in this case) so you'd only have a problem if you're using third-party code which expects a Swift dictionary, or really need the type checking.

The short answer here is that you actually do have to loop. Even if you're not entering it explicitly, that's what the method you're calling (addEntriesFromDictionary: here) will do. I'd suggest if you're a bit unclear on why that would be the case you should consider how you would merge the leaf nodes of two B-trees.

If you really actually need a Swift native dictionary type in return, I'd suggest:

let x = ["a":1]
let y = ["b":2]

var out = x
for (k, v) in y {
    out[k] = v
}

The downside of this approach is that the dictionary index - however it's done - may be rebuilt several times in the loop, so in practice this is about 10x slower than the NSMutableDictionary approach.

Prevent form redirect OR refresh on submit?

If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):

<input name="o" required="required" aria-required="true" type="text">

You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:

$('form').on('submit', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment

As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.

So if you want to get rid of these default pop-ups, use the click event on the submit button:

$('form input[type=submit]').on('click', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes

How to request Administrator access inside a batch file

Another PowerShell Solution...

This is not about running a batch script as admin per, but rather how to elevate another program from batch...

I have a batch file "wrapper" for an exe. They have the same "root file name", but alternate extensions. I am able to launch the exe as admin, and set the working directory to the one containing the script, with the following one line powershell invocation:

@powershell "Start-Process -FilePath '%~n0.exe' -WorkingDirectory '%~dp0' -Verb RunAs"

More info

There are a whole slew of additional Start-Process options as well that you can apply! Check out: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6

Note that I use the @ prefix. That's equivalent to @echo off for the one line. I use %~n0 here to get the "root name" of the batch script, then I concatenate the .exe to point it the adjancent binary. The use of %~dp0 provides the full path to the directory which the batch resides. And, of course, the -Verb RunAs parameter provides the elevation.

How to resolve 'unrecognized selector sent to instance'?

Mine was something simple/stupid. Newbie mistake, for anyone that has converted their NSManagedObject to a normal NSObject.

I had:

@dynamic order_id;

when i should have had:

@synthesize order_id;

Oracle find a constraint

select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/

Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.

The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:

SQL> create table t23 (id number not null primary key)
  2  /

Table created.

SQL> select constraint_name, constraint_type
  2  from user_constraints
  3  where table_name = 'T23'
  4  /

CONSTRAINT_NAME                C
------------------------------ -
SYS_C00935190                  C
SYS_C00935191                  P

SQL>

'C' for check, 'P' for primary.

Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191.

To be honest most people don't bother naming NOT NULL constraints.

Installing SciPy and NumPy using pip

This worked for me on Ubuntu 14.04:

sudo apt-get install libblas-dev liblapack-dev libatlas-base-dev gfortran
pip install scipy

Restore the mysql database from .frm files

Yes this is possible. It is not enough you just copy the .frm files to the to the databse folder but you also need to copy the ib_logfiles and ibdata file into your data folder. I have just copy the .frm files and copy those files and just restart the server and my database is restored.

After copying the above files execute the following command -

sudo chown -R mysql:mysql /var/lib/mysql

The above command will change the file owner under mysql and it's folder to MySql user. Which is important for mysql to read the .frm and ibdata files.

Labels for radio buttons in rails form

This an example from my project for rating using radio buttons and its labels

<div class="rating">
  <%= form.radio_button :star, '1' %>
  <%= form.label :star, '?', value: '1' %>

  <%= form.radio_button :star, '2' %>
  <%= form.label :star, '?', value: '2' %>

  <%= form.radio_button :star, '3' %>
  <%= form.label :star, '?', value: '3' %>

  <%= form.radio_button :star, '4' %>
  <%= form.label :star, '?', value: '4' %>

  <%= form.radio_button :star, '5' %>
  <%= form.label :star, '?', value: '5' %>
</div>

Apply CSS Style to child elements

.test * {padding: 40px 100px 40px 50px;}

How to tell bash that the line continues on the next line

In general, you can use a backslash at the end of a line in order for the command to continue on to the next line. However, there are cases where commands are implicitly continued, namely when the line ends with a token than cannot legally terminate a command. In that case, the shell knows that more is coming, and the backslash can be omitted. Some examples:

# In general
$ echo "foo" \
> "bar"
foo bar

# Pipes
$ echo foo |
> cat
foo

# && and ||
$ echo foo &&
> echo bar
foo
bar
$ false ||
> echo bar
bar

Different, but related, is the implicit continuation inside quotes. In this case, without a backslash, you are simply adding a newline to the string.

$ x="foo
> bar"
$ echo "$x"
foo
bar

With a backslash, you are again splitting the logical line into multiple logical lines.

$ x="foo\
> bar"
$ echo "$x"
foobar

How to find out when a particular table was created in Oracle?

SELECT CREATED FROM USER_OBJECTS WHERE OBJECT_NAME='<<YOUR TABLE NAME>>'

beyond top level package error in relative import

As the most popular answer suggests, basically its because your PYTHONPATH or sys.path includes . but not your path to your package. And the relative import is relative to your current working directory, not the file where the import happens; oddly.

You could fix this by first changing your relative import to absolute and then either starting it with:

PYTHONPATH=/path/to/package python -m test_A.test

OR forcing the python path when called this way, because:

With python -m test_A.test you're executing test_A/test.py with __name__ == '__main__' and __file__ == '/absolute/path/to/test_A/test.py'

That means that in test.py you could use your absolute import semi-protected in the main case condition and also do some one-time Python path manipulation:

from os import path
…
def main():
…
if __name__ == '__main__':
    import sys
    sys.path.append(path.join(path.dirname(__file__), '..'))
    from A import foo

    exit(main())

Compiling Java 7 code via Maven

Diagnostics:

You can see which java version Maven uses by running "mvn --version"

Solution for Debian:

The mvn script sets the JAVA_HOME env variable internally by looking for javac (which javac). Therefore, if you have multiple java versions installed concurrently, e.g. JDK 6 and JDK 7 and use the Debian Alternatives system to choose between them, even though you changed the alternative for "java" to JDK 7, mvn will still use JDK 6. You have to change the alternative for "javac", too. E.g.:

# update-alternatives --set javac /usr/lib/jvm/java-7-openjdk-amd64/bin/javac

EDIT:

Actually, an even better solution is to use update-java-alternatives (e.g.)

# update-java-alternatives -s java-1.7.0-openjdk-amd64

as detailed in https://wiki.debian.org/JavaPackage, because this will change all the alternatives to various Java tools (there's a dozen or so).

GetFiles with multiple extensions

Why not create an extension method? That's more readable.

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
    if (extensions == null) 
         throw new ArgumentNullException("extensions");
    IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>();
    foreach(string ext in extensions)
    {
       files = files.Concat(dir.GetFiles(ext));
    }
    return files;
}

EDIT: a more efficient version:

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
    if (extensions == null) 
         throw new ArgumentNullException("extensions");
    IEnumerable<FileInfo> files = dir.EnumerateFiles();
    return files.Where(f => extensions.Contains(f.Extension));
}

Usage:

DirectoryInfo dInfo = new DirectoryInfo(@"c:\MyDir");
dInfo.GetFilesByExtensions(".jpg",".exe",".gif");

Get access to parent control from user control - C#

If you want to get any parent by any child control you can use this code, and when you find the UserControl/Form/Panel or others you can call funnctions or set/get values:

Control myControl= this;
while (myControl.Parent != null)
{

    if (myControl.Parent!=null)
    {
        myControl = myControl.Parent;
        if  (myControl.Name== "MyCustomUserControl")
        {
            ((MyCustomUserControl)myControl).lblTitle.Text = "FOUND IT";
        }
    }

}

SQL Current month/ year question

This should work for SQL Server:

SELECT * FROM myTable
WHERE month = DATEPART(m, GETDATE()) AND
year = DATEPART(yyyy, GETDATE())

Setting a log file name to include current date in Log4j

this example will be creating logger for each minute, if you want to change for each day change the DatePattern value.

<appender name="ASYNC" class="org.apache.log4j.DailyRollingFileAppender">
   <param name="File" value="./applogs/logger.log" />
   <param name="Append" value="true" />
   <param name="Threshold" value="debug" />
   <appendToFile value="true" />
   <param name="DatePattern" value="'.'yyyy_MM_dd_HH_mm"/>
   <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
      <param name="fileNamePattern" value="./applogs/logger_%d{ddMMMyyyy HH:mm:ss}.log"/>
      <param name="rollOver" value="TRUE"/>
   </rollingPolicy>
   <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{ddMMMyyyy HH:mm:ss,SSS}^[%X{l4j_mdc_key}]^[%c{1}]^ %-5p %m%n" />
   </layout>
</appender>
<root>
   <level value="info" />
   <appender-ref ref="ASYNC" />
</root>

How to extract hours and minutes from a datetime.datetime object?

datetime has fields hour and minute. So to get the hours and minutes, you would use t1.hour and t1.minute.

However, when you subtract two datetimes, the result is a timedelta, which only has the days and seconds fields. So you'll need to divide and multiply as necessary to get the numbers you need.

In HTML5, should the main navigation be inside or outside the <header> element?

To expand on what @JoshuaMaddox said, in the MDN Learning Area, under the "Introduction to HTML" section, the Document and website structure sub-section says (bold/emphasis is by me):

Header

Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.

Navigation bar

Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.

Android SDK Manager Not Installing Components

For those running SDK Manager in Eclipse, selecting "Run As Administrator" while starting Eclipse.exe helps.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

python - find index position in list based of partial string

Without enumerate():

>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]

How to display a Windows Form in full screen on top of the taskbar?

This is how I make forms full screen.

private void button1_Click(object sender, EventArgs e)
{
    int minx, miny, maxx, maxy;
    inx = miny = int.MaxValue;
    maxx = maxy = int.MinValue;

    foreach (Screen screen in Screen.AllScreens)
    {
        var bounds = screen.Bounds;
        minx = Math.Min(minx, bounds.X);
        miny = Math.Min(miny, bounds.Y);
        maxx = Math.Max(maxx, bounds.Right);
        maxy = Math.Max(maxy, bounds.Bottom);
    }

    Form3 fs = new Form3();
    fs.Activate();
    Rectangle tempRect = new Rectangle(1, 0, maxx, maxy);
    this.DesktopBounds = tempRect;
}

How do you display JavaScript datetime in 12 hour AM/PM format?

In modern browsers, use Intl.DateTimeFormat and force 12hr format with options:

    let now = new Date();

    new Intl.DateTimeFormat('default',
        {
            hour12: true,
            hour: 'numeric',
            minute: 'numeric'
        }).format(now);

    // 6:30 AM

Using default will honor browser's default locale if you add more options, yet will still output 12hr format.

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

How do you find the first key in a dictionary?

d.keys()[0] to get the individual key.

Update:- @AlejoBernardin , am not sure why you said it didn't work. here I checked and it worked. import collections

prices  = collections.OrderedDict((

    ("banana", 4),
    ("apple", 2),
    ("orange", 1.5),
    ("pear", 3),
))
prices.keys()[0]

'banana'

Convert Month Number to Month Name Function in SQL

SELECT DATENAME(MONTH,dateadd(month, -3,getdate()))

Export and import table dump (.sql) using pgAdmin

  1. In pgAdmin, select the required target schema in object tree (databases->your_db_name->schemas->your_target_schema)
  2. Click on Plugins/PSQL Console (in top-bar)
  3. Write \i /path/to/yourfile.sql
  4. Press enter

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

I tried so many different things and finally found what worked best for me was simply adding in padding-right: 28px;

I played around with the padding to get the right amount to evenly space the items.

Remove menubar from Electron app

For Electron 7.1.1, you can use this:

const {app, BrowserWindow, Menu} = require('electron')
Menu.setApplicationMenu(false)

byte array to pdf

Usually this happens if something is wrong with the byte array.

File.WriteAllBytes("filename.PDF", Byte[]);

This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

Asynchronous implementation of this is also available.

public static System.Threading.Tasks.Task WriteAllBytesAsync 
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);

Bootstrap Navbar toggle button not working

Wasted several hours only to realize that viewport meta was missing from my code. Adding here just in case some one else misses it out.

As soon as I added this, the toggle started working fine.

<meta name="viewport" content="width=device-width, initial-scale=1">

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

You can also use this stored procedure if you only want to truncate all tables in a specific schema:

-- =============================================
-- Author:      Ben de Ridder
-- Create date: 20160513
-- Description: Truncate all tables in schema
-- =============================================
CREATE PROCEDURE TruncateAllTablesInSchema
    @schema nvarchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @table nVARCHAR(255)

    DECLARE db_cursor CURSOR FOR 
        select t.name
          from sys.tables t inner join
               sys.schemas s on 
                    t.schema_id=s.schema_id
         where s.name=@schema
         order by 1

    OPEN db_cursor   

    FETCH NEXT FROM db_cursor INTO @table   

    WHILE @@FETCH_STATUS = 0   
    BEGIN   
           declare @sql nvarchar(1000)

           set @sql = 'truncate table [' + @schema + '].[' + @table + ']'

           exec sp_sqlexec @sql

           FETCH NEXT FROM db_cursor INTO @table   
    END   

    CLOSE db_cursor   
    DEALLOCATE db_cursor 

END
GO

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

Delete all lines starting with # or ; in Notepad++

Find:

^[#;].*

Replace with nothing. The ^ indicates the start of a line, the [#;] is a character class to match either # or ;, and .* matches anything else in the line.

In versions of Notepad++ before 6.0, you won't be able to actually remove the lines due to a limitation in its regex engine; the replacement results in blank lines for each line matched. In other words, this:

# foo
; bar
statement;

Will turn into:



statement;

However, the replacement will work in Notepad++ 6.0 if you add \r, \n or \r\n to the end of the pattern, depending on which line ending your file is using, resulting in:

statement;

How to check if a Unix .tar.gz file is a valid file without uncompressing?

I have tried the following command and they work well.

bzip2 -t file.bz2
gunzip -t file.gz

However, we can found these two command are time-consuming. Maybe we need some more quick way to determine the intact of the compress files.

How to update two tables in one statement in SQL Server 2005?

You should place two update statements inside a transaction

How to center a subview of UIView

func callAlertView() {

    UIView.animate(withDuration: 0, animations: {
        let H = self.view.frame.height * 0.4
        let W = self.view.frame.width * 0.9
        let X = self.view.bounds.midX - (W/2)
        let Y = self.view.bounds.midY - (H/2)
        self.alertView.frame = CGRect(x:X, y: Y, width: W, height: H)
        self.alertView.layer.borderWidth = 1
        self.alertView.layer.borderColor = UIColor.red.cgColor
        self.alertView.layer.cornerRadius = 16
        self.alertView.layer.masksToBounds = true
        self.view.addSubview(self.alertView)

    })


}// calculation works adjust H and W according to your requirement

What is the reason behind "non-static method cannot be referenced from a static context"?

I just realized, I think people shouldn't be exposed to the concept of "static" very early.

Static methods should probably be the exception rather than the norm. Especially early on anyways if you want to learn OOP. (Why start with an exception to the rule?) That's very counter-pedagogical of Java, that the "first" thing you should learn is the public static void main thing. (Few real Java applications have their own main methods anyways.)

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Use Rescue mode with cd and mount the filesystem. Try to check if any binary files or folder are deleted. If deleted you will have to manually install the rpms to get those files back.

https://askubuntu.com/questions/92946/cannot-boot-because-kernel-panic-not-syncing-attempted-to-kill-init

Merge two dataframes by index

If u want to join two dataframes in pandas you can simply use available attributes like merge or concatenate. For example if I have two dataframes df1 and df2 I can join them by:

newdataframe=merge(df1,df2,left_index=True,right_index=True)

TypeError: unhashable type: 'list' when using built-in set function

Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.

mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
    thing = tuple(thing)
    mylist2.append(thing)
set(mylist2)

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

How to rename uploaded file before saving it into a directory?

The move_uploaded_file will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file

Best way to store passwords in MYSQL database

You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.

Check if a process is running or not on Windows with Python

I'd like to add this solution to the list, for historical purposes. It allows you to find out based on .exe instead of window title, and also returns memory used & PID.

processes = subprocess.Popen('tasklist', stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0]
# Put a regex for exact matches, or a simple 'in' for naive matches

A slice of example output:

notepad.exe                  13944 Console                    1     11,920 K
python.exe                    5240 Console                    1     28,616 K
conhost.exe                   9796 Console                    1      7,812 K
svchost.exe                   1052 Services                   0     18,524 K
iTunes.exe                    1108 Console                    1    157,764 K

Remove columns from dataframe where ALL values are NA

I hope this may also help. It could be made into a single command, but I found it easier for me to read by dividing it in two commands. I made a function with the following instruction and worked lightning fast.

naColsRemoval = function (DataTable) { na.cols = DataTable [ , .( which ( apply ( is.na ( .SD ) , 2 , all ) ) )] DataTable [ , unlist (na.cols) := NULL , with = F] }

.SD will allow to limit the verification to part of the table, if you wish, but it will take the whole table as

Android studio logcat nothing to show

enter image description here

  1. First make Sure developer option is enabled in your device.
  2. Device is connected.
  3. Verbose.
  4. Show Only Selected application.

What is an HttpHandler in ASP.NET

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.

Find the last element of an array while using a foreach loop in PHP

Don't add a comma after the last value:

The array:

$data = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'];

The function:

$result = "";
foreach($data as $value) {
    $result .= (next($data)) ? "$value, " : $value;
}

The result:

print $result;

lorem, ipsum, dolor, sit, amet

Delete the 'first' record from a table in SQL Server, without a WHERE condition

No, AFAIK, it's not possible to do it portably.

There's no defined "first" record anyway - on different SQL engines it's perfectly possible that "SELECT * FROM table" might return the results in a different order each time.

CSS filter: make color image with transparency white

You can use

filter: brightness(0) invert(1);

_x000D_
_x000D_
html {_x000D_
  background: red;_x000D_
}_x000D_
p {_x000D_
  float: left;_x000D_
  max-width: 50%;_x000D_
  text-align: center;_x000D_
}_x000D_
img {_x000D_
  display: block;_x000D_
  max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
  -webkit-filter: brightness(0) invert(1);_x000D_
  filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
  Original:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
  Filter:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

First, brightness(0) makes all image black, except transparent parts, which remain transparent.

Then, invert(1) makes the black parts white.

MySQL Removing Some Foreign keys

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region; This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION Now simply issue an:

alter table region drop foreign key region_ibfk_1;

or

more simply just type:- alter table TableName drop foreign key TableName_ibfk_1;

remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

How to change btn color in Bootstrap

Adding a step-by-step guide to @Codeply-er's answer above for SASS/SCSS newbies like me.

  1. Save btnCustom.scss.
/* import the necessary Bootstrap files */
@import 'bootstrap';

/* Define color */
$mynewcolor:#77cccc;

.btn-custom {
    @include button-variant($mynewcolor, darken($mynewcolor, 7.5%), darken($mynewcolor, 10%), lighten($mynewcolor,5%), lighten($mynewcolor, 10%), darken($mynewcolor,30%));
}

.btn-outline-custom {
    @include button-outline-variant($mynewcolor, #222222, lighten($mynewcolor,5%), $mynewcolor);
}
  1. Download a SASS compiler such as Koala so that SCSS file above can be compiled to CSS.
  2. Clone the Bootstrap github repo because the compiler needs the button-variant mixins somewhere.
  3. Explicitly import bootstrap functions by creating a _bootstrap.scss file as below. This will allow the compiler to access the Bootstrap functions and variables.
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/images";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/tables";
@import "bootstrap/scss/forms";
@import "bootstrap/scss/buttons";
@import "bootstrap/scss/utilities";
  1. Compile btnCustom.scss with the previously downloaded compiler to css.

Is __init__.py not required for packages in Python 3.3+

I would say that one should omit the __init__.py only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the __init__.py even in Python 3.

Multiprocessing a for loop?

You can simply use multiprocessing.Pool:

from multiprocessing import Pool

def process_image(name):
    sci=fits.open('{}.fits'.format(name))
    <process>

if __name__ == '__main__':
    pool = Pool()                         # Create a multiprocessing Pool
    pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

jQuery get values of checked checkboxes into array

Call .get() at the very end to turn the resulting jQuery object into a true array.

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
      return $(this).val();
    }).get(); // <----
    console.log(searchIDs);
});

Per the documentation:

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

Playing m3u8 Files with HTML Video Tag

You can use video js library for easily play HLS video's. It allows to directly play videos

<!-- CSS  -->
 <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">


<!-- HTML -->
<video id='hls-example'  class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>


<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>

<script>
var player = videojs('hls-example');
player.play();
</script>

GitHub Video Js

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

I really liked this answer, with ngBind, your default text can just live in the element body, and then if the ngBind evaluates to something non-null/undefined, your content is replaced automatically, and everythings happy

angularjs setting default values to display before evaluation

To show a new Form on click of a button in C#

Double click the button in the form designer and write the code:

    var form2 = new Form2();
    form2.Show();

Search some samples on the Internet.

jQuery find() method not working in AngularJS directive

From the docs on angular.element:

find() - Limited to lookups by tag name

So if you're not using jQuery with Angular, but relying upon its jqlite implementation, you can't do elm.find('#someid').

You do have access to children(), contents(), and data() implementations, so you can usually find a way around it.

MS Access - execute a saved query by name in VBA

You can do it the following way:

DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("yourQueryName")

How to store arrays in MySQL?

A sidenote to consider, you can store arrays in Postgres.

Pandas split DataFrame by column value

You can use boolean indexing:

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

How To Get Selected Value From UIPickerView

You can get it in the following manner:

NSInteger row;
NSArray *repeatPickerData;
UIPickerView *repeatPickerView;

row = [repeatPickerView selectedRowInComponent:0];
self.strPrintRepeat = [repeatPickerData objectAtIndex:row];

How to check if one DateTime is greater than the other in C#

if(StartDate < EndDate)
{}

DateTime supports normal comparision operators.

Ajax Success and Error function failure

One also may use the following to catch the errors:

$.ajax({
    url: url, 
    success: function (data) {
        // Handle success here
        $('#editor-content-container').html(data);
        $('#editor-container').modal('show');
    },
    cache: false
}).fail(function (jqXHR, textStatus, error) {
    // Handle error here
    $('#editor-content-container').html(jqXHR.responseText);
    $('#editor-container').modal('show');
});

The 'json' native gem requires installed build tools

My gem version 2.0.3 and I was getting the same issue. This command resolved it:

gem install json --platform=ruby --verbose

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

How to use regex with find command?

You should use absolute directory path when applying find instruction with regular expression. In your example, the

find . -regex "[a-f0-9\-]\{36\}\.jpg"

should be changed into

find . -regex "./[a-f0-9\-]\{36\}\.jpg"

In most Linux systems, some disciplines in regular expression cannot be recognized by that system, so you have to explicitly point out -regexty like

find . -regextype posix-extended -regex "[a-f0-9\-]\{36\}\.jpg"

Get single listView SelectedItem

Sometimes using only the line below throws me an Exception,

String text = listView1.SelectedItems[0].Text; 

so I use this code below:

private void listView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (listView1.SelectedIndices.Count <= 0) 
    { 
        return; 
    } 
    int intselectedindex = listView1.SelectedIndices[0]; 
    if (intselectedindex >= 0) 
    {
        String text = listView1.Items[intselectedindex].Text;

        //do something
        //MessageBox.Show(listView1.Items[intselectedindex].Text); 
    } 
}

.Net picking wrong referenced assembly version

I had the same message when switching between two versions of an application that referenced different versions of the same DLL. Although I was testing in different folders I accidentally copied the newer version over the older version.

So the first thing to check is the version of the referenced DLL in the application's folder. Just in case.

How to install Intellij IDEA on Ubuntu?

You can also try my ubuntu repository: https://launchpad.net/~mmk2410/+archive/ubuntu/intellij-idea

To use it just run the following commands:

sudo apt-add-repository ppa:mmk2410/intellij-idea
sudo apt-get update

The community edition can then installed with

sudo apt-get install intellij-idea-community

and the ultimate edition with

sudo apt-get install intellij-idea-ultimate

Unable to import path from django.urls

I changed the python interpreter and it worked. On the keyboard, I pressed ctrl+shift+p. On the next window, I typed python: select interpreter, and there was an option to select the interpreter I wanted. From here, I chose the python interpreter located in my virtual environment.
In this case, it was my ~\DevFolder\myenv\scripts\python.exe

Is there anything like .NET's NotImplementedException in Java?

You could do it yourself (thats what I did) - in order to not be bothered with exception handling, you simply extend the RuntimeException, your class could look something like this:

public class NotImplementedException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public NotImplementedException(){}
}

You could extend it to take a message - but if you use the method as I do (that is, as a reminder, that there is still something to be implemented), then usually there is no need for additional messages.

I dare say, that I only use this method, while I am in the process of developing a system, makes it easier for me to not lose track of which methods are still not implemented properly :)

How do you Encrypt and Decrypt a PHP String?

Below code work in php for all string with special character

   // Encrypt text --

    $token = "9611222007552";

      $cipher_method = 'aes-128-ctr';
      $enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);  
      $enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));  
      $crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
    echo    $crypted_token;
    //unset($token, $cipher_method, $enc_key, $enc_iv);

    // Decrypt text  -- 

    list($crypted_token, $enc_iv) = explode("::", $crypted_token);  
      $cipher_method = 'aes-128-ctr';
      $enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);
      $token = openssl_decrypt($crypted_token, $cipher_method, $enc_key, 0, hex2bin($enc_iv));
    echo   $token;
    //unset($crypted_token, $cipher_method, $enc_key, $enc_iv);

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

Use SET STATISTICS TIME ON

above your query.

Below near result tab you can see a message tab. There you can see the time.

Run Function After Delay

This answer is just useful to understand how you can make delay using JQuery delay function.

Imagine you have an alert and you want to set the alert text then show the alert and after a few seconds hide it.

Here is the simple solution:

$(".alert-element").html("I'm the alert text").fadeIn(500).delay(5000).fadeOut(1000);

It is completely simple:

  1. .html() will change the text of .alert-element
  2. .fadeIn(500) will fade in after 500 milliseconds
  3. JQuery delay(5000) function will make 5000 milliseconds of delay before calling next function
  4. .fadeOut(1000) at the end of the statement will fade out the .alert-element

How to disable Paste (Ctrl+V) with jQuery?

The following code will disable cut, copy and paste from full page.

$(document).ready(function () {
   $('body').bind('cut copy paste', function (e) {
      e.preventDefault();
   });
});

The full tutorial and working demo can be found from here - Disable cut, copy and paste using jQuery

Trying to get property of non-object in

Your error

Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22

Your comment

@22 is <?php echo $sidemenu->mname."<br />";?>

$sidemenu is not an object, and you are trying to access one of its properties.

That is the reason for your error.

How to merge rows in a column into one cell in excel?

If you prefer to do this without VBA, you can try the following:

  1. Have your data in cells A1:A999 (or such)
  2. Set cell B1 to "=A1"
  3. Set cell B2 to "=B1&A2"
  4. Copy cell B2 all the way down to B999 (e.g. by copying B2, selecting cells B3:B99 and pasting)

Cell B999 will now contain the concatenated text string you are looking for.

'^M' character at end of lines

C:\tmp\text>dos2unix hello.txt helloUNIX.txt

Sed is even more widely available and can do this kind of thing also if dos2unix is not installed

C:\tmp\text>sed s/\r// hello.txt > helloUNIX.txt  

You could also try tr:

cat hello.txt | tr -d \r > helloUNIX2.txt  

Here are the results:

C:\tmp\text>dumphex hello.txt  
00000000h: 48 61 68 61 0D 0A 68 61 68 61 0D 0A 68 61 68 61 Haha..haha..haha  
00000010h: 0D 0A 0D 0A 68 61 68 61 0D 0A                   ....haha..  

C:\tmp\text>dumphex helloUNIX.txt  
00000000h: 48 61 68 61 0A 68 61 68 61 0A 68 61 68 61 0A 0A Haha.haha.haha..  
00000010h: 68 61 68 61 0A                                  haha.  

C:\tmp\text>dumphex helloUNIX2.txt  
00000000h: 48 61 68 61 0A 68 61 68 61 0A 68 61 68 61 0A 0A Haha.haha.haha..  
00000010h: 68 61 68 61 0A                                  haha.  

How do I encrypt and decrypt a string in python?

Try this:

Python Cryptography Toolkit (pycrypto) is required

$ pip install pycrypto

Code:

from Crypto.Cipher import AES
from base64 import b64encode, b64decode


class Crypt:

    def __init__(self, salt='SlTKeYOpHygTYkP3'):
        self.salt = salt.encode('utf8')
        self.enc_dec_method = 'utf-8'

    def encrypt(self, str_to_enc, str_key):
        try:
            aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)
            hx_enc = aes_obj.encrypt(str_to_enc.encode('utf8'))
            mret = b64encode(hx_enc).decode(self.enc_dec_method)
            return mret
        except ValueError as value_error:
            if value_error.args[0] == 'IV must be 16 bytes long':
                raise ValueError('Encryption Error: SALT must be 16 characters long')
            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
                raise ValueError('Encryption Error: Encryption key must be either 16, 24, or 32 characters long')
            else:
                raise ValueError(value_error)

    def decrypt(self, enc_str, str_key):
        try:
            aes_obj = AES.new(str_key.encode('utf8'), AES.MODE_CFB, self.salt)
            str_tmp = b64decode(enc_str.encode(self.enc_dec_method))
            str_dec = aes_obj.decrypt(str_tmp)
            mret = str_dec.decode(self.enc_dec_method)
            return mret
        except ValueError as value_error:
            if value_error.args[0] == 'IV must be 16 bytes long':
                raise ValueError('Decryption Error: SALT must be 16 characters long')
            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
                raise ValueError('Decryption Error: Encryption key must be either 16, 24, or 32 characters long')
            else:
                raise ValueError(value_error)

Usage:

        test_crpt = Crypt()
        test_text = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""

        test_key = 'MyKey4TestingYnP'
        test_enc_text = test_crpt.encrypt(test_text, test_key)
        test_dec_text = test_crpt.decrypt(test_enc_text, test_key)
        print(f'Encrypted:{test_enc_text}  Decrypted:{test_dec_text}')

How can I send the "&" (ampersand) character via AJAX?

The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:

$.ajax({
  type: "POST",
  url: "/link.json",
  data: { value: poststr },
  error: function(){ alert('some error occured'); }
});

If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.

Unioning two tables with different number of columns

Add extra columns as null for the table having less columns like

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2

Where's my invalid character (ORA-00911)

If you use the string literal exactly as you have shown us, the problem is the ; character at the end. You may not include that in the query string in the JDBC calls.

As you are inserting only a single row, a regular INSERT should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):

String query1 = "select substr(to_char(max_data),1,4) as year, " + 
  "substr(to_char(max_data),5,6) as month, max_data " +
  "from dss_fin_user.acq_dashboard_src_load_success " + 
  "where source = 'CHQ PeopleSoft FS'";

String query2 = ".....";

String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();

reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();

pstmt.executeBatch();   
con.commit();

Linux command (like cat) to read a specified quantity of characters

head:

Name

head - output the first part of files

Synopsis

head [OPTION]... [FILE]...

Description

Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input.

Mandatory arguments to long options are mandatory for short options too.
-c, --bytes=[-]N print the first N bytes of each file; with the leading '-', print all but the last N bytes of each file

Rotating a view in Android

I just used the simple line in my code and it works :

myCusstomView.setRotation(45);

Hope it works for you.

JOIN queries vs multiple queries

Construct both separate queries and joins, then time each of them -- nothing helps more than real-world numbers.

Then even better -- add "EXPLAIN" to the beginning of each query. This will tell you how many subqueries MySQL is using to answer your request for data, and how many rows scanned for each query.

In Python, what is the difference between ".append()" and "+= []"?

For your case the only difference is performance: append is twice as fast.

Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.20177424499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.41192320500000079

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.23079359499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.44208112500000141

In general case append will add one item to the list, while += will copy all elements of right-hand-side list into the left-hand-side list.

Update: perf analysis

Comparing bytecodes we can assume that append version wastes cycles in LOAD_ATTR + CALL_FUNCTION, and += version -- in BUILD_LIST. Apparently BUILD_LIST outweighs LOAD_ATTR + CALL_FUNCTION.

>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
  1           0 BUILD_LIST               0
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_ATTR                1 (append)
             12 LOAD_CONST               0 ('spam')
             15 CALL_FUNCTION            1
             18 POP_TOP
             19 LOAD_CONST               1 (None)
             22 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
  1           0 BUILD_LIST               0
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_CONST               0 ('spam')
             12 BUILD_LIST               1
             15 INPLACE_ADD
             16 STORE_NAME               0 (s)
             19 LOAD_CONST               1 (None)
             22 RETURN_VALUE

We can improve performance even more by removing LOAD_ATTR overhead:

>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()
0.15924410999923566

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

I faced this issue deploying on Dokku, for some reason it was choosing JDK 1.7

Creating a system.properties file and setting java.runtime.version=1.8 solved the issue. Dokku now uses Java version 8. Choosing a JDK on Heroku

I Never had to do it before...

Assign multiple values to array in C

Exactly, you nearly got it:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

How can I pretty-print JSON in a shell script?

  1. brew install jq
  2. command + | jq
  3. (example: curl localhost:5000/blocks | jq)
  4. Enjoy!

enter image description here

BeautifulSoup: extract text from anchor tag

In my case, it worked like that:

from BeautifulSoup import BeautifulSoup as bs

url="http://blabla.com"

soup = bs(urllib.urlopen(url))
for link in soup.findAll('a'):
        print link.string

Hope it helps!

What is the best way to give a C# auto-property an initial value?

class Person 
{    
    /// Gets/sets a value indicating whether auto 
    /// save of review layer is enabled or not
    [System.ComponentModel.DefaultValue(true)] 
    public bool AutoSaveReviewLayer { get; set; }
}

How to do constructor chaining in C#

What is usage of "Constructor Chain"?
You use it for calling one constructor from another constructor.

How can implement "Constructor Chain"?
Use ": this (yourProperties)" keyword after definition of constructor. for example:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        /// ===== This method is "Chained Method" ===== ///
        this.requestCount= inputCount;
    }
}

Why is it useful?
Important reason is reduce coding, and prevention of duplicate code. such as repeated code for initializing property Suppose some property in class must be initialized with specific value (In our sample, requestDate). And class have 2 or more constructor. Without "Constructor Chain", you must repeat initializaion code in all constractors of class.

How it work? (Or, What is execution sequence in "Constructor Chain")?
in above example, method "a" will be executed first, and then instruction sequence will return to method "b". In other word, above code is equal with below:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        // ===== This method is "Chained Method" ===== ///

        /// *** --- > Compiler execute "MyBillClass()" first, And then continue instruction sequence from here
        this.requestCount= inputCount;
    }
}

VBA Count cells in column containing specified value

Do you mean you want to use a formula in VBA? Something like:

Dim iVal As Integer
iVal = Application.WorksheetFunction.COUNTIF(Range("A1:A10"),"Green")

should work.

How to transform currentTimeMillis to a readable date format?

There is a simpler way in Android

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM

Change a column type from Date to DateTime during ROR migration

Also, if you're using Rails 3 or newer you don't have to use the up and down methods. You can just use change:

class ChangeFormatInMyTable < ActiveRecord::Migration
  def change
    change_column :my_table, :my_column, :my_new_type
  end
end

Reminder - \r\n or \n\r?

if you are using C#, why not using Environment.NewLine ? (i assume you use some file writer objects... just pass it the Environment.NewLine and it will handle the right terminators.

Best way to format if statement with multiple conditions

I've been facing this dilemma for a long time and I still can't find a proper solution. In my opinion only good way is to first try to get rid of conditions before so you're not suddenly comparing 5 of them.

If there's no alternative then like others have suggested - break it down into separete ones and shorten the names or group them and e.g. if all must be true then use something like "if no false in array of x then run".

If all fails @Eoin Campbell gave pretty good ideas.

Disable copy constructor

If you don't mind multiple inheritance (it is not that bad, after all), you may write simple class with private copy constructor and assignment operator and additionally subclass it:

class NonAssignable {
private:
    NonAssignable(NonAssignable const&);
    NonAssignable& operator=(NonAssignable const&);
public:
    NonAssignable() {}
};

class SymbolIndexer: public Indexer, public NonAssignable {
};

For GCC this gives the following error message:

test.h: In copy constructor ‘SymbolIndexer::SymbolIndexer(const SymbolIndexer&)’:
test.h: error: ‘NonAssignable::NonAssignable(const NonAssignable&)’ is private

I'm not very sure for this to work in every compiler, though. There is a related question, but with no answer yet.

UPD:

In C++11 you may also write NonAssignable class as follows:

class NonAssignable {
public:
    NonAssignable(NonAssignable const&) = delete;
    NonAssignable& operator=(NonAssignable const&) = delete;
    NonAssignable() {}
};

The delete keyword prevents members from being default-constructed, so they cannot be used further in a derived class's default-constructed members. Trying to assign gives the following error in GCC:

test.cpp: error: use of deleted function
          ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
test.cpp: note: ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
          is implicitly deleted because the default definition would
          be ill-formed:

UPD:

Boost already has a class just for the same purpose, I guess it's even implemented in similar way. The class is called boost::noncopyable and is meant to be used as in the following:

#include <boost/core/noncopyable.hpp>

class SymbolIndexer: public Indexer, private boost::noncopyable {
};

I'd recommend sticking to the Boost's solution if your project policy allows it. See also another boost::noncopyable-related question for more information.

How to edit default.aspx on SharePoint site without SharePoint Designer

I was able to accomplish editing the default.aspx page by:

  • Opening the site in SharePoint Designer 2013
  • Then clicking 'All Files' to view all of the files,
  • Then right-click -> Edit file in Advanced Mode.

By doing that I was able to remove the tagprefix causing a problem on my page.

How to amend a commit without changing commit message (reusing the previous one)?

Using the accepted answer to create an alias

 oops = "!f(){ \
    git add -A; \
    if [ \"$1\" == '' ]; then \
        git commit --amend --no-edit; \
    else \
        git commit --amend \"$@\"; \
    fi;\
}; f"

then you can do

git oops

and it will add everything, and amend using the same message

or

git oops -m "new message"

to amend replacing the message

How to get an element's top position relative to the browser's viewport?

On my case, just to be safe regarding scrolling, I added the window.scroll to the equation:

var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;

That allows me to get the real relative position of element on document, even if it has been scrolled.

How to catch and print the full exception traceback without halting/exiting the program?

If you're debugging and just want to see the current stack trace, you can simply call:

traceback.print_stack()

There's no need to manually raise an exception just to catch it again.

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

I had this problem, it is for foreign-key

Click on the Relation View (like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB) column, just put the select to nothing! Means no foreign-key

enter image description here

Hope that works!

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN
IF THEN ELSE
IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

So your code should appear like this.

    declare
        var_number number;
    begin
        var_number := 10;
        if var_number > 100 then
           dbms_output.put_line(var_number ||' is greater than 100');
--elseif should be replaced with elsif
        elsif var_number < 100 then
           dbms_output.put_line(var_number ||' is less than 100');
        else
           dbms_output.put_line(var_number ||' is equal to 100');
        end if;
    end; 

How to parse XML to R data frame

You can try the code below:

# Load the packages required to read XML files.
library("XML")
library("methods")

# Convert the input xml file to a data frame.
xmldataframe <- xmlToDataFrame("input.xml")
print(xmldataframe)

Preloading CSS Images

When there is no way to modify CSS code and preload images with CSS rules for :before or :after pseudo elements another approach with JavaScript code traversing CSS rules of loaded stylesheets can be used. In order to make it working scripts should be included after stylesheets in HTML, for example, before closing body tag or just after stylesheets.

getUrls() {
    const urlRegExp = /url\(('|")?([^'"()]+)('|")\)?/;

    let urls = [];
    for (let i = 0; i < document.styleSheets.length; i++) {
        let cssRules = document.styleSheets[i].cssRules;
        for (let j = 0; j < cssRules.length; j++) {
            let cssRule = cssRules[j];
            if (!cssRule.selectorText) {
                continue;
            }

            for (let k = 0; k < cssRule.style.length; k++) {
                let property = cssRule.style[k],
                    urlMatch = cssRule.style[property].match(urlRegExp);
                if (urlMatch !== null) {
                    urls.push(urlMatch[2]);
                }
            }
        }
    }
    return urls;
}

preloadImages() {
    return new Promise(resolve => {
        let urls = getUrls(),
            loadedCount = 0;

        const onImageLoad = () => {
            loadedCount++;
            if (urls.length === loadedCount) {
                resolve();
            }
        };

        for (var i = 0; i < urls.length; i++) {
            let image = new Image();
            image.src = urls[i];
            image.onload = onImageLoad;
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    preloadImages().then(() => {
        // CSS images are loaded here
    });
});

Figuring out whether a number is a Double in Java

Reflection is slower, but works for a situation when you want to know whether that is of type Dog or a Cat and not an instance of Animal. So you'd do something like:

if(null != items.elementAt(1) && items.elementAt(1).getClass().toString().equals("Cat"))
{
//do whatever with cat.. not any other instance of animal.. eg. hideClaws();
}

Not saying the answer above does not work, except the null checking part is necessary.

Another way to answer that is use generics and you are guaranteed to have Double as any element of items.

List<Double> items = new ArrayList<Double>();

How to compare numbers in bash?

If you have floats you can write a function and then use that e.g.

#!/bin/bash

function float_gt() {
    perl -e "{if($1>$2){print 1} else {print 0}}"
}

x=3.14
y=5.20
if [ $(float_gt $x $y) == 1 ] ; then
    echo "do stuff with x"
else
    echo "do stuff with y"
fi

How to retrieve checkboxes values in jQuery

Anyway, you probably need something like this:

 var val = $('#c_b :checkbox').is(':checked').val();
 $('#t').val( val );

This will get the value of the first checked checkbox on the page and insert that in the textarea with id='textarea'.

Note that in your example code you should put the checkboxes in a form.

How do I run PHP code when a user clicks on a link?

If you haven't yet installed jquery (because you're just a beginner or something), use this bit of code:

<a href="#" onclick="thisfunction()">link</a>

<script type="text/javascript">
function thisfunction(){
    var x = new XMLHttpRequest();
    x.open("GET","function.php",true);
    x.send();
    return false;
}
</script>

How to create nested directories using Mkdir in Golang?

This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.

package main

import (
    "fmt"
    "os"
)

func main()  {
    if err := ensureDir("/test-dir"); err != nil {
        fmt.Println("Directory creation failed with error: " + err.Error())
        os.Exit(1)
    }
    // Proceed forward
}

func ensureDir(dirName string) error {

    err := os.MkdirAll(dirName, os.ModeDir)

    if err == nil || os.IsExist(err) {
        return nil
    } else {
        return err
    }
}

What does "yield break;" do in C#?

Tells the iterator that it's reached the end.

As an example:

public interface INode
{
    IEnumerable<Node> GetChildren();
}

public class NodeWithTenChildren : INode
{
    private Node[] m_children = new Node[10];

    public IEnumerable<Node> GetChildren()
    {
        for( int n = 0; n < 10; ++n )
        {
            yield return m_children[ n ];
        }
    }
}

public class NodeWithNoChildren : INode
{
    public IEnumerable<Node> GetChildren()
    {
        yield break;
    }
}

Linux/Unix command to determine if process is running?

This prints the number of processes whose basename is "chromium-browser":

ps -e -o args= | awk 'BEGIN{c=0}{
 if(!match($1,/^\[.*\]$/)){sub(".*/","",$1)} # Do not strip process names enclosed by square brackets.
 if($1==cmd){c++}
}END{print c}' cmd="chromium-browser"

If this prints "0", the process is not running. The command assumes process path does not contain breaking space. I have not tested this with suspended processes or zombie processes.

Tested using gwak as the awk alternative in Linux.

Here is a more versatile solution with some example usage:

#!/bin/sh
isProcessRunning() {
if [ "${1-}" = "-q" ]; then
 local quiet=1;
 shift
else
 local quiet=0;
fi
ps -e -o pid,args= | awk 'BEGIN{status=1}{
 name=$2
 if(name !~ /^\[.*\]$/){sub(".*/","",name)} # strip dirname, if process name is not enclosed by square brackets.
 if(name==cmd){status=0; if(q){exit}else{print $0}}
}END{exit status}' cmd="$1" q=$quiet
}

process='chromium-browser'

printf "Process \"${process}\" is "
if isProcessRunning -q "$process" 
 then printf "running.\n"
 else printf "not running.\n"; fi

printf "Listing of matching processes (PID and process name with command line arguments):\n"
isProcessRunning "$process"

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

Best way to check if a Data Table has a null value in it

foreach(DataRow row in dataTable.Rows)
{
    if(row.IsNull("myColumn"))
        throw new Exception("Empty value!")
}

How do I link to part of a page? (hash?)

On 12 March 2020, a draft has been added by WICG for Text Fragments, and now you can link to text on a page as if you were searching for it by adding the following to the hash

#:~:text=<Text To Link to>

Working example on Chrome Version 81.0.4044.138:

Click on this link Should reload the page and highlight the link's text

How to make an HTML back link?

You can also use history.back() alongside document.write() to show link only when there is actually somewhere to go back to:

<script>
  if (history.length > 1) {
    document.write('<a href="javascript:history.back()">Go back</a>');
  }
</script>

Read values into a shell variable from a pipe

This is another option

$ read test < <(echo hello world)

$ echo $test
hello world

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

Response::json() - Laravel 5.1

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.

if you are like me, simply add

   "use Response;"

above your class ...extends contoller. this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);

Email Address Validation for ASP.NET

You can use a RegularExpression validator. The ValidationExpression property has a button you can press in Visual Studio's property's panel that gets lists a lot of useful expressions. The one they use for email addresses is:

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Get current date/time in seconds

To get today's total seconds of the day:

getTodaysTotalSeconds(){
    let date = new Date();        
    return +(date.getHours() * 60 * 60) + (date.getMinutes() * 60) + date.getSeconds();
}

I have add + in return which return in int. This may help to other developers. :)

Modulo operation with negative numbers

The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z

Here's the reference

http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html

Integer Division

This section describes functions for performing integer division. These functions are redundant in the GNU C library, since in GNU C the '/' operator always rounds towards zero. But in other C implementations, '/' may round differently with negative arguments. div and ldiv are useful because they specify how to round the quotient: towards zero. The remainder has the same sign as the numerator.

Spring default behavior for lazy-init

lazy-init is the attribute of bean. The values of lazy-init can be true and false. If lazy-init is true, then that bean will be initialized when a request is made to bean. This bean will not be initialized when the spring container is initialized and if lazy-init is false then the bean will be initialized with the spring container initialization.

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

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

Borrowing from Michael Jasper's and Jon Hendershot's solutions, I offer the following:

$('address').each(function() {
    var text = $(this).text();

    var q    = $.trim(text).replace(/\r?\n/, ',').replace(/\s+/g, ' ');
    var link = '<a href="http://maps.google.com/maps?q=' + encodeURIComponent(q) + '" target="_blank"></a>';

    return $(this).wrapInner(link);
});

This solution offers the following benefits over solutions previously offered:

  • It will not remove HTML tags (e.g. <br> tags) within <address>, so formatting is preserved
  • It properly encodes the URL
  • It squashes extra spaces so that the generated URL is shorter and cleaner and human-readable after encoding
  • It produces valid markup (Mr.Hendershot's solution creates <a><address></address></a> which is invalid because block-level elements such as <address> are not permitted within inline elements such as <a>.

Caveat: If your <address> tag contains block-level elements like <p> or <div>, then this JavaScript code will produce in invalid markup (because the <a> tag will contain those block-level elements). But if you're just doing stuff like this:

<address>
  The White House
  <br>
  1600 Pennsylvania Ave NW
  <br>
  Washington, D.C.  20500
</address>

Then it'll work just fine.