You can also set up a mime type for application/JavaScript to run as PHP, .NET, Java, or whatever language you're using. I've done this for dynamic CSS files in the past.
I'm under the impression that some enterprises (e.g.: JackBe) put encrypted JavaScript code inside *.gif files, rather than JS files, as an additional measure of obfuscation.
I used Refractor to recover my script/code from dll file.
Use the following syntax:
$ for i in {01..05}; do echo "$i"; done
01
02
03
04
05
Disclaimer: Leading zeros only work in >=bash-4
.
If you want to use printf
, nothing prevents you from putting its result in a variable for further use:
$ foo=$(printf "%02d" 5)
$ echo "${foo}"
05
use the arguments -Xms<memory>
-Xmx<memory>
. Use M
or G
after the numbers for indicating Megs and Gigs of bytes respectively. -Xms
indicates the minimum and -Xmx
the maximum.
http://anandsekar.github.io/exporting-the-private-key-from-a-jks-keystore/
public class ExportPrivateKey {
private File keystoreFile;
private String keyStoreType;
private char[] password;
private String alias;
private File exportedFile;
public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
try {
Key key=keystore.getKey(alias,password);
if(key instanceof PrivateKey) {
Certificate cert=keystore.getCertificate(alias);
PublicKey publicKey=cert.getPublicKey();
return new KeyPair(publicKey,(PrivateKey)key);
}
} catch (UnrecoverableKeyException e) {
} catch (NoSuchAlgorithmException e) {
} catch (KeyStoreException e) {
}
return null;
}
public void export() throws Exception{
KeyStore keystore=KeyStore.getInstance(keyStoreType);
BASE64Encoder encoder=new BASE64Encoder();
keystore.load(new FileInputStream(keystoreFile),password);
KeyPair keyPair=getPrivateKey(keystore,alias,password);
PrivateKey privateKey=keyPair.getPrivate();
String encoded=encoder.encode(privateKey.getEncoded());
FileWriter fw=new FileWriter(exportedFile);
fw.write(“—–BEGIN PRIVATE KEY—–\n“);
fw.write(encoded);
fw.write(“\n“);
fw.write(“—–END PRIVATE KEY—–”);
fw.close();
}
public static void main(String args[]) throws Exception{
ExportPrivateKey export=new ExportPrivateKey();
export.keystoreFile=new File(args[0]);
export.keyStoreType=args[1];
export.password=args[2].toCharArray();
export.alias=args[3];
export.exportedFile=new File(args[4]);
export.export();
}
}
You can't do what I think you're asking to do.
The only privileges you can grant on procedures are EXECUTE and DEBUG.
If you want to allow user B to create a procedure in user A schema, then user B must have the CREATE ANY PROCEDURE privilege. ALTER ANY PROCEDURE and DROP ANY PROCEDURE are the other applicable privileges required to alter or drop user A procedures for user B. All are wide ranging privileges, as it doesn't restrict user B to any particular schema. User B should be highly trusted if granted these privileges.
EDIT:
As Justin mentioned, the way to give execution rights to A for a procedure owned by B:
GRANT EXECUTE ON b.procedure_name TO a;
Another option is:
Pointing the project at your installed JRE might be a better choice than renaming your JRE to match the old project code.
<input ... checked />
<input ... checked="checked" />
Those are equally valid. And in JavaScript:
input.checked = true;
input.setAttribute("checked");
input.setAttribute("checked","checked");
The $
symbol simply invokes the jQuery library's selector functionality. So $("#Text")
returns the jQuery object for the Text
div
which can then be modified.
You can create Shortcut key in Sublime Text Editor using Preferences -> Key Bindings
Now add below code on right-side of Key Bindings within square bracket []
{
"keys": ["ctrl+shift+c"],
"command": "insert_snippet",
"args": { "contents": "echo \"<pre>\";\nprint_r(${0:\\$variable_to_debug});\necho \"</pre>\";\ndie();\n" }
}
Enjoy your ctrl+shift+c shortcut as a Pretty Print of PHP.
Add this on to the end of it:
var array = $("#hidAll").html();
x = array.split(',');
key=s="";
for (i=0; i<x.length; i++) {
oldkey = key;
key = x[i].split('|')[0];
if (oldkey==key) s+='!';
else s+=',\n'+key+'|';
s+=x[i].split('|')[1];
}
s = s.substring(1);
$('#hidAll').html(a);
Use this code for read file with all type of extension file.
string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");
To find the number of days between two dates, you use:
DATEDIFF ( d, startdate , enddate )
Accepted answer not working for me, try this :
^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,6}$
Visit this Unit Test Cases for validation.
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
(function(){
var i = 0;
function stop(){
clearTimeout(i);
}
function start(){
i = setTimeout( timed, 1000 );
}
function timed(){
document.getElementById("input").value++;
start();
}
window.stop = stop;
window.start = start;
})()
<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57" ondragstart="return false;" ondrop="return false;">
Input filed only accept numbers, But it's temporary fix only.
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
Finally got it working after 1 hour struggle.
This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .
For a new WebApi 2 application example:
Postman (looks exactly, like below):
POST http://localhost:61402/api/values [Send]
Body
(*) raw JSON (application/json) v
"{ \"key1\": \"value1\" }"
The port 61402 or url /api/values above, may be different for you.
ValuesController.cs
using Newtonsoft.Json;
// ..
// POST api/values
[HttpPost]
public object Post([FromBody]string jsonString)
{
// add reference to Newtonsoft.Json
// using Newtonsoft.Json;
// jsonString to myJsonObj
var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
// value1 is myJsonObj[key1]
var valueOfkey1 = myJsonObj["key1"];
return myJsonObj;
}
All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.
I was facing same issue and I just started app with new port and everything looks good.
ng serve --port 4201
adb shell
su
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
This assumes your /system is yaffs2 and that it's at /dev/block/mtdblock3 the easier/better way to do this on most Android phones is:
adb shell
su
mount -o remount,rw /system
Done. This just says remount /system read-write, you don't have to specify filesystem or mount location.
Just use another container to wrap last two divs. Don't forget to use CSS prefixes.
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
height: 100px;_x000D_
background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
display: flex;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
background-color: red;_x000D_
flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
background-color: blue;_x000D_
flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle">1</div>_x000D_
<div id="anotherContainer">_x000D_
<div id="productShowcaseDetail">2</div>_x000D_
<div id="productShowcaseThumbnailContainer">3</div>_x000D_
</div>_x000D_
</div>
_x000D_
Run ps aux | grep nodejs
, find the PID of the process you're looking for, then run kill
starting with SIGTERM (kill -15 25239
). If that doesn't work then use SIGKILL instead, replacing -15
with -9
.
If you only have one camera, or you don't care which camera is the correct one, then use "-1" as the index. Ie for your example capture = cv.CaptureFromCAM(-1)
.
Also for pretty Json on console:
json.dumps(response.json(), indent=2)
possible to use dumps with indent. (Please import json)
To avoid division by zero!
function x = normalize(x, eps)
% Normalize vector `x` (zero mean, unit variance)
% default values
if (~exist('eps', 'var'))
eps = 1e-6;
end
mu = mean(x(:));
sigma = std(x(:));
if sigma < eps
sigma = 1;
end
x = (x - mu) / sigma;
end
Generally i prefer the lambda syntax with LINQ, but Join
is one example where i prefer the query syntax - purely for readability.
Nonetheless, here is the equivalent of your above query (i think, untested):
var query = db.Categories // source
.Join(db.CategoryMaps, // target
c => c.CategoryId, // FK
cm => cm.ChildCategoryId, // PK
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.
Use $HTTP_RAW_POST_DATA
instead of $_POST
.
It will give you POST data as is.
You will be able to decode it using json_decode()
later.
IntelliJ sometime gets confused after importing maven projects and then changing poms externally or generating sources outside IntelliJ.
You might want to try a maven->force reimport from within intellij on the project root
Bootstrap Tokenfield seems good too: http://sliptree.github.io/bootstrap-tokenfield/
As of now, Installing the apks to the /system
directory seems to be working using adb push
command.
Some hidden service was automatically remounting the /system
directory in read-only
mode.
Any way I was able to install the Play store in a normal virtual-machine ( Ie, non-Google-Api virtual machine ) by simply mounting the system.img
file from my OS and by copying over the files.
# To be executed as root user in your Unix based OS
mkdir sys_temp
mount $SDK_HOME/system-images/android-23/default/x86/system.img sys_temp -o loop
cp Phonesky.apk GmsCore.apk GoogleLoginService.apk GoogleServicesFramework.apk ./sys_temp/priv-app/
umount sys_temp
rmdir sys_temp
The APK files can be pulled from any real Android device running Google Apps by using adb pull
command
[ To get the exact path of the apks, we can use command
pm list packages -f
inside the adb shell ]
I agree and found this file under xammp-control the type of file is configuration. When I changed it to 8080 it worked automagically!
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)Set the title to empty string using builder.
Builder builder = new AlertDialog.Builder(context);
builder.setTitle("");
...
builder.show();
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
Try the following steps:
Make sure you have connectivity (you can browse) (This kind of error is usually due to connectivity with Internet)
Download Maven and unzip it
Create a JAVA_HOME
System Variable
Create an M2_HOME
System Variable
Add %JAVA_HOME%\bin;%M2_HOME%\bin;
to your PATH
variable
Open a command window cmd
. Check: mvn -v
If you have a proxy, you will need to configure it
http://maven.apache.org/guides/mini/guide-proxies.html
Make sure you have .m2/repository
(erase all the folders and files below)
If you are going to use Eclipse, You will need to create the settings.xml
Maven plugin in Eclipse - Settings.xml file is missing
You can see more detail in
http://maven.apache.org/ref/3.2.5/maven-settings/settings.html
while true ; do
...
if [ something ]; then
break
fi
done
Would this help?
final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));
Today I also got this error Cordova : Requirements check failed for JDK 1.8 or greater
in my Mac OS while build Ionic App when I run command ionic cordova build --release android
via terminal.
Below command resolve my issue :-
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home"
Hope it will help someone in future!
File directory = new File("Enter any directory name or file name"); boolean isDirectory = directory.isDirectory(); if (isDirectory) { // It returns true if directory is a directory. System.out.println("the name you have entered is a directory : " + directory); //It returns the absolutepath of a directory. System.out.println("the path is " + directory.getAbsolutePath()); } else { // It returns false if directory is a file. System.out.println("the name you have entered is a file : " + directory); //It returns the absolute path of a file. System.out.println("the path is " + file.getParent()); }
//R stands for ROW and C stands for COLUMN:
//i stands for ROW and j stands for COLUMN:
#include<stdio.h>
int main(){
int M[100][100];
int R,C,i,j;
printf("Please enter how many rows you want:\n");
scanf("%d",& R);
printf("Please enter how column you want:\n");
scanf("%d",& C);
printf("Please enter your matrix:\n");
for(i = 0; i < R; i++){
for(j = 0; j < C; j++){
scanf("%d", &M[i][j]);
}
printf("\n");
}
for(i = 0; i < R; i++){
for(j = 0; j < C; j++){
printf("%d\t", M[i][j]);
}
printf("\n");
}
getch();
return 0;
}
For MongoDB shell version 3.0.5 insert the following command in the shell:
db.adminCommand('listDatabases')
or alternatively:
db.getMongo().getDBNames()
I'd use a couple of tiny images. Would look better too.
Alternatively, you can try the Character Map utility that comes with Windows or try looking here.
Another solution I've seen is to use the Wingdings font for symbols. That has a lot fo arrows.
I think the XML format can be so diverse that it's impossible to write a code that could do this without a very strict defined XML format. Here is what I mean:
<persons>
<person>
<name>Koen Bok</name>
<age>26</age>
</person>
<person>
<name>Plutor Heidepeen</name>
<age>33</age>
</person>
</persons>
Would become
{'persons': [
{'name': 'Koen Bok', 'age': 26},
{'name': 'Plutor Heidepeen', 'age': 33}]
}
But what would this be:
<persons>
<person name="Koen Bok">
<locations name="defaults">
<location long=123 lat=384 />
</locations>
</person>
</persons>
See what I mean?
Edit: just found this article: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
(1) add layer group and array to hold layers and reference to layers as global variables:
var search_group = new L.LayerGroup(); var clickArr = new Array();
(2) add map
(3) Add group layer to map
map.addLayer(search_group);
(4) the add to map function, with a popup that contains a link, which when clicked will have a remove option. This link will have, as its id the lat long of the point. This id will then be compared to when you click on one of your created markers and you want to delete it.
map.on('click', function(e) {
var clickPositionMarker = L.marker([e.latlng.lat,e.latlng.lng],{icon: idMarker});
clickArr.push(clickPositionMarker);
mapLat = e.latlng.lat;
mapLon = e.latlng.lng;
clickPositionMarker.addTo(search_group).bindPopup("<a name='removeClickM' id="+e.latlng.lat+"_"+e.latlng.lng+">Remove Me</a>")
.openPopup();
/* clickPositionMarker.on('click', function(e) {
markerDelAgain();
}); */
});
(5) The remove function, compare the marker lat long to the id fired in the remove:
$(document).on("click","a[name='removeClickM']", function (e) {
// Stop form from submitting normally
e.preventDefault();
for(i=0;i<clickArr.length;i++) {
if(search_group.hasLayer(clickArr[i]))
{
if(clickArr[i]._latlng.lat+"_"+clickArr[i]._latlng.lng==$(this).attr('id'))
{
hideLayer(search_group,clickArr[i]);
clickArr.splice(clickArr.indexOf(clickArr[i]), 1);
}
}
}
All the answers are complete. But Wanted to add one thing,
set FirstName=%~1
set LastName=%~2
This line should have worked, you needed a small change.
set "FirstName=%~1"
set "LastName=%~2"
Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.
If you used rbenv
to install it, you can use
rbenv versions
to see which versions you have installed.
Then, use the uninstall command:
rbenv uninstall [-f|--force] <version>
for example:
rbenv uninstall 2.4.0 # Uninstall Ruby 2.4.0
If you installed Rails, it will be removed, too.
If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . "
And you expect the answer to be
"this string have lots of space"
, you can use the following solution:
$strng = "this string have lots of space . ";
$strng = trim(preg_replace('/\s+/',' ', $strng));
echo $strng;
To say "nodemon" would answer the question.
But on how only to kill (all) node demon(s), the following works for me:
pkill -HUP node
In my scenario, I was supposed to open a dialog box in the mouse position based on a GUI operation done with the mouse. The following code worked for me:
public Object open() {
//create the contents of the dialog
createContents();
//setting the shell location based on the curent position
//of the mouse
PointerInfo a = MouseInfo.getPointerInfo();
Point pt = a.getLocation();
shellEO.setLocation (pt.x, pt.y);
//once the contents are created and location is set-
//open the dialog
shellEO.open();
shellEO.layout();
Display display = getParent().getDisplay();
while (!shellEO.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
app.use(express.static(__dirname + '/public'));
<link href="/css/style.css" rel="stylesheet" type="text/css">
So folder structure should be:
.
./app.js
./public
/css
/style.css
HTML:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa omnis obcaecati dolore reprehenderit praesentium. Nisi eius deleniti voluptates quis esse deserunt magni eum commodi nostrum facere pariatur sed eos voluptatum?
</p><span class="small-text">George Nelson 1955</span>
CSS:
p {font-size:24px; font-weight: 300; -webkit-font-smoothing: subpixel-antialiased;}
p span {font-size:16px; font-style: italic; margin-top:50px;}
.small-text{
font-size: 12px;
font-style: italic;
}
You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()
What is the purpose of a module system?
It accomplishes the following things:
Having modules makes it easier to find certain parts of code which makes our code more maintainable.
How does it work?
NodejS
uses the CommomJS module system which works in the following manner:
module.export
syntaxrequire('file')
syntaxtest1.js
const test2 = require('./test2'); // returns the module.exports object of a file
test2.Func1(); // logs func1
test2.Func2(); // logs func2
test2.js
module.exports.Func1 = () => {console.log('func1')};
exports.Func2 = () => {console.log('func2')};
require()
is called on the same module the is pulled from the cache.require()
right away.The file .so is not a UNIX file extension for shared library.
It just happens to be a common one.
Check line 3b at ArnaudRecipes sharedlib page
Basically .dylib is the mac file extension used to indicate a shared lib.
A more flexible filtering array from another array which contain object properties
function filterFn(array, diffArray, prop, propDiff) {_x000D_
diffArray = !propDiff ? diffArray : diffArray.map(d => d[propDiff])_x000D_
this.fn = f => diffArray.indexOf(f) === -1_x000D_
if (prop) {_x000D_
return array.map(r => r[prop]).filter(this.fn)_x000D_
} else {_x000D_
return array.filter(this.fn)_x000D_
}_x000D_
}_x000D_
_x000D_
//You can use it like this;_x000D_
_x000D_
var arr = [];_x000D_
_x000D_
for (var i = 0; i < 10; i++) {_x000D_
var obj = {}_x000D_
obj.index = i_x000D_
obj.value = Math.pow(2, i)_x000D_
arr.push(obj)_x000D_
}_x000D_
_x000D_
var arr2 = [1, 2, 3, 4, 5]_x000D_
_x000D_
var sec = [{t:2}, {t:99}, {t:256}, {t:4096}]_x000D_
_x000D_
var log = console.log.bind(console)_x000D_
_x000D_
var filtered = filterFn(arr, sec, 'value', 't')_x000D_
_x000D_
var filtered2 = filterFn(arr2, sec, null, 't')_x000D_
_x000D_
log(filtered, filtered2)
_x000D_
This is a way to see if any XML-files exists in that folder, yes.
To check for specific files use File.Exists(path)
, which will return a boolean indicating wheter the file at path
exists.
Git Bash uses cmd.exe
for its terminal plus extentions from MSYS/MinGW which are provided by sh.exe
, a sort of cmd.exe
wrapper. In Windows you launch a new terminal using the start
command.
Thus a shell script which launches a new Git Bash terminal with a specific working directory is:
(cd C:/path/to/dir1 && start sh --login) &
(cd D:/path/to/dir2 && start sh --login) &
An equivalent Windows batch script is:
C:
cd \path\to\dir1
start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
D:
cd \path\to\dir2
start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
To get the same font and window size as the Git Bash launched from the start menu, it is easiest to copy the start menu shortcut settings to the command console defaults (to change defaults, open cmd.exe
, left-click the upper left icon, and select Defaults).
Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.
The example the OP gave would simply be:
>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18
Looking at your Erlang implementation. The timing has included the start up of the entire virtual machine, running your program and halting the virtual machine. Am pretty sure that setting up and halting the erlang vm takes some time.
If the timing was done within the erlang virtual machine itself, results would be different as in that case we would have the actual time for only the program in question. Otherwise, i believe that the total time taken by the process of starting and loading of the Erlang Vm plus that of halting it (as you put it in your program) are all included in the total time which the method you are using to time the program is outputting. Consider using the erlang timing itself which we use when we want to time our programs within the virtual machine itself
timer:tc/1 or timer:tc/2 or timer:tc/3
. In this way, the results from erlang will exclude the time taken to start and stop/kill/halt the virtual machine. That is my reasoning there, think about it, and then try your bench mark again.
I actually suggest that we try to time the program (for languages that have a runtime), within the runtime of those languages in order to get a precise value. C for example has no overhead of starting and shutting down a runtime system as does Erlang, Python and Haskell (98% sure of this - i stand correction). So (based on this reasoning) i conclude by saying that this benchmark wasnot precise /fair enough for languages running on top of a runtime system. Lets do it again with these changes.
EDIT: besides even if all the languages had runtime systems, the overhead of starting each and halting it would differ. so i suggest we time from within the runtime systems (for the languages for which this applies). The Erlang VM is known to have considerable overhead at start up!
Just implement an Interface given by PHP JsonSerializable.
Take a look at the Oracle Documentation.
Starting from JDK 1.4 an Application terminates if:
Cornercases:
The document states that some packages create displayable components without releasing them.A program which calls Toolkit.getDefaultToolkit() won't terminate. is among others given as an example.
Also other Processes can keep AWT alive when they, for what ever reason, are sending events into the native event queue.
Also I noticed that on some Systems it takes a coupple of seconds before the Application actually terminates.
Try this:
var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id";
ctx.Database.ExecuteSqlCommand(
sql,
new SqlParameter("@FirstName", firstname),
new SqlParameter("@Id", id));
/(.*)<FooBar>/s
the s causes Dot (.) to match carriage returns
You can use the Text_Qualifier
field in your Flat file connection manager to as "
. This should wrap your data in quotes and only separate by commas which are outside the quotes.
Choosing a "different one" is actually a pretty easy solution.
I had been running Eclipse as an administrator (sudo eclipse
from the command line) because the "workspace" folder was throwing the Workspace in use or cannot be created…
error (and running as administrator seemed to be the only solution that fixed it).
A coworker (working on this same issue with me) wanted to run Eclipse by clicking on an icon. So when he ran Eclipse, and the dialogue box came up with the choose your workspace, he just added a "2" to the end of "workspace".
This created a new folder: "workspace2". Eclipse ran fine with that; and I haven’t had any of the locking problems since.
tl;dr: You don't have to remove the slashes, you have nested JSON, and hence have to decode the JSON twice: DEMO (note I used double slashes in the example, because the JSON is inside a JS string literal).
I assume that your actual JSON looks like
{"data":"{\n \"taskNames\" : [\n \"01 Jan\",\n \"02 Jan\",\n \"03 Jan\",\n \"04 Jan\",\n \"05 Jan\",\n \"06 Jan\",\n \"07 Jan\",\n \"08 Jan\",\n \"09 Jan\",\n \"10 Jan\",\n \"11 Jan\",\n \"12 Jan\",\n \"13 Jan\",\n \"14 Jan\",\n \"15 Jan\",\n \"16 Jan\",\n \"17 Jan\",\n \"18 Jan\",\n \"19 Jan\",\n \"20 Jan\",\n \"21 Jan\",\n \"22 Jan\",\n \"23 Jan\",\n \"24 Jan\",\n \"25 Jan\",\n \"26 Jan\",\n \"27 Jan\"]}"}
I.e. you have a top level object with one key, data
. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \"
inside the string. This lets the parser know that "
is to be treated literally and doesn't terminate the string.
So you can either fix the server side code, so that you don't double encode the data, or you have to decode the JSON twice, e.g.
var data = JSON.parse(JSON.parse(json).data));
What seems to be needed is to actually define the button as a button widget.
I had the same problem (in beta 1)
I did
$("#submitButton").button();
in my window ready handler, after that it worked to do as it is said in the docs, i.e.:
$("#submitButton").button('disable');
I guess this has to do with that jqm is converting the markup, but isnt actually instatiating a real button widget for buttons and link buttons.
How about using numpy.vectorize
.
import numpy as np
x = np.array([1, 2, 3, 4, 5])
squarer = lambda t: t ** 2
vfunc = np.vectorize(squarer)
vfunc(x)
# Output : array([ 1, 4, 9, 16, 25])
On a Unix/Linux box you could just run 'wget' but this is not really an option if you're writing a cross-platform client. Of course this assumes that you don't really want to do much with the data you download between the point of downloading it and it hitting the disk.
Solution as proposed by Aziz would be:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:children,
)
It would not be in the exact center because of padding:
padding: new EdgeInsets.all(25.0),
To make exactly center Column - at least in this case - you would need to remove padding.
You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
}
To put it more simply, if you have:
if(condition == TRUE) x <- TRUE
else x <- FALSE
Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:
if(condition == TRUE) {x <- TRUE
} else {x <- FALSE}
There's no easy way to do this, but something like this will work:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
If we declare datatype as VARCHAR then it will occupy space for NULL values. In the case of VARCHAR2 datatype, it will not occupy any space for NULL values. e.g.,
name varchar(10)
will reserve 6 bytes of memory even if the name is 'Ravi__', whereas
name varchar2(10)
will reserve space according to the length of the input string. e.g., 4 bytes of memory for 'Ravi__'.
Here, _ represents NULL.
NOTE: varchar will reserve space for null values and varchar2 will not reserve any space for null values.
<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">xxxxx</td>
<td width="700">xxxxxx</td>
<td width="170">xxxxxx</td>
<td width="30">xxxxxx</td>
</tr>
<tr bgcolor="#FFFFFF">
<td><?php
$date = date_create($row_Recordset3['fecha']);
echo date_format($date, 'd-m-Y');
?></td>
<td><?php echo $row_Recordset3['descripcion']; ?></td>
<td><?php echo $row_Recordset3['producto']; ?></td>
<td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
</tr>
</table>
<input type="hidden" id="datatodisplay" name="datatodisplay">
<input type="submit" value="Export to Excel">
exporttable.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
if someone needs to view arrays so cool ;) use this method.. this will print to your browser console
function console($obj)
{
$js = json_encode($obj);
print_r('<script>console.log('.$js.')</script>');
}
you can use like this..
console($myObject);
Output will be like this.. so cool eh !!
I had a similar situation on a function that calculates the average.
Example:
ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();
Case Solved:
ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();
I have the same error but with different case. Let me quote the solution from here:
Luckly I also have the same set up on my desktop. I have installed first default instance and then Sql Express. Everything is fine for me for several days. Then I tried connecting the way you trying, i.e with MachineName\MsSqlServer to default instance and I got exctaly the same error.
So the solution is when you trying to connect to default instance you don't need to provide instance name.(well this is something puzzled me, why it is failing when we are giving instance name when it is a default instance? Is it some bug, don't know)
Just try with - PC-NAME and everything will be fine. PC-NAME is the MSSQLServer instance.
Edit : Well after reading your question again I realized that you are not aware of the fact that MSSQLSERVER is the default instance of Sql Server. And for connecting to default instance (MSSQLSERVER) you don't need to provide the instance name in connection string. The "MachineName" is itself means "MachineName\MSSQLSERVER".
The newest version of docker (18.03) offers a built in port forwarding solution. Inside your docker container simply have the db host set to host.docker.internal
. This will be forwarded to the host the docker container is running on.
Documentation for this is here: https://docs.docker.com/docker-for-mac/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host
Yes, and basically you can also use inline style:
<span style="font-size: 15px" class="glyphicon glyphicon-cog"></span>
If you have Login in a seperate folder within your project make sure that where you are using it you do:
using FootballLeagueSystem.[Whatever folder you are using]
Just call it and supply self
class A:
def m(self, x, y):
print(x+y)
class B:
def call_a(self):
A.m(self, 1, 2)
b = B()
b.call_a()
output: 3
Instead of using URI segments you should do this:
$this->router->fetch_class(); // class = controller
$this->router->fetch_method();
That way you know you are always using the correct values even if you are behind a routed URL, in a sub-domain, etc.
While on dealing with the SimpleDateFormat class, it's important to remember that Date is not thread-safe and you can not share a single Date object with multiple threads.
Also there is big difference between "m" and "M" where small case is used for minutes and capital case is used for month. The same with "d" and "D". This can cause subtle bugs which often get overlooked. See Javadoc or Guide to Convert String to Date in Java for more details.
get current activity from parent, then using this code
getActivity().getSupportFragmentManager()
Go to the package.json
file, check the "@angular/core"
version. It is an actual project version.
Double them to escape;
SELECT *
FROM Header
WHERE userID LIKE '%''%'
Just a heads up that Bootstrap 4 now uses img-fluid
instead of img-responsive
, so double check which version you're using if you're having problems.
Make sure you declare the variable on "root" level, outside any code blocks.
You could also remove the var
altogether, although that is not recommended and will throw a "strict" warning.
According to the documentation at MDC, you can set global variables using window.variablename
.
npm build
no longer exists. You must call npm run build
now. More info below.
npm install
: installs dependencies, then calls the install
from the package.json
scripts
field.
npm run build
: runs the build field from the package.json
scripts
field.
https://docs.npmjs.com/misc/scripts
There are many things you can put into the npm package.json
scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.
npm install
is not the same as npm run install
npm install
installs package.json
dependencies, then runs the package.json
scripts.install
npm run install
after dependencies are installed.npm run install
only runs the package.json
scripts.install
, it will not install dependencies.npm build
used to be a valid command (used to be the same as npm run build
) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build?
You can read more on the documentation: https://docs.npmjs.com/cli/buildThere are still two top level commands that will run scripts, they are:
npm start
which is the same as npm run start
npm test
==> npm run test
For me, I was receiving this error when connecting to the new IP Address I had configured FileZilla to bind to and saved the configuration. After trying all of the other answers unsuccessfully, I decided to connect to the old IP Address to see what came up; lo and behold it responded.
I restarted the FileZilla Windows Service and it immediately came back listening on the correct IP. Pretty elementary, but it cost me some time today as a noob to FZ.
Hopefully this helps someone out in the same predicament.
Assuming you already know how to write a view in Flask
that responds to a url, create one that reads the request.post
data. To add the input box
to this post data create a form on your page with the text box. You can then use jquery
to do
var data = $('#<form-id>').serialize()
and then post to your view asynchronously using something like the below.
$.post('<your view url>', function(data) {
$('.result').html(data);
});
All these patterns, MVC, MVVM, MVP, and Presentation Model, can be applied to Android apps, but without a third-party framework, it is not easy to get well-organized structure and clean code.
MVVM is originated from PresentationModel. When we apply MVC, MVVM, and Presentation Model to an Android app, what we really want is to have a clear structured project and more importantly easier for unit tests.
At the moment, without an third-party framework, you usually have lots of code (like addXXListener(), findViewById(), etc.), which does not add any business value. What's more, you have to run Android unit tests instead of normal JUnit tests, which take ages to run and make unit tests somewhat impractical.
For these reasons, some years ago we started an open source project, RoboBinding - A data-binding Presentation Model framework for the Android platform. RoboBinding helps you write UI code that is easier to read, test, and maintain. RoboBinding removes the need of unnecessary code like addXXListener or so, and shifts UI logic to the Presentation Model, which is a POJO and can be tested via normal JUnit tests. RoboBinding itself comes with more than 300 JUnit tests to ensure its quality.
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
or an ECHO server and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
According to the GNU C library manual (http://www.gnu.org/software/libc/manual/html_node/Header-Files.html)
In C, a declaration merely provides information that a function or variable exists and gives its type. For a function declaration, information about the types of its arguments might be provided as well. The purpose of declarations is to allow the compiler to correctly process references to the declared variables and functions. A definition, on the other hand, actually allocates storage for a variable or says what a function does.
set PYTHONIOENCODING=utf-8
set PYTHONLEGACYWINDOWSSTDIO=utf-8
You may or may not need to set that second environment variable PYTHONLEGACYWINDOWSSTDIO
.
Alternatively, this can be done in code (although it seems that doing it through env vars is recommended):
sys.stdin.reconfigure(encoding='utf-8')
sys.stdout.reconfigure(encoding='utf-8')
Additionally: Reproducing this error was a bit of a pain, so leaving this here too in case you need to reproduce it on your machine:
set PYTHONIOENCODING=windows-1252
set PYTHONLEGACYWINDOWSSTDIO=windows-1252
Once you have copied the plugins and features folder to eclipse (eg. c:\program files\eclipse (or whereever you installed it). You will see a features and plugins folder there already) you can check if hibernate has installed by going to Help > Software updates > installed software. If hibernate is not listed close eclipse and launch it again via a command window with this command "eclipse -clean".
I made a simple tool that will display an image given a filename or image object or url.
It's crude, but it'll do in a hurry.
Installation:
$ pip install simple-imshow
Usage:
from simshow import simshow
simshow('some_local_file.jpg') # display from local file
simshow('http://mathandy.com/escher_sphere.png') # display from url
In case this is of use to some newer dev's because its not specified above. Just to be very explicit:
You need two things if using onConfigurationChanged:
An onConfigurationChanged
method in your Activity Class
Specify in your manifest which configuration changes will be handled by your onConfigurationChanged
method
The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.
<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>
In the above manifest entry, there are various Android actions for android:configChanges=""
which can trigger the onCreate in your Activity lifecycle.
This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged
method in your Activity Class.
So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.
<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>
Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.
Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged
is not working. You must put all relevant ones into your manifest.
I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize
. So test on a selection of platforms.
<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>
So my suggestion, although I'm sure someone can poke holes in this:
Add your onConfigurationChanged
method in your Activity Class with a TOAST or LOG so you can see when its working.
Add all possible configuration options to your manifest.
Confirm your onConfigurationChanged
method is working by testing your app.
Remove each config option from your manifest file one at a time, testing your app after each.
Test on as large a variety of devices as possible.
Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.
I hope this saves someone some time.
My onConfigurationChanged
method just for info below. onConfigurationChanged
is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if
to check the orientation works correctly, and then the 2nd nested if
to look at the visibility of my UI ImageView also works correctly.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
}
}
if you are Executing Linq to Entity
you can't use the ClassType
with new
in the select
closure of query only anonymous types are allowed (new without type)
take look at this snippet of my project
//...
var dbQuery = context.Set<Letter>()
.Include(letter => letter.LetterStatus)
.Select(l => new {Title =l.Title,ID = l.ID, LastModificationDate = l.LastModificationDate, DateCreated = l.DateCreated,LetterStatus = new {ID = l.LetterStatusID.Value,NameInArabic = l.LetterStatus.NameInArabic,NameInEnglish = l.LetterStatus.NameInEnglish} })
^^ without type__________________________________________________________________________________________________________^^ without type
of you added the new keyword
in Select closure even on the complex properties
you will got this error
so
remove
theClassTypes from new
keyword onLinq to Entity
queries ,,
because it will transformed to sql statement and executed on SqlServer
so when can I use new with types
on select
closure?
you can use it if you you are dealing with LINQ to Object (in memory collection)
//opecations in tempList , LINQ to Entities; so we can not use class types in select only anonymous types are allowed
var tempList = dbQuery.Skip(10).Take(10).ToList();// this is list of <anonymous type> so we have to convert it so list of <letter>
//opecations in list , LINQ to Object; so we can use class types in select
list = tempList.Select(l => new Letter{ Title = l.Title, ID = l.ID, LastModificationDate = l.LastModificationDate, DateCreated = l.DateCreated, LetterStatus = new LetterStatus{ ID = l.LetterStatus.ID, NameInArabic = l.LetterStatus.NameInArabic, NameInEnglish = l.LetterStatus.NameInEnglish } }).ToList();
^^^^^^ with type
after I executed ToList
on query it became in memory collection
so we can use new ClassTypes
in select
If you're just trying to find out where npm is installing your global module (the title of this thread), look at the output when running npm install -g sample_module
$ npm install -g sample_module C:\Users\user\AppData\Roaming\npm\sample_module -> C:\Users\user\AppData\Roaming\npm\node_modules\sample_module\bin\sample_module.js + [email protected] updated 1 package in 2.821s
JSON is just a subset of JavaScript. But eval
evaluates the full JavaScript language and not just the subset that’s JSON.
On an AWS Ubuntu 16.04 Server I put the Docker images on a separate EBS, mounted on /home/ubuntu/kaggle/, under the docker dir
This snippet of my initialization script worked correctly
# where are the images initially stored?
sudo docker info | grep "Root Dir"
# ... not where I want them
# modify the configuration files to change to image location
# NOTE this generates an error
# WARNING: Usage of loopback devices is strongly discouraged for production use.
# Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
# see https://stackoverflow.com/questions/31620825/
# warning-of-usage-of-loopback-devices-is-strongly-discouraged-for-production-use
sudo sed -i ' s@#DOCKER_OPTS=.*@DOCKER_OPTS="-g /home/ubuntu/kaggle/docker"@ ' /etc/default/docker
sudo chmod -R ugo+rw /lib/systemd/system/docker.service
sudo cp /lib/systemd/system/docker.service /etc/systemd/system/
sudo chmod -R ugo+rw /etc/systemd/system/
sudo sed -i ' s@ExecStart.*@ExecStart=/usr/bin/dockerd $DOCKER_OPTS -H fd://@ ' /etc/systemd/system/docker.service
sudo sed -i '/ExecStart/a EnvironmentFile=-/etc/default/docker' /etc/systemd/system/docker.service
sudo systemctl daemon-reload
sudo systemctl restart docker
sudo docker info | grep "Root Dir"
# now they're where I want them
With pure CSS, nothing fancy with :before
and :after
, no transforms, you can turn off the default appearance and then style it with an inline background image like the following example. This works in Chrome, Firefox, Safari, and now Edge (Chromium Edge).
INPUT[type=checkbox]:focus
{
outline: 1px solid rgba(0, 0, 0, 0.2);
}
INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
width: 17px;
height: 17px;
cursor: pointer;
position: relative;
top: 5px;
}
INPUT[type=checkbox]:checked
{
background-color: #409fd6;
background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
_x000D_
<form>
<label><input type="checkbox"> I Agree To Terms & Conditions</label>
</form>
_x000D_
This is the VBA that I use to open the current path in an Explorer window:
Shell Environ("windir") & "\explorer.exe """ & CurDir() & "",vbNormalFocus
Microsoft Documentation:
If you do not want to change your HTML structure you can also do by adding text-align: center;
to the wrapper element and a display: inline-block;
to the centered element.
#container {
width:100%;
text-align:center;
}
#left {
float:left;
width:100px;
}
#center {
display: inline-block;
margin:0 auto;
width:100px;
}
#right {
float:right;
width:100px;
}
Live Demo: http://jsfiddle.net/CH9K8/
scores = ['91','89','87','86','85']
scores.sort()
print (scores)
This worked for me using python version 3, though it didn't in version 2.
To avoid any ambiguity, use the utilities methods from SwingUtilities :
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
The regex you're looking for is ^[A-Za-z.\s_-]+$
^
asserts that the regular expression must match at the beginning of the subject[]
is a character class - any character that matches inside this expression is allowedA-Z
allows a range of uppercase charactersa-z
allows a range of lowercase characters.
matches a period
rather than a range of characters\s
matches whitespace (spaces and tabs)_
matches an underscore-
matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-
) instead and put it anywhere in the character class, but that's less clear+
asserts that the preceding expression (in our case, the character class) must match one or more times$
Finally, this asserts that we're now at the end of the subjectWhen you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.
that is the right behavior.
if you set @item1
to a value the below expression will be true
IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)
Anyway in SQL Server there is not a such function but you can create your own:
CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
RETURN 0
ELSE
RETURN 1
END
Make sure that the path actually leads to the executables. I'm using version 11 and it did not work until this was set as the path:
C:\Program Files\PostgreSQL\11\bin\bin
Maybe this is how version 11 is structured or I somehow botched the installation but I haven't had a problem since.
Do
apachectl -k graceful
Check this link for more information : http://www.electrictoolbox.com/article/apache/restart-apache/
nsenter
does that. However I also needed to enter a container in a simple way and nsenter didn't suffice for my needs. It was buggy in some occasions (black screen plus -wd flag not working). Furthermore I wanted to login as a specific user and in a specific directory.
I ended up making my own tool to enter containers. You can find it at: https://github.com/Pithikos/docker-enter
Its usage is as easy as
./docker-enter [-u <user>] [-d <directory>] <container ID>
If You are comparing only with the date vale, then converting it to date (not datetime) will work
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= convert(date,'2013-04-12',102)
This conversion is also applicable during using GetDate() function
Try this:
NSString *URL = @"xyz.com";
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:URL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL]];
}
I had this problem because I updated packages, which included Microsoft.AspNet.WebApi that has a reference to Newtonsoft.Json 4.5.6 and I already had version 6 installed. It wasn't clever enough to use the version 6.
To resolve it, after the WebApi update I opened the Tools > NuGet Package Manager > Pacakge Manager Console and ran:
Update-Package Newtonsoft.Json
The log showed that the 6.0.x and 4.5.6 versions were all updated to the latest one and everything was fine.
I have a feeling this will come up again.
I agree with the first answer but I would also declare the class as final so that it cannot be extended as extending a singleton violates the singleton pattern. Also the instance variable should be private so that it cannot be accessed directly. Also make the __clone method private so that you cannot clone the singleton object.
Below is some example code.
/**
* Singleton class
*
*/
final class UserFactory
{
private static $_instance = null;
/**
* Private constructor
*
*/
private function __construct() {}
/**
* Private clone method
*
*/
private function __clone() {}
/**
* Call this method to get singleton
*
* @return UserFactory
*/
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new UserFactory();
}
return self::$_instance;
}
}
Example Usage
$user_factory = UserFactory::getInstance();
What this stops you from doing (which would violate the singleton pattern..
YOU CANNOT DO THIS!
$user_factory = UserFactory::$_instance;
class SecondUserFactory extends UserFactory { }
You can check this way too
<c:if test="${theBooleanVariable ne true}">It's false!</c:if>
I found the best way to tackle this.
You need to set a solid rectangle background on the layout.
Use this code - ViewCompat.setElevation(view , value)
On the parent layout set android:clipToPadding="false"
you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)
also you cannot use OVER
clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from docs.oracle.com)
select *
from (select
staff_id, site_id, pay_level, date,
max(date) over (partition by staff_id) max_date
from owner.table
where end_enrollment_date is null
)
where date = max_date
Here is a single function that will merge X amount of PDFs using PDFSharp
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
public static void MergePDFs(string targetPath, params string[] pdfs) {
using(PdfDocument targetDoc = new PdfDocument()){
foreach (string pdf in pdfs) {
using (PdfDocument pdfDoc = PdfReader.Open(pdf, PdfDocumentOpenMode.Import)) {
for (int i = 0; i < pdfDoc.PageCount; i++) {
targetDoc.AddPage(pdfDoc.Pages[i]);
}
}
}
targetDoc.Save(targetPath);
}
}
Same thing worked for me: Properties -> Java Build Path -> "Order and Export" Interestingly - why this is not done automatically? I guess some setting is missing. Also this happened for me after SDK upgrade.
If you are writing a scraper and really don't care about the SSL certificate you can set it global:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
DO NOT USE IN PRODUCTION
I usually go for the visibility:hidden
trick
this is my styled button
<div id="uploadbutton" class="btn btn-success btn-block">Upload</div>
this is the input type=file button. Note the visibility:hidden
rule
<input type="file" id="upload" style="visibility:hidden;">
this is the JavaScript bit to glue them together. It works
<script>
$('#uploadbutton').click(function(){
$('input[type=file]').click();
});
</script>
Great answers here but I needed to replace a value in a JSON request. After a little digging into the code, I came up with the following code. Let me know if I'm doing something dumb.
$json = $request->json()->all();
$json['field'] = 'new value';
$request->json()->replace($json);
apply the below code in productRepository
@Query("update Product set prodName=:name where prodId=:id ")
@Transactional
@Modifying
int updateMyData(@Param("name")String name, @Param("id") Integer id);
while in junit test apply below code
@Test
public void updateData()
{
int i=productRepository.updateMyData("Iphone",102);
System.out.println("successfully updated ... ");
assertTrue(i!=0);
}
it is working fine for my code
Scenario
In a college there are many students doing different courses, and after an examination we have to prepare a marks card showing grade. I can calculate grade two ways
1. I can write some code like this
if(totalMark <= 100 && totalMark > 90) { grade = "A+"; }
else if(totalMark <= 90 && totalMark > 80) { grade = "A"; }
else if(totalMark <= 80 && totalMark > 70) { grade = "B"; }
else if(totalMark <= 70 && totalMark > 60) { grade = "C"; }
2. You can ask user to enter grade definition some where and save that data
Something like storing into a database table
In the first case the grade is common for all the courses and if the rule changes the code needs to be changed. But for second case we are giving user the provision to enter grade based on their requirement. So the code will be not be changed when the grade rules changes.
That's the important thing when you give more provision for users to define business logic. The first case is nothing but Hard Coding.
So in your question if you ask the user to enter the path of the file at the start, then you can remove the hard coded path in your code.
@nombre_row :nombre ligne par page
@page:numero de la page
//--------------code sql---------------
declare @page int,@nombre_row int;
set @page='2';
set @nombre_row=5;
SELECT *
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY etudiant_ID ) AS RowNum, *
FROM etudiant
) AS RowConstrainedResult
WHERE RowNum >= ((@page-1)*@nombre_row)+1
AND RowNum < ((@page)*@nombre_row)+1
ORDER BY RowNum
I just solved this issue myself. You were on the right track.
@media (min-width: 1200px) {
.container{
max-width: 970px;
}
}
Here we say: On viewports 1200px or larger - set container max-width to 970px. This will overwrite the standard class that currently sets max-width to 1170px for that range.
NOTE: Make sure you include this AFTER the bootstrap.css stuff (everyone has made this little mistake in the past).
Hope this helps.. good luck!
Use the os.EOL constant instead.
var os = require("os");
function processInput ( text )
{
fs.open('H://log.txt', 'a', 666, function( e, id ) {
fs.write( id, text + os.EOL, null, 'utf8', function(){
fs.close(id, function(){
console.log('file is updated');
});
});
});
}
The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).
You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.
Use:
SELECT mt.name
FROM MY_TABLE mt
GROUP BY mt.name
HAVING MAX(LENGTH(mt.name)) = 18
...assuming you know the length beforehand. If you don't, use:
SELECT mt.name
FROM MY_TABLE mt
JOIN (SELECT MAX(LENGTH(x.name) AS max_length
FROM MY_TABLE x) y ON y.max_length = LENGTH(mt.name)
You cannot supply system properties to the jarsigner.exe tool, unfortunately.
I have submitted defect 7177232, referencing @eckes' defect 7127374 and explaining why it was closed in error.
My defect is specifically about the impact on the jarsigner tool, but perhaps it will lead them to reopening the other defect and addressing the issue properly.
UPDATE: Actually, it turns out that you CAN supply system properties to the Jarsigner tool, it's just not in the help message. Use jarsigner -J-Djsse.enableSNIExtension=false
Tomcat can work in 2 modes:
Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol
parameter in the server.xml
file.
HTTP/1.1
or org.apache.coyote.http11.Http11Protocol
org.apache.coyote.http11.Http11NioProtocol
If you're using BIO then I believe they should be more or less the same.
If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
You can:
mkdir -p folder/subfolder
The -p
flag causes any parent directories to be created if necessary.
You can use the "-r" option to set the sender address:
mailx -r [email protected] -s ...
I had fix this with adduser *username* dialout
. I never had this error again, even though previously the only way to get it to work was to reboot the PC or unplug and replug the usb to serial adapter.
This is working for me in ReactNative 0.60.4
View
<View style={styles.SectionStyle}>
<Image
source={require('../assets/images/ico-email.png')} //Change your icon image here
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1 }}
placeholder="Enter Your Name Here"
underlineColorAndroid="transparent"
/>
</View>
Styles
SectionStyle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
borderWidth: 0.5,
borderColor: '#000',
height: 40,
borderRadius: 5,
margin: 10,
},
ImageStyle: {
padding: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
}
I have Far.exe as the first item in the start menu.
Richtext in the clipboard ->
ctrl-escape,arrdown,enter,shift-f4,$,enter
shift-insert,ctrl-insert,alt-backspace,
f10,enter
-> plaintext in the clipboard
Pros: no mouse, just blind typing, ends exactly where i was before
Cons: ANSI encoding - international symbols are lost
Luckily, I do not have to do that too often :)
You should checkout Junit-ext
project. They have RunIf
annotation that performs conditional tests, like:
@Test
@RunIf(DatabaseIsConnected.class)
public void calculateTotalSalary() {
//your code there
}
class DatabaseIsConnected implements Checker {
public boolean satisify() {
return Database.connect() != null;
}
}
[Code sample taken from their tutorial]
To pass XML content, you need to wrap the content in a Reader
, and unmarshal that instead:
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);
I opened the project org.eclipse.wst.common.project.facet.core.xml and first changed then removed line with web module tag. Cleaned project and launched on Tomcat each time but it still didn't run. Returned line (as was) and cleaned project. Opened Tomcat settings in Eclipse and manually added project to Tomcat startup (Right click + Add and Remove). Clicked on project and selected Run on server....and everything was fine.
File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
counter[row[11]]+=1
TypeError: unhashable type: 'list'
row[11]
is unhashable. It's a list. That is precisely (and only) what the error message means. You might not like it, but that is the error message.
Do this
counter[tuple(row[11])]+=1
Also, simplify.
d= [ row for row in c if counter[tuple(row[11])]>=sample_cutoff ]
using System;
using System.IO;
public class GetwithoutExtension
{
public static void Main()
{
//D:Dir dhould exists in ur system
DirectoryInfo dir1 = new DirectoryInfo(@"D:Dir");
FileInfo [] files = dir1.GetFiles("*xls", SearchOption.AllDirectories);
foreach (FileInfo f in files)
{
string filename = f.Name.ToString();
filename= filename.Replace(".xls", "");
Console.WriteLine(filename);
}
Console.ReadKey();
}
}
I had this issue, and found out that the server side C# method should be static.
Client Side:
$.ajax({
type: "POST",
url: "Default.aspx/ListItem_Selected",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: ListItemElectionSuccess,
error: ListItemElectionError
});
function ListItemElectionSuccess(data) {
alert([data.d]);
}
function ListItemElectionError(data) {
}
Server Side:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static String ListItem_Selected()
{
return "server responce";
}
}
While Nexus 5 owners wait for a dedicated driver, you could try this driver, which is the one for the LG G2, from LG Electronics' website, since usually USB drivers are not limited to one particular model. This one, for example, seems like a generic USB driver. You are prompted to download the same one for quite a few models on LG Electronics' website.
I hope this helps you ;)
I have found a way if you know startIndex and endIndex of the elements one need to remove from ArrayList
Let al
be the original ArrayList and startIndex
,endIndex
be start and end index to be removed from the array respectively:
al.subList(startIndex, endIndex + 1).clear();
You can try
git log --oneline | wc -l
or to list all the commits done by the people contributing in the repository
git shortlog -s
You can have great success and great performance either way. MSDN runs off of ASP.NET so you know it can perform well. PHP runs a lot of the top websites in the world. The same can be said of the databases as well. You really need to choose based upon your skills, the skills of your team, possible specific features that you need/want that one does better than the other, and even the servers that you want to run this site.
If I were building it, I would lean towards PHP because probably everything you want to do has been done before (with code examples how) and because hosting is so much easier to get (and cheaper because you don't have the licensing issues to deal with compared to Windows hosting). For the same reason, I would choose MySQL as well. It is a great database platform and the price is right.
Steps 1- Create/export a runnable jar file out of your project.
2- Create a .bat file with the below content
@Echo off
set classpath="c:\jars\lib\*****.jar;c:\jars\lib\*****.jar;c:\extJars\****.jar"
java -cp %classpath%;c:\apps\applName\yourJar.jar com.****.****.MainMethod args1 args2 ...
@pause
3- set classpath is required if any external jars you are using.
4- Put the .bat file and jar file in the same folder.
5- As per the java -cp command give your exact jar file location and the fully qualified name of the main method and followed by argument list as per requirement.
The simplest way is using HTML META tag like this:
<meta http-equiv="refresh" content="3;url=http://example.com/" />
In my case the problem was that Xcode was not installed.
Try this:
SELECT filename,Dates,Status
FROM TableName
WHERE Dates In (SELECT MAX(Dates) FROM TableName GROUP BY filename)
You can use the familiar Matplotlib style calling a figure
and subplot
, but you simply need to specify the current axis using plt.gca()
. An example:
plt.figure(1)
plt.subplot(2,2,1)
df.A.plot() #no need to specify for first axis
plt.subplot(2,2,2)
df.B.plot(ax=plt.gca())
plt.subplot(2,2,3)
df.C.plot(ax=plt.gca())
etc...
Getting the Text of ComboBox when the item is changed
self.ui.comboBox.activated.connect(self.pass_Net_Adap)
def pass_Net_Adap(self):
print str(self.ui.comboBox.currentText())
You can check the Ascii value by e.keychar on KeyPress event of TextBox.
By checking the AscII value you can check for number or character.
Similarly you can write logic to check the Email ID.
Bootstrap3
CSS (gutter only, without margins around):
.row.row-gutter {
margin-bottom: -15px;
overflow: hidden;
}
.row.row-gutter > *[class^="col"] {
margin-bottom: 15px;
}
CSS (equal margins around, 15px/2):
.row.row-margins {
padding-top: 7px; /* or margin-top: 7px; */
padding-bottom: 7px; /* or margin-bottom: 7px; */
}
.row.row-margins > *[class^="col"] {
margin-top: 8px;
margin-bottom: 8px;
}
Usage:
<div class="row row-gutter">
<div class="col col-sm-9">first</div>
<div class="col col-sm-3">second</div>
<div class="col col-sm-12">third</div>
</div>
(with SASS or LESS 15px could be a variable from bootstrap)
Using Perl:
perl -ne 'print if /\S/'
\S
means match non-blank characters.
I had the same requirement which i have tried in below fiddle.
#container1 {
background-color:red;
position:absolute;
left:0;
top:0;
height:230px;
width:300px;
z-index:2;
}
#container2 {
background-color:blue;
position:absolute;
left:0;
top:0;
height:300px;
width:300px;
z-index:1;
}
#container {
position : relative;
height:350px;
width:350px;
background-color:yellow;
}
I found that if the application within the httpd server has a rule like "if the X-Frame-Options header exists and has a value, leave it alone; otherwise add the header X-Frame-Options: SAMEORIGIN" then an httpd.conf mod_headers rule like "Header always unset X-Frame-Options" would not suffice. The SAMEORIGIN value would always reach the client.
To remedy this, I add two, not one, mod_headers rules (in the outermost httpd.conf file):
Header set X-Frame-Options ALLOW-FROM http://to.be.deleted.com early
Header unset X-Frame-Options
The first rule tells any internal request handler that some other agent has taken responsibility for clickjack prevention and it can skip its attempt to save the world. It runs with "early" processing. The second rule strips off the entirely unwanted X-Frame-Options header. It runs with "late" processing.
I also add the appropriate Content-Security-Policy headers so that the world remains protected yet multi-sourced Javascript from trusted sites still gets to run.
Definitely in Modules.
Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.
This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.
There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.
I need this for Unity in C# so I thought that it might be useful for some one. This is an example of passing a list of AudioSources to whatever function you want:
private void ChooseClip(GameObject audioSourceGameObject , List<AudioClip> sources) {
audioSourceGameObject.GetComponent<AudioSource> ().clip = sources [0];
}
Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>
Use:
YourActivityName.this
Instead of:
getApplicationContext();
All solution that call length from array, add your code redundant null checkersconsider example:
int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
//What if array a comes as local parameter? You need to use null check:
public void someMethod(int[] a) {
if (a!=null) {
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
}
}
I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:
public void someMethod(int[] a) {
int[] b = ArrayUtils.clone(a);
}
Apache commons you can find there
Copy-paste the following into your current terminal:
gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"
This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.
function printCrossword(printContainer) {
var DocumentContainer = getElement(printContainer);
var WindowObject = window.open('', "PrintWindow", "width=5,height=5,top=200,left=200,toolbars=no,scrollbars=no,status=no,resizable=no");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
Nick Craver's solution works but you can also use this:
:nth-last-child(n+2) { /* Your code here */ }
Chris Coyier of CSS Tricks made a nice :nth tester for this.
For fresh setup of LAMP running php 7 edit the file /etc/httpd/conf/httpd.conf Note: make sure to make backup for it before changing anything.
Paste this at the very bottom of the file:
<IfModule php7_module>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
Then, search for LoadModule and paste the following line:
LoadModule php7_module modules/libphp7.so
This line will simply ask httpd to load the php 7 module
Then restart httpd
To Enable the Bluetooth you could use either of the following functions:
public void enableBT(View view){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()){
Intent intentBtEnabled = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult()
// implementation as the requestCode parameter.
int REQUEST_ENABLE_BT = 1;
startActivityForResult(intentBtEnabled, REQUEST_ENABLE_BT);
}
}
The second function is:
public void enableBT(View view){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.enable();
}
}
The difference is that the first function makes the app ask the user a permission to turn on the Bluetooth or to deny. The second function makes the app turn on the Bluetooth directly.
To Disable the Bluetooth use the following function:
public void disableBT(View view){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
}
}
NOTE/ The first function needs only the following permission to be defined in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.BLUETOOTH"/>
While, the second and third functions need the following permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.
This directly compares elements rather than just checking index numbers.
$yourset.each(function() {
var $this = $(this);
if($this[0] === $yourset.last()[0]) {
//$this is the last one
}
});
What about:
PrintWriter out = response.getWriter();
out.println("THE_STRING_TO_SEND_AS_RESPONSE");
return null;
This woks for me.
Write it as below
<script language="javascript">
var visitorName = 'Chuck';
var myOldString = 'Hello username. I hope you enjoy your stay username.';
var myNewString = myOldString.replace('username', visitorName);
document.write('Old String = ' + myOldString);
document.write('<br/>New string = ' + myNewString);
</script>
Try this:
Swift 4
myButton.addTarget(self,
action: #selector(myAction),
for: .touchUpInside)
Objective-C
[myButton addTarget:self
action:@selector(myAction)
forControlEvents:UIControlEventTouchUpInside];
You can find a rich source of information in Apple's Documentation. Have a look at the UIButton's documentation, it will reveal that UIButton is a descendant of UIControl, which implements the method to add targets.
--
You'll need to pay attention to whether add colon or not after myAction
in
action:@selector(myAction)
Here's the reference.
Quick fix, add this in your options:
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false)
Now you have no idea what host you're actually connecting to, because cURL will not verify the certificate in any way. Hope you enjoy man-in-the-middle attacks!
Or just add it to your current function:
/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an
* array containing the HTTP server response header fields and content.
*/
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false // Disabled SSL Cert checks
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
func post() {
NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"),
object: nil,
userInfo:["key0": "value", "key1": 1234])
}
func addObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(someMethod),
name: Notification.Name("SomeNotificationName"),
object: nil)
}
@objc func someMethod(_ notification: Notification) {
let info0 = notification.userInfo?["key0"]
let info1 = notification.userInfo?["key1"]
}
Replace Notification.Name("SomeNotificationName")
with .someNotificationName
:
extension Notification.Name {
static let someNotificationName = Notification.Name("SomeNotificationName")
}
Replace "key0"
and "key1"
with Notification.Key.key0
and Notification.Key.key1
:
extension Notification {
enum Key: String {
case key0
case key1
}
}
Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...
https://www.youtube.com/account_advanced now provides both channel and user ids. See also https://developers.google.com/youtube/v3/guides/working_with_channel_ids .
Note that starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's possible to improve a bit on Krzysztof Krason's solution by capturing the match result directly within the if condition as a variable and re-use it in the condition's body:
# pattern = '<title>(.*)</title>'
# text = '<title>hello</title>'
if match := re.search(pattern, text, re.IGNORECASE):
title = match.group(1)
# hello
This is an alternative if you don't want to use claims all the time. Take a look at this tutorial by Ben Foster.
public class AppUser : ClaimsPrincipal
{
public AppUser(ClaimsPrincipal principal)
: base(principal)
{
}
public string Name
{
get
{
return this.FindFirst(ClaimTypes.Name).Value;
}
}
}
Then you can add a base controller.
public abstract class AppController : Controller
{
public AppUser CurrentUser
{
get
{
return new AppUser(this.User as ClaimsPrincipal);
}
}
}
In you controller, you would do:
public class HomeController : AppController
{
public ActionResult Index()
{
ViewBag.Name = CurrentUser.Name;
return View();
}
}
Does this work for you?
http://jojovedder.blogspot.com/2009/04/running-maven-offline-using-local.html
Don't forget to add it to your plugin repository and point the url to wherever your repository is.
<repositories>
<repository>
<id>local</id>
<url>file://D:\mavenrepo</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>local</id>
<url>file://D:\mavenrepo</url>
</pluginRepository>
</pluginRepositories>
If not, you may need to run a local server, e.g. apache, on your machines.
Additional to Vasil's answer: If you have the values given as a Scala collection, you can write
val list = List(1,2,3,4,5)
val arr = Array[Int](list:_*)
println(arr.mkString)
But usually the toArray method is more handy:
val list = List(1,2,3,4,5)
val arr = list.toArray
println(arr.mkString)
Have a look at this answer: Encrypt and decrypt with AES and Base64 encoding
We can get different return value from http_response_code via the two different environment:
At the web server environment, return previous response code if you provided a response code or when you do not provide any response code then it will be print the current value. Default value is 200 (OK).
At CLI Environment, true will be return if you provided a response code and false if you do not provide any response_code.
Example of Web Server Environment of Response_code's return value:
var_dump(http_respone_code(500)); // int(200)
var_dump(http_response_code()); // int(500)
Example of CLI Environment of Response_code's return value:
var_dump(http_response_code()); // bool(false)
var_dump(http_response_code(501)); // bool(true)
var_dump(http_response_code()); // int(501)
You can also fix this problem by adding to model (Entity Framework version >= 5)
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreationDate { get; set; }
copy *.csv new.csv
No need for /b as csv isn't a binary file type.
Here is a way.
We set-up options' string, in a list, just as we set-up command line arguments. In this case opts=['-g', 'videoID']
. Then, invoke youtube_dl.main(opts)
. In this way, we write our custom .py module, import youtube_dl
and then invoke the main()
function.
This is an old question, but it has no chosen answer, and I just solved this problem myself. Here's my solution:
Make sure you are set up to work with your Google API in the first place. See Google's list of prerequisites. I was working with Google My Business, so I also went through it's Get Started process.
In the OAuth 2.0 playground, Step 1 requires you to select which API you want to authenticate. Select or input as applicable for your case (in my case for Google My Business, I had to input https://www.googleapis.com/auth/plus.business.manage into the "Input your own scopes" input field). Note: this is the same as what's described in step 6 of the "Make a simple HTTP request" section of the Get Started guide.
Assuming successful authentication, you should get an "Access token" returned in the "Step 1's result" step in the OAuth playground. Copy this token to your clipboard.
Open Postman and open whichever collection you want as necessary.
In Postman, make sure "GET" is selected as the request type, and click on the "Authorization" tab below the request type drop-down.
In the Authorization "TYPE" dropdown menu, select "Bearer Token"
Paste your previously copied "Access Token" which you copied from the OAuth playground into the "Token" field which displays in Postman.
Almost there! To test if things work, put https://mybusiness.googleapis.com/v4/accounts/ into the main URL input bar in Postman and click the send button. You should get a JSON list of accounts back in the response that looks something like the following:
{
"accounts": [
{
"name": "accounts/REDACTED",
"accountName": "REDACTED",
"type": "PERSONAL",
"state": {
"status": "UNVERIFIED"
}
},
{
"name": "accounts/REDACTED",
"accountName": "REDACTED",
"type": "LOCATION_GROUP",
"role": "OWNER",
"state": {
"status": "UNVERIFIED"
},
"permissionLevel": "OWNER_LEVEL"
}
]
}
Here's some advice from someone with an environment where we have folders containing tens of millions of files.
To answer your question more directly: If you're looking at 100K entries, no worries. Go knock yourself out. If you're looking at tens of millions of entries, then either:
a) Make plans to sub-divide them into sub-folders (e.g., lets say you have 100M files. It's better to store them in 1000 folders so that you only have 100,000 files per folder than to store them into 1 big folder. This will create 1000 folder indices instead of a single big one that's more likely to hit the max # of fragments limit or
b) Make plans to run contig.exe on a regular basis to keep your big folder's index defragmented.
Read below only if you're bored.
The actual limit isn't on the # of fragment, but on the number of records of the data segment that stores the pointers to the fragment.
So what you have is a data segment that stores pointers to the fragments of the directory data. The directory data stores information about the sub-directories & sub-files that the directory supposedly stored. Actually, a directory doesn't "store" anything. It's just a tracking and presentation feature that presents the illusion of hierarchy to the user since the storage medium itself is linear.
The following query works. It uses each group to do the select instead of SelectMany
. SelectMany
works on each element from each collection. For example, in your query you have a result of 2 collections. SelectMany
gets all the results, a total of 3, instead of each collection. The following code works on each IGrouping
in the select portion to get your aggregate operations working correctly.
var results = from line in Lines
group line by line.ProductCode into g
select new ResultLine {
ProductName = g.First().Name,
Price = g.Sum(pc => pc.Price).ToString(),
Quantity = g.Count().ToString(),
};
You can use HTML tables on GitHub (but not on StackOverflow)
<table>
<tr>
<td>One</td>
<td>Two</td>
</tr>
<tr>
<td colspan="2">Three</td>
</tr>
</table>
Becomes
For me - here is a less confusing way of doing the socket.setTimeout
var request=require('https').get(
url
,function(response){
var r='';
response.on('data',function(chunk){
r+=chunk;
});
response.on('end',function(){
console.dir(r); //end up here if everything is good!
});
}).on('error',function(e){
console.dir(e.message); //end up here if the result returns an error
});
request.on('error',function(e){
console.dir(e); //end up here if a timeout
});
request.on('socket',function(socket){
socket.setTimeout(1000,function(){
request.abort(); //causes error event ?
});
});
I think it's better to use importlib.import_module('.c', __name__)
since you don't need to know about a
and b
.
I'm also wondering that, if you have to use importlib.import_module('a.b.c')
, why not just use import a.b.c
?
I have recently blogged on a solution that worked for me by using a Markdown XSLT file to transform the HTML Source. The HTML source will of course need to be valid XML first
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
I use a similar method to dasblinkenlight's in a function to return a single key value from a Cookie containing a JSON array loaded into a Dictionary as follows:
/// <summary>
/// Gets a single key Value from a Json filled cookie with 'cookiename','key'
/// </summary>
public static string GetSpecialCookieKeyVal(string _CookieName, string _key)
{
//CALL COOKIE VALUES INTO DICTIONARY
Dictionary<string, string> dictCookie =
JsonConvert.DeserializeObject<Dictionary<string, string>>
(MyCookinator.Get(_CookieName));
string value;
if (dictCookie.TryGetValue( _key, out value))
{
return value;
}
else
{
return "0";
}
}
Where "MyCookinator.Get()" is another simple Cookie function getting an http cookie overall value.
What is row?
Either of these could be correct.
1) I assume that you capture your ajax response in a javascript variable 'row'. If that is the case, this would hold true.
var result=row.split('|');
alert(result[2]);
otherwise
2) Use this where $(row)
is a jQuery
object.
var result=$(row).val().split('|');
alert(result[2]);
[As mentioned in the other answer, you may have to use $(row).val()
or $(row).text()
or $(row).html()
etc. depending on what $(row) is.]
Alternatively, and this would give you more flexibility if testing for values other than 1 or 2 in future, is to use a switch statement
switch(value)
{
case 1:
case 2:
return true;
default:
return false
}