This can get you selector path of clicked HTML element-
$("*").on("click", function() {
let selectorPath = $(this).parents().map(function () {return this.tagName;}).get().reverse().join("->");
alert(selectorPath);
return false;
});
you should to delete your the Override onOptionsItemSelected and replate your onCreateOptionsMenu with this code
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_action_bar_finish_order_stop, menu);
menu.getItem(0).setOnMenuItemClickListener(new FinishOrderStopListener(this, getApplication(), selectedChild));
return true;
}
$('.my-link').click(function(e) { e.preventDefault(); });
You could use:
$('.my-link').click(function(e) { return false; });
But I don't like to use this myself as it is more cryptic, even though it is used extensively throughout much jQuery code.
In Swift:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.dictionaryRepresentation().keys.forEach { defaults.removeObjectForKey($0) }
<?php
$sessionDetails = $this->Session->read('Auth.User');
if (!empty($sessionDetails)) {
$loginFlag = 1;
# code...
}else{
$loginFlag = 0;
}
?>
<script type="text/javascript">
var sessionValue = '<?php echo $loginFlag; ?>';
if (sessionValue = 0) {
//model show
}
</script>
I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:
class DOH(object):
def __init__(self, property=None):
self.property=property
def property():
return property
x = DOH(1)
print(x.property())
Results
$ python3 t.py
Traceback (most recent call last):
File "t.py", line 9, in <module>
print(x.property())
TypeError: 'int' object is not callable
The problem here of course is that the function is overwritten with a property.
The script below is a generic solution that works for me. It is based on ideas pulled from this and other threads.
When a link with an href attribute beginning with "#" is clicked, it scrolls the page smoothly to the indicated div. Where only the "#" is present, it scrolls smoothly to the top of the page.
$('a[href^=#]').click(function(){
event.preventDefault();
var target = $(this).attr('href');
if (target == '#')
$('html, body').animate({scrollTop : 0}, 600);
else
$('html, body').animate({
scrollTop: $(target).offset().top - 100
}, 600);
});
For example, When the code above is present, clicking a link with the tag <a href="#">
scrolls to the top of the page at speed 600. Clicking a link with the tag <a href="#mydiv">
scrolls to 100px above <div id="mydiv">
at speed 600. Feel free to change these numbers.
I hope it helps!
You can use the following command to access with your ip.
ng serve --host 0.0.0.0 --disable-host-check
If you are using npm and want to avoid running the command every time, we can add the following line to the package.json file in the scripts section.
"scripts": {
...
"start": "ng serve --host 0.0.0.0 --disable-host-check"
...
}
Then you can run you app using the below command to be accessed from the other system in the same network.
npm start
May be this is alltime multiple connection open issue, you are somewhere in your code opening connections and not closing them properly. use
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
}
Refer this article: http://msdn.microsoft.com/en-us/library/ms254507(v=vs.80).aspx, The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.
To disable (or control disabling), add the following lines to the beginning of /etc/ssh/ssh_config
...
Host 192.168.0.*
StrictHostKeyChecking=no
UserKnownHostsFile=/dev/null
Options:
*
to allow unrestricted access to all IPs./etc/ssh/ssh_config
for global configuration or ~/.ssh/config
for user-specific configuration. See http://linuxcommando.blogspot.com/2008/10/how-to-disable-ssh-host-key-checking.html
Similar question on superuser.com - see https://superuser.com/a/628801/55163
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
Add a DoEvents function inside the loop, see below.
You may also want to ensure that the Status bar is visible to the user and reset it when your code completes.
Sub ProgressMeter()
Dim booStatusBarState As Boolean
Dim iMax As Integer
Dim i As Integer
iMax = 10000
Application.ScreenUpdating = False
''//Turn off screen updating
booStatusBarState = Application.DisplayStatusBar
''//Get the statusbar display setting
Application.DisplayStatusBar = True
''//Make sure that the statusbar is visible
For i = 1 To iMax ''// imax is usually 30 or so
fractionDone = CDbl(i) / CDbl(iMax)
Application.StatusBar = Format(fractionDone, "0%") & " done..."
''// or, alternatively:
''// statusRange.value = Format(fractionDone, "0%") & " done..."
''// Some code.......
DoEvents
''//Yield Control
Next i
Application.DisplayStatusBar = booStatusBarState
''//Reset Status bar display setting
Application.StatusBar = False
''//Return control of the Status bar to Excel
Application.ScreenUpdating = True
''//Turn on screen updating
End Sub
Check your config file on views directory. in the add the key for MVC 4/5
Public Function GetLastRow(ByVal SheetName As String) As Integer
Dim sht As Worksheet
Dim FirstUsedRow As Integer 'the first row of UsedRange
Dim UsedRows As Integer ' number of rows used
Set sht = Sheets(SheetName)
''UsedRange.Rows.Count for the empty sheet is 1
UsedRows = sht.UsedRange.Rows.Count
FirstUsedRow = sht.UsedRange.Row
GetLastRow = FirstUsedRow + UsedRows - 1
Set sht = Nothing
End Function
sheet.UsedRange.Rows.Count: retrurn number of rows used, not include empty row above the first row used
if row 1 is empty, and the last used row is 10, UsedRange.Rows.Count will return 9, not 10.
This function calculate the first row number of UsedRange plus number of UsedRange rows.
I forgot to use var
on my item variable
Incorrect code:
var itemCreateInfo = new SP.ListItemCreationInformation();
item = list.addItem(itemCreateInfo);
item.set_item('Title', 'Haytham - Oil Eng');
Correct code:
var itemCreateInfo = new SP.ListItemCreationInformation();
var item = list.addItem(itemCreateInfo);
item.set_item('Title', 'Haytham - Oil Eng');
Since I got here with my problem I will add this answer although it is not exactly relevant to the original question. When you are implementing an interface make sure you do not forget to add the type pointer on your member function declarations. Example:
type AnimalSounder interface {
MakeNoise()
}
type Dog struct {
Name string
mean bool
BarkStrength int
}
func (dog *Dog) MakeNoise() {
//implementation
}
I forgot the *(dog Dog) part, I do not recommend it. Then you get into ugly trouble when calling MakeNoice on an AnimalSounder interface variable of type Dog.
I wasn't quite sure where I would store the start position, so I want to elaborate on David Boikes comment. I found that I could store that variable in the ui.item object itself and retrieve it in the stop function as so:
$( "#sortable" ).sortable({
start: function(event, ui) {
ui.item.startPos = ui.item.index();
},
stop: function(event, ui) {
console.log("Start position: " + ui.item.startPos);
console.log("New position: " + ui.item.index());
}
});
In my case, the installation of nlme
package is in trouble:
mv: cannot move '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/nlme'
to '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/00LOCK-nlme/nlme':
Permission denied
Using Ubuntu 18.04, CTRL+ALT+T to open a terminal window:
sudo R
install.packages('nlme')
q()
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));
kk.getText().toString();
System.out.println(+kk.getText().toString());
You can use style="border:0;"
in your iframe code. That is the recommended way to remove border in HTML5.
Check out my html5 iframe generator tool to customize your iframe without editing code.
Have a look on the below python script to take snap of FB homepage by using selenium package of Chrome web driver.
Script:
import selenium
from selenium import webdriver
import time
from time import sleep
chrome_browser = webdriver.Chrome()
chrome_browser.get('https://www.facebook.com/') # Enter to FB login page
sleep(5)
chrome_browser.save_screenshot('C:/Users/user/Desktop/demo.png') # To take FB homepage snap
chrome_browser.close() # To Close the driver connection
chrome_browser.quit() # To Close the browser
SQL Developer can show the blob as an image (at least it works for jpegs). In the Data view, double click on the BLOB field to get the "pencil" icon. Click on the pencil to get a dialog that will allow you to select a "View As Image" checkbox.
One more scenario of this error:
locally
and run the command without npm run
First, it is important to notice this is a "general" terminal error (Even if you write hello bla.js
-or- wowowowow index.js
):
"hello world" example of this error:
-g
) ==> npm install typescript
.
https://docs.npmjs.com/downloading-and-installing-packages-locallytsc
commands available if you run npm run
inside your local project. For example: npm run tsc -v
:-or- install typescript globally (Like other answer mention).
it means "append "THIS" to the current value"
example:
a = "hello"; a += " world";
printing a now will output: "hello world"
You can add --force-with-lease to the command, it will works.
git push --force-with-lease
--force is destructive because it unconditionally overwrites the remote repository with whatever you have locally. But --force-with-lease ensure you don't overwrite other's work.
See more info here.
string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.
Completing remark to Jimmy Pena's accepted answer
As SeanC points out, this must be a 1-D array.
The following example call demonstrates that the IsInArray()
function cannot be called only for 1-dim arrays,
but also for "flat" 2-dim arrays:
Sub TestIsInArray()
Const SearchItem As String = "ghi"
Debug.Print "SearchItem = '" & SearchItem & "'"
'----
'a) Test 1-dim array
Dim Arr As Variant
Arr = Split("abc,def,ghi,jkl", ",")
Debug.Print "a) 1-dim array " & vbNewLine & " " & Join(Arr, "|") & " ~~> " & IsInArray(SearchItem, Arr)
'----
'//quick tool to create a 2-dim 1-based array
Dim v As Variant, vals As Variant
v = Array(Array("abc", "def", "dummy", "jkl", 5), _
Array("mno", "pqr", "stu", "ghi", "vwx"))
v = Application.Index(v, 0, 0) ' create 2-dim array (2 rows, 5 cols)
'b) Test "flat" 2-dim arrays
Debug.Print "b) ""flat"" 2-dim arrays "
Dim i As Long
For i = LBound(v) To UBound(v)
'slice "flat" 2-dim arrays of one row each
vals = Application.Index(v, i, 0)
'check for findings
Debug.Print Format(i, " 0"), Join(vals, "|") & " ~~> " & IsInArray(SearchItem, vals)
Next i
End Sub
Function IsInArray(stringToBeFound As String, Arr As Variant) As Boolean
'Site: https://stackoverflow.com/questions/10951687/how-to-search-for-string-in-an-array/10952705
'Note: needs a "flat" array, not necessarily a 1-dimensioned array
IsInArray = (UBound(Filter(Arr, stringToBeFound)) > -1)
End Function
Results in VB Editor's immediate window
SearchItem = 'ghi'
a) 1-dim array
abc|def|ghi|jkl ~~> Wahr
b) "flat" 2-dim arrays
1 abc|def|dummy|jkl|5 False
2 mno|pqr|stu|ghi|vwx True
This technique is now deprecated.
This used to tell Google how to index the page.
https://developers.google.com/webmasters/ajax-crawling/
This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value
, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value
to fetch a non-AJAX version of the contents.
Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21"
to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can't initialize arrays like this:
int cipher[Array_size][Array_size]=0;
The syntax for 2D arrays is:
int cipher[Array_size][Array_size]={{0}};
Note the curly braces on the right hand side of the initialization statement.
for 1D arrays:
int tomultiply[Array_size]={0};
try this script..
#!/bin/bash
NULL="_"
for f in `svn st|grep -v ^\?|sed s/.\ *//`;
do LIST="${LIST} $f $NULL on";
done
dialog --checklist "Select files to commit" 30 60 30 $LIST 2>/tmp/svnlist.txt
svn ci `cat /tmp/svnlist.txt|sed 's/"//g'`
This worked for me:
git reset HEAD <filename>
If you want to disable this warning it is important to know that there are two related warning parameters in GCC and Clang: GCC Compiler options -wno-four-char-constants and -wno-multichar
Sometimes the switch variable can also make that error for example:
switch(view.getTag()) {//which is an Object type
case 0://will give compiler error that says Constant expression required
//...
}
To solve you should cast the variable to int(in this case). So:
switch((int)view.getTag()) {//will be int
case 0: //No Error
//...
}
If id
is sequential starting at 1, the simplest (and quickest) would be:
UPDATE `table`
SET uid = ELT(id, 2952, 4925, 1592)
WHERE id IN (1,2,3)
As ELT() returns the Nth element of the list of strings: str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments.
Clearly, the above code only works if id
is 1, 2, or 3. If id
was 10, 20, or 30, either of the following would work:
UPDATE `table`
SET uid = CASE id
WHEN 10 THEN 2952
WHEN 20 THEN 4925
WHEN 30 THEN 1592 END CASE
WHERE id IN (10, 20, 30)
or the simpler:
UPDATE `table`
SET uid = ELT(FIELD(id, 10, 20, 30), 2952, 4925, 1592)
WHERE id IN (10, 20, 30)
As FIELD() returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.
Try:
$string = "'name', 'name2', 'name3',";
$string = rtrim($string,',');
IntelliJ IDEA Plugins / GenerateSerialVersionUID https://plugins.jetbrains.com/plugin/?idea&id=185
very nice, very easy to install. you can install that from plugins menu, select install from disk, select the jar file you unpacked in the lib folder. restart, control + ins, and it pops up to generate serial UID from menu. love it. :-)
Simply run the alter table query using 'KEY' instead of 'FOREIGN KEY' in the drop statement. I hope it will help to solve the issue, and will drop the foreign key constraint and you can change the table columns and drop the table.
ALTER TABLE slide_image_sub DROP KEY FK_slide_image_sub;
here in DROP KEY
instead of DROP FOREIGN KEY
,
hope it will help.
Thanks
As long as you need to find it based on Count just more than 0, it is better to use EXISTS like this:
IF EXISTS (SELECT 1 FROM INCIDENTS WHERE [Some Column] = 'Target Data')
BEGIN
-- TRUE Procedure
END
ELSE BEGIN
-- FALSE Procedure
END
Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.
"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.
"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.
There is a similar problem.it is a tomcat digital signature.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc apache-tomcat-9.0.16-windows-
x64.zip
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key
but then I use the RSA key it provided to receive the public key to verify.
$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg: imported: 1
Then successfully.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc
gpg: assuming signed data in 'apache-tomcat-9.0.16-windows-x64.zip'
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987 5A51 10C0 1C5A 2F60 59E7
Ok, at that time got it done with the help of a friend and the code looks like this.
Sub Saving()
Dim part1 As String
Dim part2 As String
part1 = Range("C5").Value
part2 = Range("C8").Value
ActiveWorkbook.SaveAs Filename:= _
"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou
Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?
You can use stri_paste
function with collapse
parameter from stringi
package like this:
stri_paste(letters, collapse='')
## [1] "abcdefghijklmnopqrstuvwxyz"
And some benchmarks:
require(microbenchmark)
test <- stri_rand_lipsum(100)
microbenchmark(stri_paste(test, collapse=''), paste(test,collapse=''), do.call(paste, c(as.list(test), sep="")))
Unit: microseconds
expr min lq mean median uq max neval
stri_paste(test, collapse = "") 137.477 139.6040 155.8157 148.5810 163.5375 226.171 100
paste(test, collapse = "") 404.139 406.4100 446.0270 432.3250 442.9825 723.793 100
do.call(paste, c(as.list(test), sep = "")) 216.937 226.0265 251.6779 237.3945 264.8935 405.989 100
import re
sentence = ' hello apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub(' ',' ',sentence) #hello world (remove double spaces)
You can't load a controller from a controller in CI - unless you use HMVC or something.
You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.
UPDATE
After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.
If this is the case, you'd get a cleaner solution by getting creative with your routes.
For a really basic example, say you have two controllers, controller1
and controller2
. Controller1
has a method method_1
- and controller2
has a method method_2
.
You can set up routes like this:
$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";
Then, you can call method 1 with a URL like http://site.com/method_1
and method 2 with http://site.com/method_2
.
Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.
You could also go with remapping your controllers.
From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}
You can use getTime()
method to convert the Date
to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date
with setTime()
. See here an example.
Try this, it will convert True into 1 and False into 0:
data.frame$column.name.num <- as.numeric(data.frame$column.name)
Then you can convert into factor if you want:
data.frame$column.name.num.factor <- as .factor(data.frame$column.name.num)
In addition to richq answer of using git log -g --grep=<regexp>
or git grep -e <regexp> $(git log -g --pretty=format:%h)
: take a look at the following blog posts by Junio C Hamano, current git maintainer
Both git grep and git log --grep are line oriented, in that they look for lines that match specified pattern.
You can use git log --grep=<foo> --grep=<bar>
(or git log --author=<foo> --grep=<bar>
that internally translates to two --grep
) to find commits that match either of patterns (implicit OR semantic).
Because of being line-oriented, the useful AND semantic is to use git log --all-match --grep=<foo> --grep=<bar>
to find commit that has both line matching first and line matching second somewhere.
With git grep
you can combine multiple patterns (all which must use the -e <regexp>
form) with --or
(which is the default), --and
, --not
, (
and )
. For grep --all-match
means that file must have lines that match each of alternatives.
Refer this code, auth.ts file
import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { } from 'angular-2-local-storage';
import { Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(public localStorageService:LocalStorageService, private router: Router){}
canActivate() {
// Imaginary method that is supposed to validate an auth token
// and return a boolean
var logInStatus = this.localStorageService.get('logInStatus');
if(logInStatus == 1){
console.log('****** log in status 1*****')
return true;
}else{
console.log('****** log in status not 1 *****')
this.router.navigate(['/']);
return false;
}
}
}
// *****And the app.routes.ts file is as follow ******//
import { Routes } from '@angular/router';
import { HomePageComponent } from './home-page/home- page.component';
import { WatchComponent } from './watch/watch.component';
import { TeachersPageComponent } from './teachers-page/teachers-page.component';
import { UserDashboardComponent } from './user-dashboard/user- dashboard.component';
import { FormOneComponent } from './form-one/form-one.component';
import { FormTwoComponent } from './form-two/form-two.component';
import { AuthGuard } from './authguard';
import { LoginDetailsComponent } from './login-details/login-details.component';
import { TransactionResolver } from './trans.resolver'
export const routes:Routes = [
{ path:'', component:HomePageComponent },
{ path:'watch', component:WatchComponent },
{ path:'teachers', component:TeachersPageComponent },
{ path:'dashboard', component:UserDashboardComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'formone', component:FormOneComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'formtwo', component:FormTwoComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'login-details', component:LoginDetailsComponent, canActivate: [AuthGuard] },
];
This can also be done in the GUI:
Add to your gradle:
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
Convert ArrayList
to JsonArray
JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);
You can also use the following syntax
iptables -D <chain name> <rule number>
For example
Chain HTTPS
target prot opt source destination
ACCEPT all -- anywhere anywhere
ACCEPT all -- 10.0.0.0/8 anywhere
ACCEPT all -- 182.162.0.0/16 anywhere
To delete the rule
ACCEPT all -- 10.0.0.0/8 anywhere
iptables -D HTTPS 2
This is what you can do to source an .env (and .flaskenv) file in the pycharm flask/django console. It would also work for a normal python console of course.
Do pip install python-dotenv
in your environment (the same as being pointed to by pycharm).
Go to: Settings > Build ,Execution, Deployment > Console > Flask/django Console
In "starting script" include something like this near the top:
from dotenv import load_dotenv load_dotenv(verbose=True)
The .env file can look like this:
export KEY=VALUE
It doesn't matter if one includes export
or not for dotenv to read it.
As an alternative you could also source the .env file in the activate shell script for the respective virtual environement.
[examine all threads backtraces to find the culprit]
Even fully expanded call stack can still hide the actual offending line of code from you when you use more than one thread!
Example: One thread is iterating ruby Hash, other thread is trying to modify it. BOOM! Exception! And the problem with the stack trace you get while trying to modify 'busy' hash is that it shows you chain of functions down to the place where you're trying to modify hash, but it does NOT show who's currently iterating it in parallel (who owns it)! Here's the way to figure that out by printing stack trace for ALL currently running threads. Here's how you do this:
# This solution was found in comment by @thedarkone on https://github.com/rails/rails/issues/24627
rescue Object => boom
thread_count = 0
Thread.list.each do |t|
thread_count += 1
err_msg += "--- thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace begin \n"
# Lets see if we are able to pin down the culprit
# by collecting backtrace for all existing threads:
err_msg += t.backtrace.join("\n")
err_msg += "\n---thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace end \n"
end
# and just print it somewhere you like:
$stderr.puts(err_msg)
raise # always reraise
end
The above code snippet is useful even just for educational purposes as it can show you (like x-ray) how many threads you actually have (versus how many you thought you have - quite often those two are different numbers ;)
I know the original posters question was solved, but I came here via Google, and the various answers eventually led me to discovering that my SQL was dumped with a different default charset than the one used to import it. I got the same error as the original question, but as our dump was piped into another MySQL client, we couldn't go the route of opening it with another tool and saving it differently.
For us, the solution turned out to be the --default-character-set=utf8mb4
option, to be used both on the call of mysqldump
as well as the call to import it via mysql
. Of course, the value of the parameter may differ for others facing the same problem, it's just important to keep it the same, as the servers (or the tools) default setting might be any charset.
You were close
/my/bash/script <<< 'This string will be sent to stdin.'
For multiline input, here-docs are suited:
/my/bash/script <<STDIN -o other --options
line 1
line 2
STDIN
Edit To the comments:
To achieve binary input, say
xxd -r -p <<BINARY | iconv -f UCS-4BE -t UTF-8 | /my/bash/script
0000 79c1 0000 306f 0000 3061 0000 3093 0000 3077 0000 3093 0000 304b 0000 3093 0000 3077 0000 3093 0000 306a 0000 8a71 0000 306b 0000 30ca 0000 30f3 0000 30bb
0000 30f3 0000 30b9 0000 3092 0000 7ffb 0000 8a33 0000 3059 0000 308b 0000 3053 0000 3068 0000 304c 0000 3067 0000 304d 0000 000a
BINARY
If you substitute cat
for /my/bash/script
(or indeed drop the last pipe), this prints:
????????????????????????????
Or, if you wanted something a little more geeky:
0000000: 0000 0000 bef9 0e3c 59f8 8e3c 0a71 d63c .......<Y..<.q.<
0000010: c6f2 0e3d 3eaa 323d 3a5e 563d 090e 7a3d ...=>.2=:^V=..z=
0000020: 7bdc 8e3d 2aaf a03d b67e b23d c74a c43d {..=*..=.~.=.J.=
0000030: 0513 d63d 16d7 e73d a296 f93d a8a8 053e ...=...=...=...>
0000040: 6583 0e3e 5a5b 173e 5b30 203e 3d02 293e e..>Z[.>[0 >=.)>
0000050: d4d0 313e f39b 3a3e 6f63 433e 1c27 4c3e ..1>..:>ocC>.'L>
0000060: cde6 543e 59a2 5d3e 9259 663e 4d0c 6f3e ..T>Y.]>.Yf>M.o>
0000070: 60ba 773e cf31 803e ee83 843e 78d3 883e `.w>.1.>...>x..>
0000080: 5720 8d3e 766a 913e beb1 953e 1cf6 993e W .>vj.>...>...>
0000090: 7a37 9e3e c275 a23e dfb0 a63e bce8 aa3e z7.>.u.>...>...>
00000a0: 441d af3e 624e b33e 017c b73e 0ca6 bb3e D..>bN.>.|.>...>
00000b0: 6fcc bf3e 15ef c33e e90d c83e d728 cc3e o..>...>...>.(.>
00000c0: c93f d03e ac52 d43e 6c61 d83e f36b dc3e .?.>.R.>la.>.k.>
00000d0: 2f72 e03e 0a74 e43e 7171 e83e 506a ec3e /r.>.t.>qq.>Pj.>
00000e0: 945e f03e 274e f43e f738 f83e f11e fc3e .^.>'N.>.8.>...>
00000f0: 0000 003f 09ee 013f 89d9 033f 77c2 053f ...?...?...?w..?
0000100: caa8 073f 788c 093f 776d 0b3f be4b 0d3f ...?x..?wm.?.K.?
0000110: 4427 0f3f 0000 113f e8d5 123f f3a8 143f D'.?...?...?...?
0000120: 1879 163f 4e46 183f 8d10 1a3f cad7 1b3f .y.?NF.?...?...?
0000130: fe9b 1d3f 1f5d 1f3f 241b 213f 06d6 223f ...?.].?$.!?.."?
0000140: bb8d 243f 3a42 263f 7cf3 273f 78a1 293f ..$?:B&?|.'?x.)?
0000150: 254c 2b3f 7bf3 2c3f 7297 2e3f 0138 303f %L+?{.,?r..?.80?
0000160: 22d5 313f ca6e 333f ".1?.n3?
Which is the sines of the first 90 degrees in 4byte binary floats
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
the html element break line depend of it's white-space
style property.
in the most of the elements the default white-space
is auto
, which mean break line when the text come to the width of the element.
if you want the text break by \n
you have to give to the parent element the style:
white space: pre-line
, which will read the \n
and break the line, or
white-space: pre
which will also read \t
etc.
note: to write \n
as break-line and not as a string , you have to use a double quoted string ("\n"
)
if you not wanna use a white space, you always welcome to use the HTML Element for break line, which is <br/>
Refer this link for full understand of multiple permission, also full source code download, click Here
private boolean checkAndRequestPermissions() {
int permissionReadPhoneState = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
int permissionProcessOutGogingCalls = ContextCompat.checkSelfPermission(this, Manifest.permission.PROCESS_OUTGOING_CALLS);
int permissionProcessReadContacts = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
int permissionProcessReadCallLog = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG);
int permissionWriteStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionReadStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionReadPhoneState != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
}
if (permissionProcessOutGogingCalls != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
}
if (permissionProcessReadContacts != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_CONTACTS);
}
if (permissionProcessReadCallLog != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_CALL_LOG);
}
if (permissionWriteStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionReadStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length == 0 || grantResults == null) {
/*If result is null*/
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/*If We accept permission*/
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
/*If We Decline permission*/
}
}
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
DECLARE @isAvailable BIT = 0;
IF EXISTS(SELECT 1 FROM [User] WHERE (UserID = 20070022))
BEGIN
SET @isAvailable = 1
END
initially isAvailable boolean value is set to 0
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
In addition to the accepted answer, if you have multiple instances of the activity, you can use a counter instead:
class MyActivity extends Activity {
static int activeInstances = 0;
static boolean isActive() {
return (activeInstance > 0)
}
@Override
public void onStart() {
super.onStart();
activeInstances++;
}
@Override
public void onStop() {
super.onStop();
activeInstances--;
}
}
Another possible candidate are the Guava I/O utilities:
http://code.google.com/p/guava-libraries/wiki/IOExplained
I thought I'd use these since Guava is already immensely useful in my project, rather than adding yet another library for one function.
I've seen this style being used:
if (when || who || format || data || len);
You're dealing with a python list, and sorting it is as easy as doing this.
my_list = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
my_list.sort()
Previous answers might not work for later mysql versions. Try these steps if previous answers did not work for you:
Click on the wamp icon &rarr: mysql → mysql console
write following commands, one by one
use mysql;
update user set authentication_string=password('your_password') where user='root';
FLUSH PRIVILEGES;
quit
You can delete all the documents from a collection in MongoDB, you can use the following:
db.users.remove({})
Alternatively, you could use the following method as well:
db.users.deleteMany({})
Follow the following MongoDB documentation, for further details.
To remove all documents from a collection, pass an empty filter document
{}
to either thedb.collection.deleteMany()
or thedb.collection.remove()
method.
Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)
however, there are still cases where you need the service locator pattern. for example, i have a controller bean, this controller might have some default service beans, which can be dependency injected by configuration. while there could also be many additional or new services this controller can invoke now or later, which then need the service locator to retrieve the service beans.
If you want to change font size for all the text in a figure, you can use findall
to find all text handles, after which it's easy:
figureHandle = gcf;
%# make all text in the figure to size 14 and bold
set(findall(figureHandle,'type','text'),'fontSize',14,'fontWeight','bold')
Look at the specification here: section 2.7.3 http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-25#page-19
The scheme and host are case-insensitive and normally provided in lowercase; all other components are compared in a case-sensitive manner.
Some more options. In Ipython with pylab enabled, dedent is already in the namespace. I checked and it is from matplotlib. Or it can be imported with:
from matplotlib.cbook import dedent
In documentation it states that it is faster than the textwrap equivalent one and in my tests in ipython it is indeed 3 times faster on average with my quick tests. It also has the benefit that it discards any leading blank lines this allows you to be flexible in how you construct the string:
"""
line 1 of string
line 2 of string
"""
"""\
line 1 of string
line 2 of string
"""
"""line 1 of string
line 2 of string
"""
Using the matplotlib dedent on these three examples will give the same sensible result. The textwrap dedent function will have a leading blank line with 1st example.
Obvious disadvantage is that textwrap is in standard library while matplotlib is external module.
Some tradeoffs here... the dedent functions make your code more readable where the strings get defined, but require processing later to get the string in usable format. In docstrings it is obvious that you should use correct indentation as most uses of the docstring will do the required processing.
When I need a non long string in my code I find the following admittedly ugly code where I let the long string drop out of the enclosing indentation. Definitely fails on "Beautiful is better than ugly.", but one could argue that it is simpler and more explicit than the dedent alternative.
def example():
long_string = '''\
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.\
'''
return long_string
print example()
Do you get an error when you try to map through the object keys, or does it throw something else.
Also note when you want to map through the keys you make sure to refer to the object keys correctly. Just like this:
{ Object.keys(subjects).map((item, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subjects[item]}</span>
</li>
))}
You need to use {subjects[item]}
instead of {subjects[i]}
because it refers to the keys of the object. If you look for subjects[i] you will get undefined.
Same issue here as lxxxvi describes. Running
mysql_upgrade -u root
allowed me to then successfully enter a password that
mysql_secure_installation
was waiting for.
<style>
a:hover {
cursor:pointer;
}
</style>
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".link").click(function(){
var href = $(this).attr("href").split("#");
$(".results").text(href[1]);
})
})
</script>
<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>
<br /><br />
<div class="results"></div>
Remove constraint not null
to null
ALTER TABLE 'test' CHANGE COLUMN 'testColumn' 'testColumn' datatype NULL;
For Django
in django.test.TestCase
unit testing, I changed my Python2 syntax:
def test_view(self):
response = self.client.get(reverse('myview'))
self.assertIn(str(self.obj.id), response.content)
...
To use the Python3 .decode('utf8')
syntax:
def test_view(self):
response = self.client.get(reverse('myview'))
self.assertIn(str(self.obj.id), response.content.decode('utf8'))
...
I had some problems with the other solutions on this page, so thought I'd drop this in.
@Html.TextBoxFor(m => m.EndDate, "{0:d}", new { @class = "form-control datepicker" })
So you only need to add "{0:d}" in the second parameter and you should be good to go.
Just had this problem (again!) after getting a new Lion box.
Best solution I've found (still not 100% optimal, but working):
make sure you have 64-bit python. How to check if a library is 32bit/64bit built on Mac OS X?
install easy_install if you don't have it. http://packages.python.org/distribute/easy_install.html
install GCC if you don't have it.
you can get it by downloading XCode/Dev Tools from Apple - this is a big download -
... but instead I recommend this github which has what you need (and does not have XCode): https://github.com/kennethreitz/osx-gcc-installer
I downloaded their prebuilt PKG for lion, https://github.com/downloads/kennethreitz/osx-gcc-installer/GCC-10.7-v2.pkg
make sure you have downloaded a 64-BIT version of MYSQL Community. (The DMG install is an easy route) http://dev.mysql.com/downloads/mysql/
Set paths as follows:
export PATH=$PATH:/usr/local/mysql-XXXX
export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/
export ARCHFLAGS='-arch x86_64'
NOTE THAT:
1 in mysql-XXXX above, XXX is the specific version you downloaded. (Probably /usr/local/mysql/ would also work since this is most likely an alias to the same, but I won't pretend to know your setup)
2 I have seen it suggested that ARCHFLAGS be set to '-arch i386 -arch x86_64' but specifying only x86_64 seemed to work better for me. (I can think of some reasons for this but they are not strictly relevant).
Install the beast!
easy_install MySQL-python
LAST STEP:
Permanently add the DYLD_LIBRARY_PATH!
You can add it to your bash_profile or similar. This was the missing step for me, without which my system continued to insist on various errors finding _mysql.so and so on.
export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/
@richard-boardman, just noticed your soft link solution, which may in effect be doing the same thing my PATH solution does...folks, whatever works best for you.
Best reference: http://activeintelligence.org/blog/archive/mysql-python-aka-mysqldb-on-osx-lion/
you will need the package and its dependencies.
since you mentioned synaptic, you must be using a Debian based system. one way to get what you need:
sudo apt-get install python-tk
I think you have to add grunt to your package.json
file. See this link.
Try this:
String status = "The status of my combobox is " + comboBoxTest.text;
Simply cleaning the project solved it for me.
My project is a C++ application (not a shared library). I randomly got this error after a lot of successful builds.
Those who getting the version issue try this code ..
public static void switchLocal(Context context, String lcode, Activity activity) {
if (lcode.equalsIgnoreCase(""))
return;
Resources resources = context.getResources();
Locale locale = new Locale(lcode);
Locale.setDefault(locale);
android.content.res.Configuration config = new
android.content.res.Configuration();
config.locale = locale;
resources.updateConfiguration(config, resources.getDisplayMetrics());
//restart base activity
activity.finish();
activity.startActivity(activity.getIntent());
}
Just to add to RichieHindle's answer, check out Floatutorial, which walks you through how CSS floating and clearing works.
The importance of the double quotes is worth emphasizing. Suppose an argument contains whitespace.
Code:
#!/bin/bash
printf 'arguments:%s\n' "$@"
declare -a arrayGOOD=( "$@" )
declare -a arrayBAAD=( $@ )
printf '\n%s:\n' arrayGOOD
declare -p arrayGOOD
arrayGOODlength=${#arrayGOOD[@]}
for (( i=1; i<${arrayGOODlength}+1; i++ ));
do
echo "${arrayGOOD[$i-1]}"
done
printf '\n%s:\n' arrayBAAD
declare -p arrayBAAD
arrayBAADlength=${#arrayBAAD[@]}
for (( i=1; i<${arrayBAADlength}+1; i++ ));
do
echo "${arrayBAAD[$i-1]}"
done
Output:
> ./bash-array-practice.sh 'The dog ate the "flea" -- and ' the mouse.
arguments:The dog ate the "flea" -- and
arguments:the
arguments:mouse.
arrayGOOD:
declare -a arrayGOOD='([0]="The dog ate the \"flea\" -- and " [1]="the" [2]="mouse.")'
The dog ate the "flea" -- and
the
mouse.
arrayBAAD:
declare -a arrayBAAD='([0]="The" [1]="dog" [2]="ate" [3]="the" [4]="\"flea\"" [5]="--" [6]="and" [7]="the" [8]="mouse.")'
The
dog
ate
the
"flea"
--
and
the
mouse.
>
for python 3 it worked for what @HYRY posted. I needed it for a returned data in a dbus.array. This is the only way it worked
s = "ABCD"
from array import array
a = array("B", s)
Try a combination of std::string::find
and std::string::replace
.
This gets the position:
std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);
And this replaces the first occurrence:
s.replace(pos, toReplace.length(), "new text");
Now you can simply create a function for your convenience:
std::string replaceFirstOccurrence(
std::string& s,
const std::string& toReplace,
const std::string& replaceWith)
{
std::size_t pos = s.find(toReplace);
if (pos == std::string::npos) return s;
return s.replace(pos, toReplace.length(), replaceWith);
}
Here's a solution that I think is better than any posted so far:
/* s must be an even-length string. */
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
Reasons why it is an improvement:
Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)
Doesn't convert the String into a char[]
, or create StringBuilder and String objects for every single byte.
No library dependencies that may not be available
Feel free to add argument checking via assert
or exceptions if the argument is not known to be safe.
If you want to keep it open when you are debugging, but still let it close normally when not debugging, you can do something like this:
if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();
Like other answers have stated, the call to Console.ReadLine()
will keep the window open until enter is pressed, but Console.ReadLine()
will only be called if the debugger is attached.
I got here looking for a way to add a key/value pair(s) as a group - in my case it was the output of a function call, so adding the pair using dictionary[key] = value
would require me to know the name of the key(s).
In this case, you can use the update method:
dictionary.update(function_that_returns_a_dict(*args, **kwargs)))
Beware, if dictionary
already contains one of the keys, the original value will be overwritten.
Here's a solution that shuffles a list of unique numbers (no repeats, ever).
for (var a=[],i=0;i<40;++i) a[i]=i;
// http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
a = shuffle(a);
If you want to allow repeated values (which is not what the OP wanted) then look elsewhere. :)
You can also use:
git reset HEAD file/path
One option is to place your properties file in the src/ directory of your project. This will copy it to the "classes" (along with your .class files) at build time. I often do this for web projects.
An on-line syntax highlighter:
or
Just copy and paste into your document.
No, it's not possible.
It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".
A standard prolog predicate will do this.
isfive(5).
will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use \=
isNotEqual(A,B):- A\=B.
Technically it is does not unify, but it is similar to not equal.
Learn Prolog Now is a good website for learning prolog.
Edit: To add another example.
isEqual(A,A).
For individual variables you want to make available on a one off basis you can make it part of the command.
sudo http_proxy=$http_proxy wget "http://stackoverflow.com"
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
try this step if you need: Xcode 11.5 1- open terminal: cd Path_project 2- cd pod clean 3- pod install
1- open Build Phases for target -> [CP] Embed Pods FrameWork check this field
Please see this:
http://jsfiddle.net/JSWorld/Hp4W7/32/
<div ng-repeat="division in divisions | orderBy:['group','sub']">{{division.group}}-{{division.sub}}</div>
A non-JIT compiler takes source code and transforms it into machine specific byte code at compile time. A JIT compiler takes machine agnostic byte code that was generated at compile time and transforms it into machine specific byte code at run time. The JIT compiler that Java uses is what allows a single binary to run on a multitude of platforms without modification.
You could try direction:rtl;
in your css. Then reset the text direction in the inner div
#scroll{
direction:rtl;
overflow:auto;
height:50px;
width:50px;}
#scroll div{
direction:ltr;
}
Untested.
I actually used the answer from How do I run a node.js app as a background service? combined with what dwrz said above. In my case, I was creating a Discord bot that needed to be able to run when I was not around.
With this service in place, I initially got the same error that the initial poster did, which brought me here. I was missing the #!/usr/bin/env node
at the top of my executed node.js script.
Since then, no problems, although I intend to see what else can be extended to the service itself.
As already stated this is not something that browsers support.
If you aren't coming up with the styles dynamically (i.e. pulling them out of a database or something) you should be able to work around this by adding a class to the body of the page.
The css would look something like:
a:hover { background: red; }
.theme1 a:hover { background: blue; }
And the javascript to change this would be something like:
// Look up some good add/remove className code if you want to do this
// This is really simplified
document.body.className += " theme1";
The best way to do this is to first generate a .c file, and then compile it with tcc to a .pyd file
Note: Windows-onlyRequirements
Install:
sudo pip install -U cython
To obfuscate your .py file:
pyobfuscate.py myfile.py >obfuscated.py
To generate a .c file,
Add an Optionalinit<filename>()
function to your .py file
cython --embed file.py
cp Python.h tcc\include
tcc file.c -o file.pyd -shared -I\path\to\Python\include -L\path\to\Python\lib
import .pyd file into app.exe
The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.
GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';
This will grant all privileges to one database test_database
(in your case dbTest
) to that user on localhost.
Check what permissions that above command issued to that user by running the below command.
SHOW GRANTS FOR 'user'@'localhost'
Just in case, if you want to limit the user access to only one single table
GRANT ALL ON mydb.table_name TO 'someuser'@'host';
Also had this error when accidentally fed a database connection string to the readonly mirror - not the primary database in a HA setup.
This Worked for me ! For Angular 2 , Call child component method in parent component
Parent.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from '../child/child';
@Component({
selector: 'parent-app',
template: `<child-cmp></child-cmp>`
})
export class parentComponent implements OnInit{
@ViewChild(ChildComponent ) child: ChildComponent ;
ngOnInit() {
this.child.ChildTestCmp(); }
}
Child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'child-cmp',
template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> `
})
export class ChildComponent {
test: string;
ChildTestCmp()
{
this.test = "I am child component!";
}
}
public LightDataTable PagerSelection(int pageNumber, int setsPerPage, Func<LightDataRow, bool> prection = null)
{
this.setsPerPage = setsPerPage;
this.pageNumber = pageNumber > 0 ? pageNumber - 1 : pageNumber;
if (!ValidatePagerByPageNumber(pageNumber))
return this;
var rowList = rows.Cast<LightDataRow>();
if (prection != null)
rowList = rows.Where(prection).ToList();
if (!rowList.Any())
return new LightDataTable() { TablePrimaryKey = this.tablePrimaryKey };
//if (rowList.Count() < (pageNumber * setsPerPage))
// return new LightDataTable(new LightDataRowCollection(rowList)) { TablePrimaryKey = this.tablePrimaryKey };
return new LightDataTable(new LightDataRowCollection(rowList.Skip(this.pageNumber * setsPerPage).Take(setsPerPage).ToList())) { TablePrimaryKey = this.tablePrimaryKey };
}
this is what i did. Normaly you start at 1 but in IList you start with 0. so if you have 152 rows that mean you have 8 paging but in IList you only have 7. hop this can make thing clear for you
Try this one, according to http://www.regextester.com it works for js normaly.
([^{]*?)(?=\})
I was having the same issue in Workbench plus insert query from C# application. In my case using ISO format solve the issue
string value = date.ToString("yyyy-MM-dd HH:mm:ss");
Use the other encode
method in URLEncoder:
URLEncoder.encode(String, String)
The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., UTF-8
). For example:
System.out.println(
URLEncoder.encode(
"urlParameterString",
java.nio.charset.StandardCharsets.UTF_8.toString()
)
);
Here's a comparison of the two:
Entity Type
Message consumption
Use Case
Persistence
Consumer Type
Sample applications
As a checkbox click = a checkbox change the following will also work:
<CheckBox Click="CheckBox_Click" />
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
// ... do some stuff
}
It has the additional advantage of working when IsThreeState="True"
whereas just handling Checked and Unchecked does not.
In TF1, the statement x.assign(1)
does not actually assign the value 1
to x
, but rather creates a tf.Operation
that you have to explicitly run to update the variable.* A call to Operation.run()
or Session.run()
can be used to run the operation:
assign_op = x.assign(1)
sess.run(assign_op) # or `assign_op.op.run()`
print(x.eval())
# ==> 1
(* In fact, it returns a tf.Tensor
, corresponding to the updated value of the variable, to make it easier to chain assignments.)
However, in TF2 x.assign(1)
will now assign the value eagerly:
x.assign(1)
print(x.numpy())
# ==> 1
//just edit menu.xml file
//add icon for item which will change default setting icon
//add sub menus
///menu.xml file
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
android:icon="@drawable/your_icon"
app:showAsAction="always" >
<menu>
<item android:id="@+id/action_menu1"
android:icon="@android:drawable/ic_menu_preferences"
android:title="menu 1" />
<item android:id="@+id/action_menu2"
android:icon="@android:drawable/ic_menu_help"
android:title="menu 2" />
</menu>
</item>
why not simply
public Date(){
data = new int[]{0,0,0};
}
the reason you got the error is because int[] data = ...
declares a new variable and hides the field data
however it should be noted that the contents of the array are already initialized to 0 (the default value of int
)
2 things you need to add to AndroidManifest.xml:
1st: add xmlns:tools="http://schemas.android.com/tools" to manifest tag
<manifest xmlns:android=".........
package="...........
xmlns:tools="http://schemas.android.com/tools">
2nd: Add tools:replace="icon" to application tag
<application
android:icon=.........
android:label=.......
tools:replace="icon">
No, you can't break from a closure in Groovy without throwing an exception. Also, you shouldn't use exceptions for control flow.
If you find yourself wanting to break out of a closure you should probably first think about why you want to do this and not how to do it. The first thing to consider could be the substitution of the closure in question with one of Groovy's (conceptual) higher order functions. The following example:
for ( i in 1..10) { if (i < 5) println i; else return}
becomes
(1..10).each{if (it < 5) println it}
becomes
(1..10).findAll{it < 5}.each{println it}
which also helps clarity. It states the intent of your code much better.
The potential drawback in the shown examples is that iteration only stops early in the first example. If you have performance considerations you might want to stop it right then and there.
However, for most use cases that involve iterations you can usually resort to one of Groovy's find, grep, collect, inject, etc. methods. They usually take some "configuration" and then "know" how to do the iteration for you, so that you can actually avoid imperative looping wherever possible.
For functions that do not have more than 2 parameters, you can pass them without defining your own interface. For example,
class Klass {
static List<String> foo(Integer a, String b) { ... }
}
class MyClass{
static List<String> method(BiFunction<Integer, String, List<String>> fn){
return fn.apply(5, "FooBar");
}
}
List<String> lStr = MyClass.method((a, b) -> Klass.foo((Integer) a, (String) b));
In BiFunction<Integer, String, List<String>>
, Integer
and String
are its parameters, and List<String>
is its return type.
For a function with only one parameter, you can use Function<T, R>
, where T
is its parameter type, and R
is its return value type. Refer to this page for all the interfaces that are already made available by Java.
This worked for me:
import re
thestring = "text1\ntext2\nhttp://url.com/bla1/blah1/\ntext3\ntext4\nhttp://url.com/bla2/blah2/\ntext5\ntext6"
URLless_string = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', thestring)
print URLless_string
Result:
text1
text2
text3
text4
text5
text6
Instead of:
var host = req.get('host');
var origin = req.get('origin');
you can also use:
var host = req.headers.host;
var origin = req.headers.origin;
It's been a while since this question was asked. As of today (matplotlib 2.2.2
) and after some reading and trials, I think the best/proper way is the following:
Matplotlib has a module named ticker
that "contains classes to support completely configurable tick locating and formatting". To modify a specific tick from the plot, the following works for me:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
def update_ticks(x, pos):
if x == 0:
return 'Mean'
elif pos == 6:
return 'pos is 6'
else:
return x
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=25, edgecolor='black')
ax.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
plt.show()
Caveat! x
is the value of the tick and pos
is its relative position in order in the axis. Notice that pos
takes values starting in 1
, not in 0
as usual when indexing.
In my case, I was trying to format the y-axis
of a histogram with percentage values. mticker
has another class named PercentFormatter
that can do this easily without the need to define a separate function as before:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
weights = np.ones_like(data) / len(data)
ax.hist(data, bins=25, weights=weights, edgecolor='black')
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.0, decimals=1))
plt.show()
In this case xmax
is the data value that corresponds to 100%. Percentages are computed as x / xmax * 100
, that's why we fix xmax=1.0
. Also, decimals
is the number of decimal places to place after the point.
If you always need to know the length, and you just need the content of the match rather than the other info, you might as well use re.findall
. Otherwise, if you only need the length sometimes, you can use e.g.
matches = re.finditer(...)
...
matches = tuple(matches)
to store the iteration of the matches in a reusable tuple. Then just do len(matches)
.
Another option, if you just need to know the total count after doing whatever with the match objects, is to use
matches = enumerate(re.finditer(...))
which will return an (index, match)
pair for each of the original matches. So then you can just store the first element of each tuple in some variable.
But if you need the length first of all, and you need match objects as opposed to just the strings, you should just do
matches = tuple(re.finditer(...))
You may well want to use JSON-P instead (see below). First a quick explanation.
The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest
) rather than the standard XMLHttpRequest
that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com
).
To get the JSON data you're requesting, you basically have three options:
If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)
Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax
call (just set dataType
to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:
{"weather": "Dreary start but soon brightening into a fine summer day."}
Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:
jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
That's it. JSON-P is very broadly compatible (because it works via JavaScript script
tags). JSON-P is only for GET
, though, not POST
(again because it works via script
tags).
Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:
A. The browser will send your server a "preflight" message using the OPTIONS
HTTP verb (method). It will contain the various headers it would send with the GET
or POST
as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET
or POST
), and "Access-Control-Request-Headers" (the headers it wants to send).
B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.
C. The browser will look at your response and see whether it's allowed to send you the actual GET
or POST
. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.
D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.
In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):
// Find out what the request is asking for
corsOrigin = get_request_header("Origin")
corsMethod = get_request_header("Access-Control-Request-Method")
corsHeaders = get_request_header("Access-Control-Request-Headers")
if corsOrigin is null or "null" {
// Requests from a `file://` path seem to come through without an
// origin or with "null" (literally) as the origin.
// In my case, for testing, I wanted to allow those and so I output
// "*", but you may want to go another way.
corsOrigin = "*"
}
// Decide whether to accept that request with those headers
// If so:
// Respond with headers saying what's allowed (here we're just echoing what they
// asked for, except we may be using "*" [all] instead of the actual origin for
// the "Access-Control-Allow-Origin" one)
set_response_header("Access-Control-Allow-Origin", corsOrigin)
set_response_header("Access-Control-Allow-Methods", corsMethod)
set_response_header("Access-Control-Allow-Headers", corsHeaders)
if the HTTP request method is "OPTIONS" {
// Done, no body in response to OPTIONS
stop
}
// Process the GET or POST here; output the body of the response
Again stressing that this is pseudo-code.
The accepted answer works great if you just want to use a different context in your partial. However, it doesn't let you reference any of the parent context. To pass in multiple arguments, you need to write your own helper. Here's a working helper for Handlebars 2.0.0
(the other answer works for versions <2.0.0
):
Handlebars.registerHelper('renderPartial', function(partialName, options) {
if (!partialName) {
console.error('No partial name given.');
return '';
}
var partial = Handlebars.partials[partialName];
if (!partial) {
console.error('Couldnt find the compiled partial: ' + partialName);
return '';
}
return new Handlebars.SafeString( partial(options.hash) );
});
Then in your template, you can do something like:
{{renderPartial 'myPartialName' foo=this bar=../bar}}
And in your partial, you'll be able to access those values as context like:
<div id={{bar.id}}>{{foo}}</div>
have you visited this links? http://groups.google.com/group/android-developers/browse_thread/thread/dcaf8b2fdd8a90c4/62d5e2ffef31ebdb
http://moazzam-khan.com/blog/?tag=android-upload-file
http://evgenyg.wordpress.com/2010/05/01/uploading-files-multipart-post-apache/
Concise example of file upload via Java lib Apache Commons
i think you will get help from this
I'm going to throw my two cents into this question and suggest a slightly more verbose extension of elias's answer. As of gcc 4.6, running of gcc -march=native -v -E - < /dev/null
emits an increasing amount of spam in the form of superfluous -mno-*
flags. The following will strip these:
gcc -march=native -v -E - < /dev/null 2>&1 | grep cc1 | perl -pe 's/ -mno-\S+//g; s/^.* - //g;'
However, I have only verified the correctness of this on two different CPUs (an Intel Core2 and AMD Phenom), so I suggest also running the following script to be sure that all of these -mno-*
flags can be safely stripped.
2021 EDIT: There are indeed machines where -march=native
uses a particular -march
value, but must disable some implied ISAs (Instruction Set Architecture) with -mno-*
.
#!/bin/bash
gcc_cmd="gcc"
# Optionally supply path to gcc as first argument
if (($#)); then
gcc_cmd="$1"
fi
with_mno=$(
"${gcc_cmd}" -march=native -mtune=native -v -E - < /dev/null 2>&1 |
grep cc1 |
perl -pe 's/^.* - //g;'
)
without_mno=$(echo "${with_mno}" | perl -pe 's/ -mno-\S+//g;')
"${gcc_cmd}" ${with_mno} -dM -E - < /dev/null > /tmp/gcctest.a.$$
"${gcc_cmd}" ${without_mno} -dM -E - < /dev/null > /tmp/gcctest.b.$$
if diff -u /tmp/gcctest.{a,b}.$$; then
echo "Safe to strip -mno-* options."
else
echo
echo "WARNING! Some -mno-* options are needed!"
exit 1
fi
rm /tmp/gcctest.{a,b}.$$
I haven't found a difference between gcc -march=native -v -E - < /dev/null
and gcc -march=native -### -E - < /dev/null
other than some parameters being quoted -- and parameters that contain no special characters, so I'm not sure under what circumstances this makes any real difference.
Finally, note that --march=native
was introduced in gcc 4.2, prior to which it is just an unrecognized argument.
From Official documents about Re-using Layouts
Although Android offers a variety of widgets to provide small and re-usable interactive elements, you might also need to re-use larger components that require a special layout. To efficiently re-use complete layouts, you can use the tag to embed another layout inside the current layout.
Here is my header.xml file which i can reuse using include tag
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="@string/app_name"
android:textColor="#000000" />
</RelativeLayout>
No I use the tag in XML to add another layout from another XML file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f0f0f0" >
<include
android:id="@+id/header_VIEW"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="@layout/header" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#ffffff"
android:orientation="vertical"
android:padding="5dp" >
</LinearLayout>
@HostListener
is a decorator for the callback/event handler method, so remove the ;
at the end of this line:
@HostListener('click', ['$event.target']);
Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick()
method on the same line for clarity:
import {Component, HostListener, Directive} from 'angular2/core';
@Directive({selector: 'button[counting]'})
class CountClicks {
numberOfClicks = 0;
@HostListener('click', ['$event.target']) onClick(btn) {
console.log("button", btn, "number of clicks:", this.numberOfClicks++);
}
}
@Component({
selector: 'my-app',
template: `<button counting>Increment</button>`,
directives: [CountClicks]
})
export class AppComponent {
constructor() { console.clear(); }
}
Host binding can also be used to listen to global events:
To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)
@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }
Check for the existence by retrieving its object_id:
if object_id('tempdb..##clients_keyword') is not null
drop table ##clients_keyword
Version 2.11+ use the following:
git stash list
git stash apply n
n is the number stash@{12}
If you're on a shared hosting environment you won't have access to the php.ini to make these changes, if you need access, a virtual private server (VPS) or a dedicated server may be a better option if you're confident in managing it yourself.
Alternatively if you create a new file called .htaccess in your root of your web directory (Ensure it doesn't contain a .txt extension if using notepad to create the file) and copy something like this inside.
php_value settingToChange 6000
This will only work if your hosting provider let's you override the certain config value. Best to ask if it doesn't work after trying.
Update answer: Android 8.0 (API level 26) introduces a new feature, Fonts in XML. just use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26.
see this link
Old answer
There are two ways to customize fonts :
!!! my custom font in assets/fonts/iran_sans.ttf
Way 1 :
Refrection Typeface.class ||| best way
call FontsOverride.setDefaultFont() in class extends Application, This code will cause all software fonts to be changed, even Toasts fonts
AppController.java
public class AppController extends Application {
@Override
public void onCreate() {
super.onCreate();
//Initial Font
FontsOverride.setDefaultFont(getApplicationContext(), "MONOSPACE", "fonts/iran_sans.ttf");
}
}
FontsOverride.java
public class FontsOverride {
public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
private static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) {
try {
final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Way 2: use setTypeface
for special view just call setTypeface() to change font.
CTextView.java
public class CTextView extends TextView {
public CTextView(Context context) {
super(context);
init(context,null);
}
public CTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context,attrs);
}
public void init(Context context, @Nullable AttributeSet attrs) {
if (isInEditMode())
return;
// use setTypeface for change font this view
setTypeface(FontUtils.getTypeface("fonts/iran_sans.ttf"));
}
}
FontUtils.java
public class FontUtils {
private static Hashtable<String, Typeface> fontCache = new Hashtable<>();
public static Typeface getTypeface(String fontName) {
Typeface tf = fontCache.get(fontName);
if (tf == null) {
try {
tf = Typeface.createFromAsset(AppController.getInstance().getApplicationContext().getAssets(), fontName);
} catch (Exception e) {
e.printStackTrace();
return null;
}
fontCache.put(fontName, tf);
}
return tf;
}
}
https://forums.oracle.com/forums/thread.jspa?threadID=2150962
Re: SQL DevErr:The Network Adapter could not establish the connection VenCode20 Posted: Dec 7, 2011 3:23 AM in response to: MehulDoshi Reply
This worked for me:
Open the "New/Select Database Connection" dialogue and try changing the connection type setting from "Basic" to "TNS" and then selecting the network alias (for me: "ORCL").
#define ROTATE_RIGHT(x) ( (x>>1) | (x&1?0x8000:0) )
I found this:
http://www.robvanderwoude.com/commandlineswitches.php#Acrobat
Open a PDF file with navigation pane active, zoom out to 50%, and search for and highlight the word "batch":
AcroRd32.exe /A "zoom=50&navpanes=1=OpenActions&search=batch" PdfFile
In ReactJS if you are rendering an array of elements you should have a unique key for each those elements. Normally those kinda situations are creating a list.
Example:
function List() {
const numbers = [0,1,2,3];
return (
<ul>{numbers.map((n) => <li> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
In the above example, it creates a dynamic list using li
tag, so since li
tag does not have a unique key it shows an error.
After fixed:
function List() {
const numbers = [0,1,2,3];
return (
<ul>{numbers.map((n) => <li key={n}> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
Alternative solution when use map when you don't have a unique key (this is not recommended by react eslint ):
function List() {
const numbers = [0,1,2,3,4,4];
return (
<ul>{numbers.map((n,i) => <li key={i}> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
Live example: https://codepen.io/spmsupun/pen/wvWdGwG
1. Create .bat File with backup sqlcmd command
for backup
SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”
for restore
SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
2. Run the the bat file with WPF/C# code
FileInfo file = new FileInfo("DB\\batfile.bat");
Process process = new Process();
process.StartInfo.FileName = file.FullName;
process.StartInfo.Arguments = @"-X";
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = false; //Changed Line
process.StartInfo.RedirectStandardOutput = true; //Changed Line
process.Start();
string output = process.StandardOutput.ReadToEnd(); //Changed Line
process.WaitForExit(); //Moved Line
You can use the sort
command:
sort -k2 -n yourfile
-n
,--numeric-sort
compare according to string numerical value
For example:
$ cat ages.txt
Bob 12
Jane 48
Mark 3
Tashi 54
$ sort -k2 -n ages.txt
Mark 3
Bob 12
Jane 48
Tashi 54
If you want to load a cmsblock into your template/blockfile/model etc. You can do this as followed. This will render any variables places in the cmsblock
$block = Mage::getModel('cms/block')
->setStoreId(Mage::app()->getStore()->getId())
->load('identifier');
$var = array('variable' => 'value', 'other_variable' => 'other value');
/* This will be {{var variable}} and {{var other_variable}} in your CMS block */
$filterModel = Mage::getModel('cms/template_filter');
$filterModel->setVariables($var);
echo $filterModel->filter($block->getContent());
let's suppose
x=50
y=5
then
z=$((x/y))
this will work properly . But if you want to use / operator in case statements than it can't resolve it. In that case use simple strings like div or devide or something else. See the code
The class Doctrine\ORM\EntityRepository
implements Doctrine\Common\Collections\Selectable
API.
The Selectable
interface is very flexible and quite new, but it will allow you to handle comparisons and more complex criteria easily on both repositories and single collections of items, regardless if in ORM or ODM or completely separate problems.
This would be a comparison criteria as you just requested as in Doctrine ORM 2.3.2
:
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('prize', 200));
$result = $entityRepository->matching($criteria);
The major advantage in this API is that you are implementing some sort of strategy pattern here, and it works with repositories, collections, lazy collections and everywhere the Selectable
API is implemented.
This allows you to get rid of dozens of special methods you wrote for your repositories (like findOneBySomethingWithParticularRule
), and instead focus on writing your own criteria classes, each representing one of these particular filters.
I would use the Apache Commons Lang library. It has a class called StringUtils that is useful for all sorts of String operations. For checking if a String is not all whitespaces, you can use the following:
StringUtils.isBlank(<your string>)
Here is the reference: StringUtils.isBlank
SQL Locator (free) has worked great for me. It comes with a lot of options and it's fairly easy to use.
try this
$("label").html(your value);
or $("label").text(your value);
Similar as shown and mentioned:
Notes: Take into consideration that Cells will change their color (only) after the DataGridView Control is Visible. Therefore one practical solution would be using the:
VisibleChanged Event
In case you wish to keep your style when creating new Rows; also subscribe the:
RowsAdded Event
Example bellow:
///<summary> Instantiate the DataGridView Control. </summary>
private DataGridView dgView = new DataGridView;
///<summary> Method to configure DataGridView Control. </summary>
private void DataGridView_Configuration()
{
// In this case the method just contains the VisibleChanged event subscription.
dgView.VisibleChanged += DgView_VisibleChanged;
// Uncomment line bellow in case you want to keep the style when creating new rows.
// dgView.RowsAdded += DgView_RowsAdded;
}
///<summary> The actual Method that will re-design (Paint) DataGridView Cells. </summary>
private void DataGridView_PaintCells()
{
int nrRows = dgView.Rows.Count;
int nrColumns = dgView.Columns.Count;
Color green = Color.LimeGreen;
// Iterate over the total number of Rows
for (int row = 0; row < nrRows; row++)
{
// Iterate over the total number of Columns
for (int col = 0; col < nrColumns; col++)
{
// Paint cell location (column, row)
dgView[col, row].Style.BackColor = green;
}
}
}
///<summary> The DataGridView VisibleChanged Event. </summary>
private void DataGridView_VisibleChanged(object sender, EventArgs e)
{
DataGridView_PaintCells();
}
/// <summary> Occurrs when a new Row is Created. </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridView_PaintCells();
}
Finally: Just call the DataGridView_Configuration() (method)
i.e: Form Load Event.
The more exact way applied to all Booostrap objects using standard classes only would be to not set top and bottom margins (as image can inherit these from parent), so I am always using:
.text-center .img-responsive {
margin-left: auto;
margin-right: auto;
}
I have also made a Gist for that, so if any changes will apply because of any bugs, update version will be always here: https://gist.github.com/jdrda/09a38bf152dd6a8aff4151c58679cc66
I did a bit of research regarding this & I have summarised my findings so far in below table
So the recommended solution is to write a a server side script to parse the Accept-Language
header & pass it to client for setting the language of the website. It's weird that why the server would be needed to detect the language preference of client but that's how it is as of now There are other various hacks available to detect the language but reading the Accept-Language
header is the recommended solution as per my understanding.
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
Named exports:
Let's say you create a file called utils.js
, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:
export function add(x, y) {
return x + y
}
export function mutiply(x, y) {
return x * y
}
Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:
import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.
Or if you prefer, place the entire module's contents under a common namespace:
import * as utils from './utils.js';
...
utils.multiply(2,3)
Default exports:
If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js
, with only one function that logs out whatever argument it's called with:
export default function log(message) {
console.log(message);
}
This can now be used like this:
import log from './log.js';
...
log('test') // Would print 'test' in the console.
You don't have to call it log
when you import it, you could actually call it whatever you want:
import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.
Combined:
A module can have both a default export (max 1), and named exports (imported either one by one, or using *
with an alias). React actually has this, consider:
import React, { Component, PropTypes } from 'react';
I found a way to do it (dont know if it is the best but it works)
string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
I hope this can be usefull for someone =) (and post here any errors)
If anyone needs to do this dynamically:
const keys = Object.keys(jsonObject);
keys.forEach((key) => {
// CREATE A NEW KEY HERE
var newKey = key.replace(' ', '_');
jsonObject[newKey] = jsonObject[key];
delete jsonObject[key];
});
jsonObject
will now have the new keys.
IMPORTANT:
If your key is not changed by the replace
function, it will just take it out of the array. You may want to put some if
statements in there.
try
sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php
this command fixed the issue having on my ubuntu 14.04.
i had a similar requirement on 1 of the projects where you had to send huge number of emails each day, and the client wanted complete control over html templates for different types of emails.
due to the large number of emails to be sent, performance was a primary concern.
what we came up with was static content in sql server where you save entire html template mark up (along with place holders, like [UserFirstName], [UserLastName] which are replaced with real data at run time) for different types of emails
then we loaded this data in asp.net cache - so we dont read the html templates over and over again - but only when they are actually changed
we gave the client a WYSIWYG editor to modify these templates via a admin web form. whenever updates were made, we reset asp.net cache.
and then we had a seperate table for email logs - where every email to be sent was logged. this table had fields called emailType, emailSent and numberOfTries.
we simply ran a job every 5 minutes for important email types (like new member sign up, forgot password) which need to be sent asap
we ran another job every 15 minutes for less important email types (like promotion email, news email, etc)
this way you dont block your server sending non stop emails and you process mails in batch. once an email is sent you set the emailSent field to 1.
For all practical purposes, the first thing you should be worried about is CHANGING YOUR PASSWORDS! It's not clear from your question whether your git repository is entirely local or whether you have a remote repository elsewhere yet; if it is remote and not secured from others you have a problem. If anyone has cloned that repository before you fix this, they'll have a copy of your passwords on their local machine, and there's no way you can force them to update to your "fixed" version with it gone from history. The only safe thing you can do is change your password to something else everywhere you've used it.
With that out of the way, here's how to fix it. GitHub answered exactly that question as an FAQ:
Note for Windows users: use double quotes (") instead of singles in this command
git filter-branch --index-filter \
'git update-index --remove PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA' <introduction-revision-sha1>..HEAD
git push --force --verbose --dry-run
git push --force
Update 2019:
This is the current code from the FAQ:
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" \
--prune-empty --tag-name-filter cat -- --all
git push --force --verbose --dry-run
git push --force
Keep in mind that once you've pushed this code to a remote repository like GitHub and others have cloned that remote repository, you're now in a situation where you're rewriting history. When others try pull down your latest changes after this, they'll get a message indicating that the changes can't be applied because it's not a fast-forward.
To fix this, they'll have to either delete their existing repository and re-clone it, or follow the instructions under "RECOVERING FROM UPSTREAM REBASE" in the git-rebase manpage.
Tip: Execute git rebase --interactive
In the future, if you accidentally commit some changes with sensitive information but you notice before pushing to a remote repository, there are some easier fixes. If you last commit is the one to add the sensitive information, you can simply remove the sensitive information, then run:
git commit -a --amend
That will amend the previous commit with any new changes you've made, including entire file removals done with a git rm
. If the changes are further back in history but still not pushed to a remote repository, you can do an interactive rebase:
git rebase -i origin/master
That opens an editor with the commits you've made since your last common ancestor with the remote repository. Change "pick" to "edit" on any lines representing a commit with sensitive information, and save and quit. Git will walk through the changes, and leave you at a spot where you can:
$EDITOR file-to-fix
git commit -a --amend
git rebase --continue
For each change with sensitive information. Eventually, you'll end up back on your branch, and you can safely push the new changes.
I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:
shake.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100" <!-- how long the animation lasts -->
android:fromDegrees="-5" <!-- how far to swing left -->
android:pivotX="50%" <!-- pivot from horizontal center -->
android:pivotY="50%" <!-- pivot from vertical center -->
android:repeatCount="10" <!-- how many times to swing back and forth -->
android:repeatMode="reverse" <!-- to make the animation go the other way -->
android:toDegrees="5" /> <!-- how far to swing right -->
Class.java
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);
This is just one way of doing what you want, there may be better methods out there.
As all answers posted above are well explained, I want to add something which I faced today.
When you export something using exports then you have to use it with variable. Like,
File1.js
exports.a = 5;
In another file
File2.js
const A = require("./File1.js");
console.log(A.a);
and using module.exports
File1.js
module.exports.a = 5;
In File2.js
const A = require("./File1.js");
console.log(A.a);
and default module.exports
File1.js
module.exports = 5;
in File2.js
const A = require("./File2.js");
console.log(A);
I think the variable name 'self' should not be used this way anymore, since modern browsers provide a global variable self
pointing to the global object of either a normal window or a WebWorker.
To avoid confusion and potential conflicts, you can write var thiz = this
or var that = this
instead.
Here is my view on how to do proper singletons (and other non-trivial static objects): https://github.com/alex4747-pub/proper_singleton
Summary:
Be carefull that the page does not contain any empty component which has "required" attribute as "true" before your selectOneMenu component running.
If you use a component such as
<p:inputText label="Nm:" id="id_name" value="#{ myHelper.name}" required="true"/>
then,
<p:selectOneMenu .....></p:selectOneMenu>
and forget to fill the required component, ajax listener of selectoneMenu cannot be executed.
My problem was unrelated to processData
. It was because I sent a function that cannot be called later with apply
because it did not have enough arguments. Specifically I shouldn't have used alert
as the error
callback.
$.ajax({
url: csvApi,
success: parseCsvs,
dataType: "json",
timeout: 5000,
processData: false,
error: alert
});
See this answer for more information on why that can be a problem: Why are certain function calls termed "illegal invocations" in JavaScript?
The way I was able to discover this was by adding a console.log(list[ firingIndex ])
to jQuery so I could track what it was firing.
This was the fix:
function myError(jqx, textStatus, errStr) {
alert(errStr);
}
$.ajax({
url: csvApi,
success: parseCsvs,
dataType: "json",
timeout: 5000,
error: myError // Note that passing `alert` instead can cause a "jquery.js:3189 Uncaught TypeError: Illegal invocation" sometimes
});
Most commands/programs return a 0 on success and some other value, called errorlevel
, to signal an error.
You can check for this in you batch for example by:
call <THE_COMMAND_HERE>
if %ERRORLEVEL% == 0 goto :next
echo "Errors encountered during execution. Exited with status: %errorlevel%"
goto :endofscript
:next
echo "Doing the next thing"
:endofscript
echo "Script complete"
open my Computer ==>
right click inside my computer and select properties ==>
Click on Advanced System Settings ==>
Environment Variables ==>
from the System Variables box select "PATH" ==>
Edit... ==>
then add this at the end of whatever you find their
;C:\PostgreSQL\9.2\bin; C:\PostgreSQL\9.2\lib
after that continue to click OK
open cmd/command prompt.... open psql in command prompt with this
psql -U username database
eg. i have a database name FRIENDS and a user MEE.. it will be
psql -U MEE FRIENDS
you will be then prompted to give the password of the user in question. Thanks
While a bit more cryptic than join
, you can also multiply the array by a string.
@arr * " "
import java.util.ArrayList;
public class TestClass {
public static void main(String[] args) {
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> List_1 = new ArrayList<String>();
List_1.add("1");
List_1.add("2");
listOLists.add(List_1);
ArrayList<String> List_2 = new ArrayList<String>();
List_2.add("4");
List_2.add("5");
List_2.add("10");
List_2.add("11");
listOLists.add(List_2);
for (int i = 0; i < listOLists.size(); i++) {
System.out.print("list " + i + " :");
for (int j = 0; j < listOLists.get(i).size(); j++) {
System.out.print(listOLists.get(i).get(j) + " ;");
}
System.out.println();
}
}
}
Since you're using Spring, stick with Spring, don't hack it yourself like the other post posits.
The Spring manual says:
You shouldn't interact directly with the HttpSession for security purposes. There is simply no justification for doing so - always use the SecurityContextHolder instead.
The suggested best practice for accessing the session is:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
The key here is that Spring and Spring Security do all sorts of great stuff for you like Session Fixation Prevention. These things assume that you're using the Spring framework as it was designed to be used. So, in your servlet, make it context aware and access the session like the above example.
If you just need to stash some data in the session scope, try creating some session scoped bean like this example and let autowire do its magic. :)
OFFSET
is nothing but a keyword to indicate starting cursor in table
SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)
you would get the same result form
SELECT column FROM table LIMIT 8, 18
visual representation (R
is one record in the table in some order)
OFFSET LIMIT rest of the table
__||__ _______||_______ __||__
/ \ / \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
\________________/
||
your result
Starting with Bootstrap v3.3.0 you can use .media-left
and .media-body
<div class="media">
<span class="media-left">
<img src="../site/img/success32.png" alt="...">
</span>
<div class="media-body">
<h3 class="media-heading">Experience</h3>
...
</div>
</div>
Documentation: https://getbootstrap.com/docs/3.3/components/#media
Have a look at: http://www.javaspecialists.eu/archive/Issue068.html and http://www.javaspecialists.eu/archive/Issue105.html
Do the same tests in your environment and check if newer JDK or your Java implementation do some type of string operation better with String
or better with StringBuilder
.
@TonyO'Hagan is comprehrensive shelljs
answer, but, I would like to highlight the synchronous version of his answer:
var shell = require('shelljs');
var output = shell.exec('netstat -rn', {silent:true}).output;
console.log(output);
You can basically switch the class using [ngClass]
for example
<button [ngClass]="{'active': selectedItem === 'item1'}" (click)="selectedItem = 'item1'">Button One</button>
<button [ngClass]="{'active': selectedItem === 'item2'}" (click)="selectedItem = 'item2'">Button Two</button>
private DataTable CreateDataTable(IList<T> item)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in item)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
Use eval()
instead of ast.literal_eval()
if the input is trusted (which it is in your case).
raw_data = userfile.read().split('\n')
for a in raw_data :
print a
btc_history.append(eval(a))
This works for me in Python 3.6.0
Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:
<?php
/////// SYNTAX ERROR CHECK ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');
//replace "pageToTest.php" with the file path that you want to test.
include('pageToTest.php');
?>
Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.
I'm not going to get in a debate about whether or not this method should be used, but this will let you set specific css attributes for IE8-9 only (note: it is not a selector, so a bit different than what you asked):
Use '\0/' after each css declaration, so:
#nav li ul {
left: -39px\0/ !important;
}
And to build off another answer, you can do this to assign variou styles to IE6, IE7, and IE8:
#nav li ul {
*left: -7px !important; /* IE 7 (IE6 also uses this, so put it first) */
_left: -6px !important; /* IE 6 */
left: -8px\0/ !important; /* IE 8-9 */
}
source: http://dimox.net/personal-css-hacks-for-ie6-ie7-ie8/
This script will help you switch Gopaths. https://github.com/buffonomics/goswitch
Looking at current hacky solutions in here, I feel I have to describe a proper solution after all.
First, you need to install the cygwin package ca-certificates
via Cygwin's setup.exe to get the certificates.
Do NOT use curl or similar hacks to download certificates (as a neighboring answer advices) because that's fundamentally insecure and may compromise the system.
Second, you need to tell wget where your certificates are, since it doesn't pick them up by default in Cygwin environment. If you can do that either with the command-line parameter --ca-directory=/usr/ssl/certs
(best for shell scripts) or by adding ca_directory = /usr/ssl/certs
to ~/.wgetrc
file.
You can also fix that by running ln -sT /usr/ssl /etc/ssl
as pointed out in another answer, but that will work only if you have administrative access to the system. Other solutions I described do not require that.
Just to show an example of how to dynamically add the "Content-type" header to every POST request. In may case I'm passing POST params as query string, that is done using the transformRequest. In this case its value is application/x-www-form-urlencoded.
// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
$http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}
Then from the interceptor in the request method before return the config object
// if header['Content-type'] is a POST then add data
'request': function (config) {
if (
angular.isDefined(config.headers['Content-Type'])
&& !angular.isDefined(config.data)
) {
config.data = '';
}
return config;
}
If you want a CompletableFuture way you could have a method like
public MyResponseObject retrieveDataFromEndpoint() {
CompletableFuture<MyResponseObject> endpointCall
= CompletableFuture.supplyAsync(() ->
yourRestService.callEnpoint(withArg1, withArg2));
try {
return endpointCall.get(10, TimeUnit.MINUTES);
} catch (TimeoutException
| InterruptedException
| ExecutionException e) {
throw new RuntimeException("Unable to fetch data", e);
}
}
If you're using spring, you could annotate the method with a @Retryable
so that it retries the method three times if an exception is thrown.
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;
foreach($input as $data) {
$weight = intval($data['Weight']);
if($weight <= $min ) {
$min = $weight ;
}
if($weight > $max ) {
$max = $weight ;
}
}
echo " min = $min and max = $max \n " ;
mock.patch
is a very very different critter than mock.Mock
. patch
replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:
>>> class MyClass(object):
... def __init__(self):
... print 'Created MyClass@{0}'.format(id(self))
...
>>> def create_instance():
... return MyClass()
...
>>> x = create_instance()
Created MyClass@4299548304
>>>
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
... MyClass.return_value = 'foo'
... return create_instance()
...
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
... print MyClass
... return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>
patch
replaces MyClass
in a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.
mock.patch
is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock
instances are clearer and are preferred. If your self.sut.something
method created an instance of MyClass
instead of receiving an instance as a parameter, then mock.patch
would be appropriate here.
When the callee throws an exception i.e. void showfile() throws java.io.IOException the caller should handle it or throw it again.
And also learn naming conventions. A class name should start with a capital letter.
Let's just say you have 3 buttons:
<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">
To style the disabled button you can use the following css:
input[type="button"]:disabled{
color:#000;
}
This will only affect the button which is disabled.
To stop the color changing when hovering you can use this too:
input[type="button"]:disabled:hover{
color:#000;
}
You can also avoid this by using a css-reset.
It's worth pointing out that if you have multiple Gmail accounts, you may want to use the URL approach because you can customize which account to compose from.
e.g.
https://mail.google.com/mail/u/0/#inbox?compose=new
https://mail.google.com/mail/u/1/#inbox?compose=new
Or if you know the email address you are sending from, replace the numeric index with the email address:
https://mail.google.com/mail/u/[email protected]/#inbox?compose=new
You could actually put the newlines to good use by reading the entire file into memory as a single long string and then use them to split that into the list of grades.
with open("grades.dat") as input:
grades = [line.split(",") for line in input.read().splitlines()]
etc...
This might give you some ideas
.NET C# View Model
public class DepartmentViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
.NET C# Web Api Controller
public class DepartmentController : BaseApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
var sms = Ctx.Departments;
var vms = new List<DepartmentViewModel>();
foreach (var sm in sms)
{
var vm = new DepartmentViewModel()
{
Id = sm.Id,
Name = sm.DepartmentName
};
vms.Add(vm);
}
return Request.CreateResponse(HttpStatusCode.OK, vms);
}
}
Angular Controller:
$http.get('/api/department').then(
function (response) {
$scope.departments = response.data;
},
function (response) {
toaster.pop('error', "Error", "An unexpected error occurred.");
}
);
$http.get('/api/getTravelerInformation', { params: { id: $routeParams.userKey } }).then(
function (response) {
$scope.request = response.data;
$scope.travelerDepartment = underscoreService.findWhere($scope.departments, { Id: $scope.request.TravelerDepartmentId });
},
function (response) {
toaster.pop('error', "Error", "An unexpected error occurred.");
}
);
Angular Template:
<div class="form-group">
<label>Department</label>
<div class="left-inner-addon">
<i class="glyphicon glyphicon-hand-up"></i>
<select ng-model="travelerDepartment"
ng-options="department.Name for department in departments track by department.Id"
ng-init="request.TravelerDepartmentId = travelerDepartment.Id"
ng-change="request.TravelerDepartmentId = travelerDepartment.Id"
class="form-control">
<option value=""></option>
</select>
</div>
</div>
display:
is not transitionable. You'll probably need to use jQuery to do what you want to do.
Syncfusion Essential XlsIO can do this. It has no dependency on Microsoft office and also has specific support for different platforms.
Code sample:
//Creates a new instance for ExcelEngine.
ExcelEngine excelEngine = new ExcelEngine();
//Loads or open an existing workbook through Open method of IWorkbooks
IWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);
//To-Do some manipulation|
//To-Do some manipulation
//Set the version of the workbook.
workbook.Version = ExcelVersion.Excel2013;
//Save the workbook in file system as xlsx format
workbook.SaveAs(outputFileName);
The whole suite of controls is available for free through the community license program if you qualify (less than 1 million USD in revenue). Note: I work for Syncfusion.
set echo off
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
If you have YAML that conforms to the YAML 1.2 specification (released 2009) then you should use ruamel.yaml (disclaimer: I am the author of that package). It is essentially a superset of PyYAML, which supports most of YAML 1.1 (from 2005).
If you want to be able to preserve your comments when round-tripping, you certainly should use ruamel.yaml.
Upgrading @Jon's example is easy:
import ruamel.yaml as yaml
with open("example.yaml") as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
Use safe_load()
unless you really have full control over the input, need it (seldom the case) and know what you are doing.
If you are using pathlib Path
for manipulating files, you are better of using the new API ruamel.yaml provides:
from ruamel.yaml import YAML
from pathlib import Path
path = Path('example.yaml')
yaml = YAML(typ='safe')
data = yaml.load(path)
In following code, we don't need to hard code the credentials.
service.Proxy = WebRequest.DefaultWebProxy;
service.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
service.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
If you're getting this, you may have forgotten to put #include <thread>
at the beginning of your file. OP's signature seems like it should work.
In regards to problems with Qt4, I couldn't use the qmake moc option mentioned above. But that wasn't the problem anyway. I had the following code in the class definition:
class ScreenWidget : public QGLWidget
{
Q_OBJECT // must include this if you use Qt signals/slots
...
};
I had to remove the line "Q_OBJECT" because I had no signals or slots defined.
Just as a tidbit:
Even (
((A)null)
instanceof A)
will return false
.
(If typecasting null
seems surprising, sometimes you have to do it, for example in situations like this:
public class Test
{
public static void test(A a)
{
System.out.println("a instanceof A: " + (a instanceof A));
}
public static void test(B b) {
// Overloaded version. Would cause reference ambiguity (compile error)
// if Test.test(null) was called without casting.
// So you need to call Test.test((A)null) or Test.test((B)null).
}
}
So Test.test((A)null)
will print a instanceof A: false
.)
P.S.: If you are hiring, please don't use this as a job interview question. :D
You can use the Web API FontFace constructor (also Typescript) without need of CSS:
export async function loadFont(fontFamily: string, url: string): Promise<void> {
const font = new FontFace(fontFamily, `local(${fontFamily}), url(${url})`);
// wait for font to be loaded
await font.load();
// add font to document
document.fonts.add(font);
// enable font with CSS class
document.body.classList.add("fonts-loaded");
}
import ComicSans from "./assets/fonts/ComicSans.ttf";
loadFont("Comic Sans ", ComicSans).catch((e) => {
console.log(e);
});
Declare a file font.ts
with your modules (TS only):
declare module "*.ttf";
declare module "*.woff";
declare module "*.woff2";
If TS cannot find FontFace type as its still officially WIP, add this declaration to your project. It will work in your browser, except for IE.