Also check this article. Supposedly Microsoft released their Enterprise Library (v4.0) from their patterns and practices where they cover the validation subject but god knows why they didn't included validation for WPF, so the blog post I'm directing you to, explains what the author did to adapt it. Hope this helps!
This worked for me. :)
sudo keytool -importcert -file filename.cer -alias randomaliasname -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit
Hello was looking for the same, and it could be also
unlist(lapply(mtcars,class))
As noted in the answer provided by Tim Cooper, java.awt.Desktop
has provided this capability since Java version 6 (1.6), but with the following caveat:
For platforms which do not support or provide java.awt.Desktop
, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.
Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:
This code is Copyright 1999-2001 by Eric Albert ([email protected]) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.
Credits: Steven Spencer, JavaWorld magazine (Java Tip 66) Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.
Check by using mod - if there is a remainder, simply increment the value by one.
"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.
In the latter case Webpack is generally the best way since it supports code splitting.
For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)
I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds
The code can be found here: https://github.com/thelgevold/angular-2-samples
Angular version: 4.1.x
Please! Just ask w3 (http://www.quirksmode.org/dom/w3c_css.html)! Or actually, it took me five hours... but here it is!
function css(selector, property, value) {
for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
//Try add rule
try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
} catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
}
}
The function is really easy to use.. example:
<div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div>
Or:
<div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div>
Or:
<div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div>
Oh..
(function (scope) {
// Create a new stylesheet in the bottom
// of <head>, where the css rules will go
var style = document.createElement('style');
document.head.appendChild(style);
var stylesheet = style.sheet;
scope.css = function (selector, property, value) {
// Append the rule (Major browsers)
try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);
} catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)
} catch(err) {console.log("Couldn't add style");}} // (alien browsers)
}
})(window);
One more approach to reading a file that I happen to like is referred to variously as variable notation or variable syntax and involves simply enclosing a filespec within curly braces preceded by a dollar sign, to wit:
$content = ${C:file.txt}
This notation may be used as either an L-value or an R-value; thus, you could just as easily write to a file with something like this:
${D:\path\to\file.txt} = $content
Another handy use is that you can modify a file in place without a temporary file and without sub-expressions, for example:
${C:file.txt} = ${C:file.txt} | select -skip 1
I became fascinated by this notation initially because it was very difficult to find out anything about it! Even the PowerShell 2.0 specification mentions it only once showing just one line using it--but with no explanation or details of use at all. I have subsequently found this blog entry on PowerShell variables that gives some good insights.
One final note on using this: you must use a drive designation, i.e. ${drive:filespec}
as I have done in all the examples above. Without the drive (e.g. ${file.txt}
) it does not work. No restrictions on the filespec on that drive: it may be absolute or relative.
You can play here with different types and check the output,
export class ParentCmp {
myVar:stirng="micronyks";
myVal:any;
myArray:Array[]=[1,2,3];
myArr:Array[];
constructor() {
if(this.myVar){
console.log('has value') // answer
}
else{
console.log('no value');
}
if(this.myVal){
console.log('has value')
}
else{
console.log('no value'); //answer
}
if(this.myArray){
console.log('has value') //answer
}
else{
console.log('no value');
}
if(this.myArr){
console.log('has value')
}
else{
console.log('no value'); //answer
}
}
}
if you have two divs, you can use this to align the divs next to each other in the same row:
#keyword {_x000D_
float:left;_x000D_
margin-left:250px;_x000D_
position:absolute;_x000D_
}_x000D_
_x000D_
#bar {_x000D_
text-align:center;_x000D_
}
_x000D_
<div id="keyword">_x000D_
Keywords:_x000D_
</div>_x000D_
<div id="bar">_x000D_
<input type = textbox name ="keywords" value="" onSubmit="search()" maxlength=40>_x000D_
<input type = button name="go" Value="Go ahead and find" onClick="search()">_x000D_
</div>
_x000D_
I'd rather not rely on swap()
or setting the queue to a newly created queue object, because the queue elements are not properly destroyed. Calling pop()
invokes the destructor for the respective element object. This might not be an issue in <int>
queues but might very well have side effects on queues containing objects.
Therefore a loop with while(!queue.empty()) queue.pop();
seems unfortunately to be the most efficient solution at least for queues containing objects if you want to prevent possible side effects.
An updated version from Kelsey :
$(function GetInfo() {
var network = new ActiveXObject('WScript.Network');
alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;
});
To store the value, add these control :
<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />
Where you also can calling it from behind like this :
Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);
I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.
Here is another simpler way to check that.
$memory_limit = return_bytes(ini_get('memory_limit'));
if ($memory_limit < (64 * 1024 * 1024)) {
// Memory insufficient
}
/**
* Converts shorthand memory notation value to bytes
* From http://php.net/manual/en/function.ini-get.php
*
* @param $val Memory size shorthand notation string
*/
function return_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
$val = substr($val, 0, -1);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
• Debug: fine-grained statements concerning program state, typically used for debugging;
• Info: informational statements concerning program state, representing program events or behavior tracking;
• Warn: statements that describe potentially harmful events or states in the program;
• Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;
• Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.
Found on http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx
The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF]
protocol, and then there's the new version using Hybi formatted packets.
The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!
However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88
(better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.
I believe this is an issue with the target origin being https
. I suspect it is because your iFrame url is using http
instead of https
. Try changing the url of the file you are trying to embed to be https
.
For instance:
'//www.youtube.com/embed/' + id + '?showinfo=0&enablejsapi=1&origin=http://localhost:9000';
to be:
'https://www.youtube.com/embed/' + id + '?showinfo=0&enablejsapi=1&origin=http://localhost:9000';
Open up the Access File you are trying to export SQL data to. Delete any Queries that are there. Everytime you run SQL Server Import wizard, even if it fails, it creates a Query in the Access DB that has to be deleted before you can run the SQL export Wizard again.
All major browsers now include native JSON encoding/decoding.
// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject);
// To decode (This produces an object)
var obj = JSON.parse(json_str);
Note that only valid JSON data will be encoded. For example:
var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"
Valid JSON types are: objects, strings, numbers, arrays, true
, false
, and null
.
Some JSON resources:
See the following example
<!DOCTYPE html>
<html ng-app>
<head>
<title>Demo Changing CSS Classes Conditionally with Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="res/js/controllers.js"></script>
<style>
.checkboxList {
border:1px solid #000;
background-color:#fff;
color:#000;
width:300px;
height: 100px;
overflow-y: scroll;
}
.uncheckedClass {
background-color:#eeeeee;
color:black;
}
.checkedClass {
background-color:#3ab44a;
color:white;
}
</style>
</head>
<body ng-controller="TeamListCtrl">
<b>Teams</b>
<div id="teamCheckboxList" class="checkboxList">
<div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">
<label>
<input type="checkbox" ng-model="team.isChecked" />
<span>{{team.name}}</span>
</label>
</div>
</div>
</body>
</html>
Checkboxes, by design, are meant to be toggled on or off. They are not dependent on other checkboxes, so you can turn as many on and off as you wish.
Radio buttons, however, are designed to only allow one element of a group to be selected at any time.
References:
Checkboxes: MDN Link
Radio Buttons: MDN Link
Use the aggregate MAX(signin)
grouped by id. This will list the most recent signin
for each id
.
SELECT
id,
MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id
To get the whole single record, perform an INNER JOIN
against a subquery which returns only the MAX(signin)
per id.
SELECT
tbl.id,
signin,
signout
FROM tbl
INNER JOIN (
SELECT id, MAX(signin) AS maxsign FROM tbl GROUP BY id
) ms ON tbl.id = ms.id AND signin = maxsign
WHERE tbl.id=1
Your title question and your example are completely different. I'll start by answering the title question:
$("a").removeAttr("href");
And as far as not requiring an href, the generally accepted way of doing this is:
<a href"#" onclick="doWork(); return false;">link</a>
The return false is necessary so that the href doesn't actually go anywhere.
My solution would be to use filter after the map.
This should support every JS data type.
example:
const notUndefined = anyValue => typeof anyValue !== 'undefined'
const noUndefinedList = someList
.map(// mapping condition)
.filter(notUndefined); // by doing this,
//you can ensure what's returned is not undefined
find . -name "*.txt"|while read fname; do
echo "$fname"
done
Note: this method and the (second) method shown by bmargulies are safe to use with white space in the file/folder names.
In order to also have the - somewhat exotic - case of newlines in the file/folder names covered, you will have to resort to the -exec
predicate of find
like this:
find . -name '*.txt' -exec echo "{}" \;
The {}
is the placeholder for the found item and the \;
is used to terminate the -exec
predicate.
And for the sake of completeness let me add another variant - you gotta love the *nix ways for their versatility:
find . -name '*.txt' -print0|xargs -0 -n 1 echo
This would separate the printed items with a \0
character that isn't allowed in any of the file systems in file or folder names, to my knowledge, and therefore should cover all bases. xargs
picks them up one by one then ...
A good option is to use an API like Docverter. Docverter will allow you to convert HTML to PDF or DOCX using an API.
You can easily use imcache. A sample code is below.
void example(){
Cache<Integer,Integer> cache = CacheBuilder.heapCache().
cacheLoader(new CacheLoader<Integer, Integer>() {
public Integer load(Integer key) {
return null;
}
}).capacity(10000).build();
}
You can also init multiple values if your selectbox is a multipl:
$('#selectBox').val(['A', 'B', 'C']);
IF you are using Vector3 this is what i did
1- I create a class Name it Player
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
public Vector3[] Position;
}
2- then i call it like this
if ( _ispressed == true)
{
Player playerInstance = new Player();
playerInstance.Position = newPos;
string jsonData = JsonUtility.ToJson(playerInstance);
reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
Debug.Log(jsonData);
_ispressed = false;
}
3- and this is the result
"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}
To answer the question posted in the comment above - try something like this:
unsigned short int x = 65529U;
short int y = (short int)x;
printf("%d\n", y);
or
unsigned short int x = 65529U;
short int y = 0;
memcpy(&y, &x, sizeof(short int);
printf("%d\n", y);
I ended up moving the Umbrella Header to bottom of the Headers list after checking the above solutions, and that worked in Xcode 9.3.
You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}
APC definitely. It's written by the PHP guys, so even though it might not share the highest speeds, you can bet on the fact it's the highest quality.
Plus you get some other nifty features I use all the time (http://www.php.net/apc).
This issue can be resolved by setting the higher values for the MySQL variable innodb_buffer_pool_size
. The default value for innodb_buffer_pool_size
will be 8,388,608
.
To change the settings value for innodb_buffer_pool_size
please see the below set.
my.cnf
from the server. For Linux servers this will be mostly at /etc/my.cnf
innodb_buffer_pool_size=64MB
to this fileTo restart the MySQL server, you can use anyone of the below 2 options:
Reference The total number of locks exceeds the lock table size
In Swift3
For ex: a variable "Duke James Thomas", we need to get "James".
let name = "Duke James Thomas"
let range: Range<String.Index> = name.range(of:"James")!
let lastrange: Range<String.Index> = img.range(of:"Thomas")!
var middlename = name[range.lowerBound..<lstrange.lowerBound]
print (middlename)
nick's example saves it to your localhost.
But you can also save it to your local drive.
if you use doublebackslashes:
$filename= "Invoice.pdf";
$filelocation = "C:\\invoices";
$fileNL = $filelocation."\\".$filename;
$pdf->Output($fileNL,'F');
$pdf->Output($filename,'D'); // you cannot add file location here
P.S. In Firefox (optional) Tools> Options > General tab> Download >Always ask me where to save files
Something like this
string find = "item_manuf_id = 'some value'";
DataRow[] foundRows = table.Select(find);
SHA is a family of "Secure Hash Algorithms" that have been developed by the National Security Agency. There is currently a competition among dozens of options for who will become SHA-3, the new hash algorithm for 2012+.
You use SHA functions to take a large document and compute a "digest" (also called "hash") of the input. It's important to realize that this is a one-way process. You can't take a digest and recover the original document.
AES, the Advanced Encryption Standard is a symmetric block algorithm. This means that it takes 16 byte blocks and encrypts them. It is "symmetric" because the key allows for both encryption and decryption.
UPDATE: Keccak was named the SHA-3 winner on October 2, 2012.
Invoke-Expression
, also aliased as iex
. The following will work on your examples #2 and #3:
iex $command
Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:
$command = 'C:\somepath\someexe.exe somearg'
iex $command
However, if the exe is in quotes, you need the help of &
to get it running, as in this example, as run from the commandline:
>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"
And then in the script:
$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"
Likely, you could handle nearly all cases by detecting if the first character of the command string is "
, like in this naive implementation:
function myeval($command) {
if ($command[0] -eq '"') { iex "& $command" }
else { iex $command }
}
But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}
, perhaps for specific exception types/messages, or examine the command string.
If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
for me, just quick SimpleDateFormat,
private static final SimpleDateFormat GMT = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat SYD = new SimpleDateFormat("yyyy-MM-dd");
static {
GMT.setTimeZone(TimeZone.getTimeZone("GMT"));
SYD.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
}
then format the date with different timezone.
The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".
If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.
Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.
Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.
So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.
A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.
The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.
Either use:
pip install xlrd
And if you are using conda, use
conda install -c anaconda xlrd
That's it. good luck.
All the answers indicate the cause, but sometimes the bigger problem is identifying all the places that define an improper namespace. With tools like Resharper that automatically adjust the namespace using the folder structure, it is rather easy to encounter this issue.
You can get all the lines that create the issue by searching in project / solution using the following regex:
namespace .+\.TheNameUsedAsBothNamespaceAndType
It is likely something else, but for the future readers, check your date time format. i had a 14th month
I suppose that for asp.net 4 project we're moving to automatic restore, so there is no need for this. For older projects I think a bit of work to convert is needed.
http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
One possible solution to this problem is to add at Sencha CMD folder a bat file as sugested at this thread Sencha Cmd 5 + Java 8 Error.
The batch will have the name "sencha.bat" with this code:
@echo off
set JAVA_HOME=<YOUR JDK 7 HOME>
set PATH=%JAVA_HOME%\bin;%PATH%
set SENCHA_HOME=%~dp0
java -jar "%SENCHA_HOME%\sencha.jar" %*
Place it at sencha folder, in my case is
C:\Users\<YOUR USER>\bin\Sencha\Architect\Cmd\6.2.0.103
The following step is to change PATHEXT enviroment varible. Change at user variables to have the least impact possible.
I change from
COM;.CMD;.EXE;.BAT;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
to
COM;.BAT;.EXE;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
The idea is to make windows run .bat files first than .exe files. This is important because in sencha folder there is already an "sencha.exe" file. And in the command line if you type "sencha" it will execute "sencha.exe" instead of "sencha.bat".
This was the only solution that worked for because I'm very restricted when it comes to permissions.
That's correct. You can find more about it in the Oracle guide on varargs.
Here's an example:
void foo(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
which can be called as
foo("foo"); // Single arg.
foo("foo", "bar"); // Multiple args.
foo("foo", "bar", "lol"); // Don't matter how many!
foo(new String[] { "foo", "bar" }); // Arrays are also accepted.
foo(); // And even no args.
int a = srand(time(NULL))
arr[i] = a;
Should be
arr[i] = rand();
And put srand(time(NULL))
somewhere at the very beginning of your program.
Set up a batch file which you can invoke. Pass the path the batch file, and have the batch file set the environment variable and then invoke NUnit.
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
You can use a light weight webserver to serve the file.
For example,
1. install Node
2. install the "http-server" (or similar) package
3. Run the http-server package ( "http-server -c-1") from the folder where the script file is located
4. Load the script from chrome console (run the following script on chrome console
var ele = document.createElement("script");
var scriptPath = "http://localhost:8080/{scriptfilename}.js" //verify the script path
ele.setAttribute("src",scriptPath);
document.head.appendChild(ele)
You can use:
CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO
To create the login (See here for more details).
Then you may need to use:
CREATE USER user_name
To create the user associated with the login for the specific database you want to grant them access too.
(See here for details)
You can also use:
GRANT permission [ ,...n ] ON SCHEMA :: schema_name
To set up the permissions for the schema's that you assigned the users to.
(See here for details)
Two other commands you might find useful are ALTER USER and ALTER LOGIN.
I use this simple, clean and effective method.
I place arguments in an array, 1 per line. This way it is very easy to read and edit. Then I use a simple trick of passing all arguments inside double quotes to a function with 1 single parameter. That flattens them, including arrays, to a single string, which I then execute using PS's 'Invoke-Expression'. This directive is specifically designed to convert a string to runnable command. Works well:
# function with one argument will flatten
# all passed-in entries into 1 single string line
Function Execute($command) {
# execute:
Invoke-Expression $command;
# if you have trouble try:
# Invoke-Expression "& $command";
# or if you need also output to a variable
# Invoke-Expression $command | Tee-Object -Variable cmdOutput;
}
# ... your main code here ...
# The name of your executable app
$app = 'my_app.exe';
# List of arguments:
# Notice the type of quotes - important !
# Those in single quotes are normal strings, like 'Peter'
$args = 'arg1',
'arg2',
$some_variable,
'arg4',
"arg5='with quotes'",
'arg6',
"arg7 \ with \ $other_variable",
'etc...';
# pass all arguments inside double quotes
Execute "$app $args";
Go to src/enviroments/enviroments.ts
and enable the production mode
export const environment = {
production: true
};
for Angular 2
The pattern you want is something like (see it on rubular.com):
^[a-zA-Z0-9_.-]*$
Explanation:
^
is the beginning of the line anchor$
is the end of the line anchor[...]
is a character class definition*
is "zero-or-more" repetitionNote that the literal dash -
is the last character in the character class definition, otherwise it has a different meaning (i.e. range). The .
also has a different meaning outside character class definitions, but inside, it's just a literal .
Here's a snippet to show how you can use this pattern:
<?php
$arr = array(
'screen123.css',
'screen-new-file.css',
'screen_new.js',
'screen new file.css'
);
foreach ($arr as $s) {
if (preg_match('/^[\w.-]*$/', $s)) {
print "$s is a match\n";
} else {
print "$s is NO match!!!\n";
};
}
?>
The above prints (as seen on ideone.com):
screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!
Note that the pattern is slightly different, using \w
instead. This is the character class for "word character".
This seems to follow your specification, but note that this will match things like .....
, etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.
The above regex also matches the empty string. If you need at least one character, then use +
(one-or-more) instead of *
(zero-or-more) for repetition.
In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.
it's worked for me set tabindex to 0 this.yourtextbox.TabIndex = 0;
Here's an example of equal-height columns - Equal Height Columns - revisited
You can also check out the idea of "Faux Columns" as well - Faux Columns
Don't go the table route. If it's not tabular data, don't treat it as such. It's bad for accessibility and flexibility.
This might not be the best method, but you can ignore the conversion error if all else fails. Mine was an issue of nulls not converting properly, so I just ignored the error and the dates came in as dates and the nulls came in as nulls, so no data quality issues--not that this would always be the case. To do this, right click on your source, click Edit, then Error Output. Go to the column that's giving you grief and under Error change it to Ignore Failure.
I too got the same error, problem in my case is I included the column name in GROUP BY
clause and it caused this error. So removed the column from GROUP BY
clause and it worked!!!
try this easy
_x000D_
.btn-circle span {_x000D_
top: 0;_x000D_
_x000D_
position: absolute;_x000D_
font-size: 18px;_x000D_
text-align: center;_x000D_
text-decoration: none;_x000D_
-webkit-animation:spin 4s linear infinite;_x000D_
-moz-animation:spin 4s linear infinite;_x000D_
animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">↻</span></button>
_x000D_
You can't get a path to file from WhatsApp. They don't expose it now. The only thing you can get is InputStream
:
InputStream is = getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/16695"));
Using is
you can show a picture from WhatsApp in your app.
I was having this error w/Citect.
Microsoft Visual C++ 2005 Service Pack 1 Redistributable Package MFC Security Update has the missing files.
Selecting camera or gallery for image in Android
I had worked hard on Camera or gallery Image Selection, and created some util class for this work. With the use of these class 'Selecting image camera or gallery is too easy' it just took 5-10 mints of your development.
Step-1: Add these classes in your code.
ImagePickerUtils :- http://www.codesend.com/view/f8f7c637716bf1c693d1490635ed49b3/
BitmapUtils :- http://www.codesend.com/view/81c1c2a3f39f1f7e627f01f67be282cf/
ConvertUriToFilePath :- http://www.codesend.com/view/f4668a29860235dd1b66eb419c5a58b5/
MediaUtils :- https://codeshare.io/5vKEMl
We need to Add these Permission in menifest :
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
This class function (checkAndRequestPermissions) auto check the permission in Android-Marshmallow and Android - Nougat.
Step-2. Calling camera class for launching camera intent :
//Create a global veriable .
private Uri mCameraUri;
private static final int CAMERA_REQUEST_CODE = 100;
// Call this function when you wants to select or capture an Image.
mCameraUri = ImagePickerUtils.createTakePictureIntent(this, CAMERA_REQUEST_CODE);
Step-3: Add onActivityResult in your Activity for receiving data from Intent
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Uri fileUri = ImagePickerUtils.getFileUriOfImage(this, data, mCameraUri);
try {
Bitmap bitmap = null;
if (CAMERA_REQUEST_CODE == requestCode) {
bitmap = new BitmapUtils().getDownsampledBitmap(this, fileUri, imageView.getWidth(), imageView.getHeight());
}
if (bitmap != null)
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I hope it helps you, If any one having any suggestion to improve these class please add your review in comments.
const isChrome = /Chrome/.test(navigator.userAgent)
const isFirefox = /Firefox/.test(navigator.userAgent)
Here is how to include latest bootstrap
https://react-bootstrap.github.io/getting-started/introduction
1.Install
npm install react-bootstrap bootstrap
then import to App.js import 'bootstrap/dist/css/bootstrap.min.css';
Then you need to import the components that you use at your app, example If you use navbar, nav, button, form, formcontrol then import all of these like below:
import Navbar from 'react-bootstrap/Navbar'
import Nav from 'react-bootstrap/Nav'
import Form from 'react-bootstrap/Form'
import FormControl from 'react-bootstrap/FormControl'
import Button from 'react-bootstrap/Button'
// or less ideally
import { Button } from 'react-bootstrap';
I change the class with implements TextWatcher to use Brasil currency formats and adjusting cursor position when editing the value.
public class MoneyTextWatcher implements TextWatcher { private EditText editText; private String lastAmount = ""; private int lastCursorPosition = -1; public MoneyTextWatcher(EditText editText) { super(); this.editText = editText; } @Override public void onTextChanged(CharSequence amount, int start, int before, int count) { if (!amount.toString().equals(lastAmount)) { String cleanString = clearCurrencyToNumber(amount.toString()); try { String formattedAmount = transformToCurrency(cleanString); editText.removeTextChangedListener(this); editText.setText(formattedAmount); editText.setSelection(formattedAmount.length()); editText.addTextChangedListener(this); if (lastCursorPosition != lastAmount.length() && lastCursorPosition != -1) { int lengthDelta = formattedAmount.length() - lastAmount.length(); int newCursorOffset = max(0, min(formattedAmount.length(), lastCursorPosition + lengthDelta)); editText.setSelection(newCursorOffset); } } catch (Exception e) { //log something } } } @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { String value = s.toString(); if(!value.equals("")){ String cleanString = clearCurrencyToNumber(value); String formattedAmount = transformToCurrency(cleanString); lastAmount = formattedAmount; lastCursorPosition = editText.getSelectionStart(); } } public static String clearCurrencyToNumber(String currencyValue) { String result = null; if (currencyValue == null) { result = ""; } else { result = currencyValue.replaceAll("[(a-z)|(A-Z)|($,. )]", ""); } return result; } public static boolean isCurrencyValue(String currencyValue, boolean podeSerZero) { boolean result; if (currencyValue == null || currencyValue.length() == 0) { result = false; } else { if (!podeSerZero && currencyValue.equals("0,00")) { result = false; } else { result = true; } } return result; } public static String transformToCurrency(String value) { double parsed = Double.parseDouble(value); String formatted = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")).format((parsed / 100)); formatted = formatted.replaceAll("[^(0-9)(.,)]", ""); return formatted; } }
Check all the references carefully
For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.
C++11 update of preferred solution:
#include <limits>
#include <type_traits>
template <typename T>
typename std::enable_if<std::numeric_limits<T>::is_integer, unsigned int>::type
numberDigits(T value) {
unsigned int digits = 0;
if (value < 0) digits = 1;
while (value) {
value /= 10;
++digits;
}
return digits;
}
prevents template instantiation with double, et. al.
It really depends on what language you're using, but in C# and Java I find IDEs beneficial for:
All of these save time. They're things I could do manually, but with more pain: I'd rather be coding.
Without changing the position to absolute, see below. This supports all recent browsers as well.
.vranger {_x000D_
margin-top: 50px;_x000D_
transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg); /*do same for other browsers if required*/_x000D_
}
_x000D_
<input type="range" class="vranger"/>
_x000D_
for very old browsers, you can use -sand-transform: rotate(10deg);
from CSS sandpaper
or use
prefix selector such as -ms-transform: rotate(270deg);
for IE9
e.g (in pseudo code)
int myInt = random(0, numcharacters)
char[] codealphabet = 'ABCDEF12345'
char random = codealphabet[i]
repeat until long enough
To use session variables, it's necessary to start the session by using the session_start
function, this will allow you to store your data in the global variable $_SESSION
in a productive way.
so your code will finally look like this :
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['picturenum'] = $_POST['picturenum'];
}
?>
<strong><?php echo $_SESSION['picturenum'];?></strong>
to make it easy to use and to avoid forgetting it again, you can create a session_file.php
which you will want to be included in all your codes and will start the session for you:
session_start.php
<?php
session_start();
?>
and then include it wherever you like :
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// including the session file
require_once("session_start.php");
if (isset($_POST['Submit'])) {
$_SESSION['picturenum'] = $_POST['picturenum'];
}
?>
that way it is more portable and easy to maintain in the future.
other remarks
if you are using Apache version 2 or newer, be careful. instead of
<?
to open php's tags, use
<?php
, otherwise your code will not be interpreted
variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters
good work!
gcc can actually compile c++ code just fine. The errors you received are linker errors, not compiler errors.
Odds are that if you change the compilation line to be this:
gcc info.C -lstdc++
which makes it link to the standard c++ library, then it will work just fine.
However, you should just make your life easier and use g++.
EDIT:
Rup says it best in his comment to another answer:
[...] gcc will select the correct back-end compiler based on file extension (i.e. will compile a .c as C and a .cc as C++) and links binaries against just the standard C and GCC helper libraries by default regardless of input languages; g++ will also select the correct back-end based on extension except that I think it compiles all C source as C++ instead (i.e. it compiles both .c and .cc as C++) and it includes libstdc++ in its link step regardless of input languages.
There is an important part of the conversation surrounding lexical and dynamic scoping that is missing: a plain explanation of the lifetime of the scoped variable - or when the variable can be accessed.
Dynamic scoping only very loosely corresponds to "global" scoping in the way that we traditionally think about it (the reason I bring up the comparison between the two is that it has already been mentioned - and I don't particularly like the linked article's explanation); it is probably best we don't make the comparison between global and dynamic - though supposedly, according to the linked article, "...[it] is useful as a substitute for globally scoped variables."
So, in plain English, what's the important distinction between the two scoping mechanisms?
Lexical scoping has been defined very well throughout the answers above: lexically scoped variables are available - or, accessible - at the local level of the function in which it was defined.
However - as it is not the focus of the OP - dynamic scoping has not received a great deal of attention and the attention it has received means it probably needs a bit more (that's not a criticism of other answers, but rather a "oh, that answer made we wish there was a bit more"). So, here's a little bit more:
Dynamic scoping means that a variable is accessible to the larger program during the lifetime of the function call - or, while the function is executing. Really, Wikipedia actually does a nice job with the explanation of the difference between the two. So as not to obfuscate it, here is the text that describes dynamic scoping:
...[I]n dynamic scoping (or dynamic scope), if a variable name's scope is a certain function, then its scope is the time-period during which the function is executing: while the function is running, the variable name exists, and is bound to its variable, but after the function returns, the variable name does not exist.
Another option can be to utilize the tagName
property of the e.target
. It doesn't apply exactly here, but let's say I have a class of something that's applied to either a DIV
or an A
tag, and I want to see if that class was clicked, and determine whether it was the DIV
or the A
that was clicked. I can do something like:
$('.example-class').click(function(e){
if ((e.target.tagName.toLowerCase()) == 'a') {
console.log('You clicked an A element.');
} else { // DIV, we assume in this example
console.log('You clicked a DIV element.');
}
});
Just took a look over the mustache docs and they support "inverted sections" in which they state
they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list
http://mustache.github.io/mustache.5.html#Inverted-Sections
{{#value}}
value is true
{{/value}}
{{^value}}
value is false
{{/value}}
I've seen a couple of answers referencing the cut
command, but they've all been deleted. It's a little odd that nobody has elaborated on that, because I think it's one of the more useful commands for doing this type of thing, especially for parsing delimited log files.
In the case of splitting this specific example into a bash script array, tr
is probably more efficient, but cut
can be used, and is more effective if you want to pull specific fields from the middle.
Example:
$ echo "[email protected];[email protected]" | cut -d ";" -f 1
[email protected]
$ echo "[email protected];[email protected]" | cut -d ";" -f 2
[email protected]
You can obviously put that into a loop, and iterate the -f parameter to pull each field independently.
This gets more useful when you have a delimited log file with rows like this:
2015-04-27|12345|some action|an attribute|meta data
cut
is very handy to be able to cat
this file and select a particular field for further processing.
You can do something like the following:
mysqldump -u[username] -p[password] database_name_for_clone
| mysql -u[username] -p[password] new_database_name
If tdd='<td class="abc"> 75</td>'
In Beautifulsoup
if(tdd.has_attr('class')):
print(tdd.attrs['class'][0])
Result: abc
Nine years later. If you know your time zone. I like the T
between date and time. And if you don't want microseconds.
Python <= 3.8
pip3 install pytz # needed!
python3
>>> import datetime
>>> import pytz
>>> datetime.datetime.now(pytz.timezone('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:23:28+01:00'
Tested on Ubuntu 18.04 and Python 3.6.9.
Python >= 3.9
pip3 install tzdata # only on Windows needed!
py -3
>>> import datetime
>>> import zoneinfo
>>> datetime.datetime.now(zoneinfo.ZoneInfo('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:39:36+01:00'
Tested on Windows 10 and Python 3.9.0.
Just adding more info, I wasn't able to find sn.exe utility in the mentioned locations, in my case it was in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin
give this style to td: width: 1%;
standalone one cell solution based on VLOOKUP
=IFERROR(ARRAYFORMULA(IF(LEN(A2:A),
IF(A2:A>2000, "More than 2000",VLOOKUP(A2:A,
{{(TRANSPOSE({{{0; "Less than 500"},
{500; "Between 500 and 1000"}},
{{1000; "Between 1000 and 1500"},
{1500; "Between 1500 and 2000"}}}))}}, 2)),)), )
=IFERROR(ARRAYFORMULA(IF(LEN(A2:A);
IF(A2:A>2000; "More than 2000";VLOOKUP(A2:A;
{{(TRANSPOSE({{{0; "Less than 500"}\
{500; "Between 500 and 1000"}}\
{{1000; "Between 1000 and 1500"}\
{1500; "Between 1500 and 2000"}}}))}}; 2));)); )
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.
For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).
Greets
Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases. However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):
RouterModule.forRoot([{ path: "", component: LoginComponent}])
I was looking back at this question and I thought to myself, maybe we are aproaching this problem the wrong way. Interfaces might not be the way to go when it concerns defining a constructor with certain parameters... but an (abstract) base class is.
If you create a base class with a constructor on there that accepts the parameters you need, every class that derrives from it needs to supply them.
public abstract class Foo
{
protected Foo(SomeParameter x)
{
this.X = x;
}
public SomeParameter X { get; private set }
}
public class Bar : Foo // Bar inherits from Foo
{
public Bar()
: base(new SomeParameter("etc...")) // Bar will need to supply the constructor param
{
}
}
<div>
<img class="crop" src="http://lorempixel.com/500/200"/>
</div>
<img src="http://lorempixel.com/500/200"/>
div {
width: 200px;
height: 200px;
overflow: hidden;
margin: 10px;
position: relative;
}
.crop {
position: absolute;
left: -100%;
right: -100%;
top: -100%;
bottom: -100%;
margin: auto;
height: auto;
width: auto;
}
FWIW- I just ran across this as well, it was in the context of a cancelled selenium run. Perhaps there was a sub-shell being instantiated and left in place. Closing that terminal window and opening a new one was all I needed to do. (macOS Sierra)
Yes, they are all the same.
We can review the interpreted machine code to confirm that that they're all doing the exact same thing.
import dis
def f1():
print "Hello World"
return None
def f2():
print "Hello World"
return
def f3():
print "Hello World"
dis.dis(f1)
4 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f2)
9 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
10 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f3)
14 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
try like this (no pun intended btw)
script {
try {
sh 'do your stuff'
} catch (Exception e) {
echo 'Exception occurred: ' + e.toString()
sh 'Handle the exception!'
}
}
The key is to put try...catch in a script block in declarative pipeline syntax. Then it will work. This might be useful if you want to say continue pipeline execution despite failure (eg: test failed, still you need reports..)
try it, maybe useful...
box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 3px #cbc9c9;
-webkit-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
-o-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
-moz-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
above CSS
cause you have a box shadow in bottom.
you can red more Here
If you're only interested in bailing if a particular argument is missing, Parameter Substitution is great:
#!/bin/bash
# usage-message.sh
: ${1?"Usage: $0 ARGUMENT"}
# Script exits here if command-line parameter absent,
#+ with following error message.
# usage-message.sh: 1: Usage: usage-message.sh ARGUMENT
Following are some key points :
Conclusion
Another approach would be to deserialize into a java.util.Map
, and then just modify the Java Map
as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
if you are running Intel processor make sure HAXM (Intel® Hardware Accelerated Execution Manager) installer is install via SDK Manager by checking this option in SDK Manager. and then run the HAXM installer ext via the path below
your_sdk_folder\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe
also check the ram size allocated while doing HAX installation so it fits the ram size of your emulator.
This video shows all the required steps which may help you to solve the problem.
This video will also help you if you face problem after installing HAXM.
->
is used to call a method, or access a property, on the object of a class
=>
is used to assign values to the keys of an array
E.g.:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34, 1=>2);
And since PHP 7.4+ the operator =>
is used too for the added arrow functions, a more concise syntax for anonymous functions.
You installed Python and added it to PATH. You've checked it too(like 64-bit etc). Everything should work but it is not.
what you didn't do is a
terminal/cmd restart
restart your terminal and everything would work like a charm.
I Hope, it helped/might help others.
Apply these changes in phpmyconfig/config.inc. Type in your username and password that you have set:
$cfg['Servers'][$i]['user'] = 'user';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
This works for me.
For this issue, Use JQuery and other js same as you are using in Web Page. However, Electron has node integration so it will not find your js objects. You have to set module = undefined
until your js objects are loaded properly. See below example
<!-- Insert this line above local script tags -->
<script>if (typeof module === 'object') {window.module = module; module =
undefined;}</script>
<!-- normal script imports etc -->
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<!-- Insert this line after script tags -->
<script>if (window.module) module = window.module;</script>
After importing like given, you will be able to use the JQuery
and other things in electron.
The thread is very old, but I came looking for answer here hence providing new solution.
With MongoDB version 3.6+, it is now possible to use the positional operator to update all items in an array. See official documentation here.
Following query would work for the question asked here. I have also verified with Java-MongoDB driver and it works successfully.
.update( // or updateMany directly, removing the flag for 'multi'
{"events.profile":10},
{$set:{"events.$[].handled":0}}, // notice the empty brackets after '$' opearor
false,
true
)
Hope this helps someone like me.
Commit: Snapshot | Changeset | Version | History-record | 'Save-as' of a repository. Git repository = series (tree) of commits.
Local repository: repository on your computer.
Remote repository: repository on a server (Github).
git commit
: Append a new commit (last commit + staged modifications) to the local repository. (Commits are stored in /.git
)
git push
, git pull
: Sync the local repository with its associated remote repository. push
- apply changes from local into remote, pull
- apply changes from remote into local.
To convert the string to an actual dict, you can do df['Pollutant Levels'].map(eval)
. Afterwards, the solution below can be used to convert the dict to different columns.
Using a small example, you can use .apply(pd.Series)
:
In [2]: df = pd.DataFrame({'a':[1,2,3], 'b':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})
In [3]: df
Out[3]:
a b
0 1 {u'c': 1}
1 2 {u'd': 3}
2 3 {u'c': 5, u'd': 6}
In [4]: df['b'].apply(pd.Series)
Out[4]:
c d
0 1.0 NaN
1 NaN 3.0
2 5.0 6.0
To combine it with the rest of the dataframe, you can concat
the other columns with the above result:
In [7]: pd.concat([df.drop(['b'], axis=1), df['b'].apply(pd.Series)], axis=1)
Out[7]:
a c d
0 1 1.0 NaN
1 2 NaN 3.0
2 3 5.0 6.0
Using your code, this also works if I leave out the iloc
part:
In [15]: pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)
Out[15]:
a c d
0 1 1.0 NaN
1 2 NaN 3.0
2 3 5.0 6.0
I needed to get the last id way after inserting it, so
$lastid = $wpdb->insert_id;
Was not an option.
Did the follow:
global $wpdb;
$id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');
send output to console, append to console log, delete output from current command
dir >> usb-create.1 && type usb-create.1 >> usb-create.log | type usb-create.1 && del usb-create.1
This thing can easily be done by implementing a public class that implements Comparable. This will allow you to use compareTo method which can be used with any other object to which you wish to compare.
for example you can implement it in this way:
public String compareTo(Animal oth)
{
return String.compare(this.population, oth.population);
}
I think this might solve your purpose.
```yaml
{
"this-json": "looks awesome..."
}
If you want to have keys a different colour to the parameters, set your language as yaml
@Ankanna's answer gave me the idea of going through github's supported language list and yaml
was my best find.
As a little memo: the interactive link anatomy
--
In short (assuming a location of http://example.org:8888/foo/bar#bang
):
hostname
gives you example.org
host
gives you example.org:8888
Perhaps a temporary table will do what you want.
CREATE TEMPORARY TABLE SalesSummary (
product_name VARCHAR(50) NOT NULL
, total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
, avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
, total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
) ENGINE=MEMORY;
INSERT INTO SalesSummary
(product_name, total_sales, avg_unit_price, total_units_sold)
SELECT
p.name
, SUM(oi.sales_amount)
, AVG(oi.unit_price)
, SUM(oi.quantity_sold)
FROM OrderItems oi
INNER JOIN Products p
ON oi.product_id = p.product_id
GROUP BY p.name;
/* Just output the table */
SELECT * FROM SalesSummary;
/* OK, get the highest selling product from the table */
SELECT product_name AS "Top Seller"
FROM SalesSummary
ORDER BY total_sales DESC
LIMIT 1;
/* Explicitly destroy the table */
DROP TABLE SalesSummary;
From forge.mysql.com. See also the temporary tables piece of this article.
>>> x = (u'2',)
>>> x += u"random string"
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", ) # concatenate a one-tuple instead
>>> x
(u'2', u'random string')
subprocess: The
subprocess
module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
http://docs.python.org/library/subprocess.html
Usage:
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
Here's a function I wrote another application. Feel free to reuse:
function writeCookie (key, value, days) {
var date = new Date();
// Default at 365 days.
days = days || 365;
// Get unix milliseconds at current time plus number of days
date.setTime(+ date + (days * 86400000)); //24 * 60 * 60 * 1000
window.document.cookie = key + "=" + value + "; expires=" + date.toGMTString() + "; path=/";
return value;
};
This appears to be a more general SWING/AWT/JDK problem that just the JBOSS installer:
The accepted answer below solved the issue for me :
Unable to run java gui programs with ubuntu
("sudo apt-get install openjdk-6-jdk")
Answered a question such as this before, you can take a look at the results here:
Creating form to have fields and text next to each other - what is the semantic way to do it?
So to apply the same rules to your fiddle you can use display:inline-block
to display your label and input groups side by side, like so:
CSS
input {
margin-top: 5px;
margin-bottom: 5px;
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
vertical-align:middle;
margin-left:20px
}
label {
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
float: left;
padding-top: 5px;
text-align: right;
width: 140px;
}
One more option, not exactly what you asked, but can be useful:
Go to Settings
-> Editor
-> File and code templates
-> Includes
tab (on the right). There is a template header for the new files, you can use the username here:
/**
* @author myname
*/
For system username use:
/**
* @author ${USER}
*/
I have tried these hash functions and got the following result. I have about 960^3 entries, each 64 bytes long, 64 chars in different order, hash value 32bit. Codes from here.
Hash function | collision rate | how many minutes to finish
==============================================================
MurmurHash3 | 6.?% | 4m15s
Jenkins One.. | 6.1% | 6m54s
Bob, 1st in link | 6.16% | 5m34s
SuperFastHash | 10% | 4m58s
bernstein | 20% | 14s only finish 1/20
one_at_a_time | 6.16% | 7m5s
crc | 6.16% | 7m56s
One strange things is that almost all the hash functions have 6% collision rate for my data.
My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!
I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:
# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root virsh start download
I think this is correct, and hope it helps someone else too.
You're doing things in the wrong order.
You need to first add all JComponents to the JFrame, and only then call pack()
and then setVisible(true)
on the JFrame
If you later added JComponents that could change the GUI's size you will need to call pack()
again, and then repaint()
on the JFrame after doing so.
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
When you define your function using this syntax:
def someFunc(*args):
for x in args
print x
You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:
def someFunc(myList = [], *args):
for x in myList:
print x
Then you can call it with this:
items = [1,2,3,4,5]
someFunc(items)
You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:
def someFunc(arg1, arg2, arg3, *args, **kwargs):
for x in args
print x
Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.
There are three simple ways:
By separator:
s.split("separator") | s.split('/') | s.split(char::is_numeric)
By whitespace:
s.split_whitespace()
By newlines:
s.lines()
By regex: (using regex
crate)
Regex::new(r"\s").unwrap().split("one two three")
The result of each kind is an iterator:
let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();
assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());
assert_eq!(None, lines.next());
More usable
#include <sys/types.h>
#include <sys/sysctl.h>
@interface UIDevice(Hardware)
- (NSString *) platform;
- (BOOL)hasRetinaDisplay;
- (BOOL)hasMultitasking;
- (BOOL)hasCamera;
@end
@implementation UIDevice(Hardware)
- (NSString *) platform{
int mib[2];
size_t len;
char *machine;
mib[0] = CTL_HW;
mib[1] = HW_MACHINE;
sysctl(mib, 2, NULL, &len, NULL, 0);
machine = malloc(len);
sysctl(mib, 2, machine, &len, NULL, 0);
NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
free(machine);
return platform;
}
- (BOOL)hasRetinaDisplay {
NSString *platform = [self platform];
BOOL ret = YES;
if ([platform isEqualToString:@"iPhone1,1"]) {
ret = NO;
}
else
if ([platform isEqualToString:@"iPhone1,2"]) ret = NO;
else
if ([platform isEqualToString:@"iPhone2,1"]) ret = NO;
else
if ([platform isEqualToString:@"iPod1,1"]) ret = NO;
else
if ([platform isEqualToString:@"iPod2,1"]) ret = NO;
else
if ([platform isEqualToString:@"iPod3,1"]) ret = NO;
return ret;
}
- (BOOL)hasMultitasking {
if ([self respondsToSelector:@selector(isMultitaskingSupported)]) {
return [self isMultitaskingSupported];
}
return NO;
}
- (BOOL)hasCamera {
BOOL ret = NO;
// check camera availability
return ret;
}
@end
you can reading properties with
NSLog(@"platform %@, retita %@, multitasking %@", [[UIDevice currentDevice] platform], [[UIDevice currentDevice] hasRetinaDisplay] ? @"YES" : @"NO" , [[UIDevice currentDevice] hasMultitasking] ? @"YES" : @"NO");
body {
width: calc( 100% );
max-width: calc( 100vw - 1em );
}
works with default scroll bars as well. could add:
overflow-x: hidden;
to ensure horizontal scroll bars remain hidden for the parent frame. unless this is desired from your clients.
req
is an object containing information about the HTTP request that raised the event. In response to req
, you use res
to send back the desired HTTP response.
Those parameters can be named anything. You could change that code to this if it's more clear:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Edit:
Say you have this method:
app.get('/people.json', function(request, response) { });
The request will be an object with properties like these (just to name a few):
request.url
, which will be "/people.json"
when this particular action is triggeredrequest.method
, which will be "GET"
in this case, hence the app.get()
call.request.headers
, containing items like request.headers.accept
, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.request.query
(e.g. /people.json?foo=bar
would result in request.query.foo
containing the string "bar"
).To respond to that request, you use the response object to build your response. To expand on the people.json
example:
app.get('/people.json', function(request, response) {
// We want to set the content-type header so that the browser understands
// the content of the response.
response.contentType('application/json');
// Normally, the data is fetched from a database, but we can cheat:
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
// Since the request is for a JSON representation of the people, we
// should JSON serialize them. The built-in JSON.stringify() function
// does that.
var peopleJSON = JSON.stringify(people);
// Now, we can use the response object's send method to push that string
// of people JSON back to the browser in response to this request:
response.send(peopleJSON);
});
FYI: If you need to specify a new startvalue between a range of IDs (256 - 10000000 for example):
SELECT setval('"Sequence_Name"',
(SELECT coalesce(MAX("ID"),255)
FROM "Table_Name"
WHERE "ID" < 10000000 and "ID" >= 256)+1
);
It sounds like you're looking for applicationHost.config
, which is located in C:\Windows\System32\inetsrv\config
.
Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config
and web.config
.
According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"
See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]
You can split on an empty string:
var chars = "overpopulation".split('');
If you just want to access a string in an array-like fashion, you can do that without split
:
var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
console.log(s.charAt(i));
}
You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).
var s = "overpopulation";
console.log(s[3]); // logs 'r'
I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:
#!/bin/bash
# flvcache script
CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M
for f in `find $CACHE -size +$MINFILESIZE`
do
a=$(file $f | cut -f2 -d ' ')
o=$(basename $f)
if [ "$a" = "Macromedia" ]
then
cp "$f" "$OUTPUTDIR/$o"
fi
done
nautilus "$OUTPUTDIR"&
It uses similar ideas to those presented here, hope this is helpful to someone.
The correct character to use in this case is a full colon (:
), not a semicolon (;
).
According to the Box-cox transformation formula in the paper Box,George E. P.; Cox,D.R.(1964). "An analysis of transformations", I think mlegge's post might need to be slightly edited.The transformed y should be (y^(lambda)-1)/lambda instead of y^(lambda). (Actually, y^(lambda) is called Tukey transformation, which is another distinct transformation formula.)
So, the code should be:
(trans <- bc$x[which.max(bc$y)])
[1] 0.4242424
# re-run with transformation
mnew <- lm(((y^trans-1)/trans) ~ x) # Instead of mnew <- lm(y^trans ~ x)
Correct implementation of Box-Cox transformation formula by boxcox() in R:
https://www.r-bloggers.com/on-box-cox-transform-in-regression-models/
A great comparison between Box-Cox transformation and Tukey transformation. http://onlinestatbook.com/2/transformations/box-cox.html
One could also find the Box-Cox transformation formula on Wikipedia: en.wikipedia.org/wiki/Power_transform#Box.E2.80.93Cox_transformation
Please correct me if I misunderstood it.
Even in base Python you can do the computation in generic form
result = sum(x**2 for x in some_vector) ** 0.5
x ** 2
is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).
Using instead x ** 0.5
to take the square root doesn't do the exact same computations as math.sqrt
as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.
I often use x ** 0.5
simply because I don't want to add math
just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.
Another solution is to make a runtime hook, which will copy(or move) your data (files/folders) to the directory at which the executable is stored. The hook is a simple python file that can almost do anything, just before the execution of your app. In order to set it, you should use the --runtime-hook=my_hook.py
option of pyinstaller. So, in case your data is an images folder, you should run the command:
pyinstaller.py --onefile -F --add-data=images;images --runtime-hook=cp_images_hook.py main.py
The cp_images_hook.py could be something like this:
import sys
import os
import shutil
path = getattr(sys, '_MEIPASS', os.getcwd())
full_path = path+"\\images"
try:
shutil.move(full_path, ".\\images")
except:
print("Cannot create 'images' folder. Already exists.")
Before every execution the images folder is moved to the current directory (from the _MEIPASS folder), so the executable will always have access to it. In that way there is no need to modify your project's code.
You can take advantage of the runtime-hook mechanism and change the current directory, which is not a good practice according to some developers, but it works fine.
The hook code can be found below:
import sys
import os
path = getattr(sys, '_MEIPASS', os.getcwd())
os.chdir(path)
You are probably missing the viewport meta tag in the html head:
<meta name="viewport" content="width=device-width, initial-scale=1">
Without it the device assumes and sets the viewport to full size.
More info here.
Simple code that finds the mode of the list without any imports:
nums = #your_list_goes_here
nums.sort()
counts = dict()
for i in nums:
counts[i] = counts.get(i, 0) + 1
mode = max(counts, key=counts.get)
In case of multiple modes, it should return the minimum node.
Or, failing mutt:
gzip -c mysqldbbackup.sql | uuencode mysqldbbackup.sql.gz | mail -s "MySQL DB" [email protected]
A list is considered to be False
if it has no elements, so you can do something like this:
{% if mylist %}
<p>I have a list!</p>
{% else %}
<p>I don't have a list!</p>
{% endif %}
File f1 = new File("..\\..\\..\\config.properties");
this path trying to access file is in Project directory then just access file like this.
File f=new File("filename.txt");
if your file is in OtherSources/Resources
this.getClass().getClassLoader().getResource("relative path");//-> relative path from resources folder
Using a Android clientId (no client_secret) I was getting the following error response:
{
"error": "invalid_grant",
"error_description": "Missing code verifier."
}
I cannot find any documentation for the field 'code_verifier' but I discovered if you set it to equal values in both the authorization and token requests it will remove this error. I'm not sure what the intended value should be or if it should be secure. It has some minimum length (16? characters) but I found setting to null
also works.
I am using AppAuth for the authorization request in my Android client which has a setCodeVerifier()
function.
AuthorizationRequest authRequest = new AuthorizationRequest.Builder(
serviceConfiguration,
provider.getClientId(),
ResponseTypeValues.CODE,
provider.getRedirectUri()
)
.setScope(provider.getScope())
.setCodeVerifier(null)
.build();
Here is an example token request in node:
request.post(
'https://www.googleapis.com/oauth2/v4/token',
{ form: {
'code': '4/xxxxxxxxxxxxxxxxxxxx',
'code_verifier': null,
'client_id': 'xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'client_secret': null,
'redirect_uri': 'com.domain.app:/oauth2redirect',
'grant_type': 'authorization_code'
} },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Success!');
} else {
console.log(response.statusCode + ' ' + error);
}
console.log(body);
}
);
I tested and this works with both https://www.googleapis.com/oauth2/v4/token
and https://accounts.google.com/o/oauth2/token
.
If you are using GoogleAuthorizationCodeTokenRequest
instead:
final GoogleAuthorizationCodeTokenRequest req = new GoogleAuthorizationCodeTokenRequest(
TRANSPORT,
JSON_FACTORY,
getClientId(),
getClientSecret(),
code,
redirectUrl
);
req.set("code_verifier", null);
GoogleTokenResponse response = req.execute();
This discussion helped me resolve the issue I was struggling with for days. I looked around all over the internet until I found the answered by Jim Tough on May 18 '11 at 15:17. With that answer I was able to connect. Now I want to give back and help others with a complete example. Here goes:
import java.sql.*;
public class MyDBConnect {
public static void main(String[] args) throws SQLException {
try {
String dbURL = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=whatEverYourHostNameIs)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=yourServiceName)))";
String strUserID = "yourUserId";
String strPassword = "yourPassword";
Connection myConnection=DriverManager.getConnection(dbURL,strUserID,strPassword);
Statement sqlStatement = myConnection.createStatement();
String readRecordSQL = "select * from sa_work_order where WORK_ORDER_NO = '1503090' ";
ResultSet myResultSet = sqlStatement.executeQuery(readRecordSQL);
while (myResultSet.next()) {
System.out.println("Record values: " + myResultSet.getString("WORK_ORDER_NO"));
}
myResultSet.close();
myConnection.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="click me"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_weight="0.5"/>
</LinearLayout>
Pass the variable to the form element like this
your form element
<input type="text" id="mytext">
javascript
var test = "Hello";
document.getElementById("mytext").value = test;//Now you get the js variable inside your form element
A really good way to make a tooltip is described here: Simple D3 tooltip example
You have to append a div
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
Then you can just toggle it using
.on("mouseover", function(){return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});
d3.event.pageX
/ d3.event.pageY
is the current mouse coordinate.
If you want to change the text you can use tooltip.text("my tooltip text");
You could put it in a function.
String paramStr = "a parameter";
Runnable myRunnable = createRunnable(paramStr);
private Runnable createRunnable(final String paramStr){
Runnable aRunnable = new Runnable(){
public void run(){
someFunc(paramStr);
}
};
return aRunnable;
}
(When I used this, my parameter was an integer ID, which I used to make a hashmap of ID --> myRunnables. That way, I can use the hashmap to post/remove different myRunnable objects in a handler.)
just wanted to post a full code that will create a table and drop it if it already exists using Jeffrey's code (kudos to him, not me!).
BEGIN
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE tablename';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
EXECUTE IMMEDIATE 'CREATE TABLE tablename AS SELECT * FROM sourcetable WHERE 1=0';
END;
Just for completeness, here's a variant that uses print()
(works on Python 2.6-3.x):
from __future__ import print_function
try: from cStringIO import StringIO
except ImportError:
from io import StringIO
def to_int(nums, _s = StringIO()):
print(*nums, sep='', end='', file=_s)
s = _s.getvalue()
_s.truncate(0)
return int(s)
I've measured performance of @cdleary's functions. The results are slightly different.
Each function tested with the input list generated by:
def randrange1_10(digit_count): # same as @cdleary
return [random.randrange(1, 10) for i in xrange(digit_count)]
You may supply your own function via --sequence-creator=yourmodule.yourfunction
command-line argument (see below).
The fastest functions for a given number of integers in a list (len(nums) == digit_count
) are:
len(nums)
in 1..30
def _accumulator(nums):
tot = 0
for num in nums:
tot *= 10
tot += num
return tot
len(nums)
in 30..1000
def _map(nums):
return int(''.join(map(str, nums)))
def _imap(nums):
return int(''.join(imap(str, nums)))
|------------------------------+-------------------|
| Fitting polynom | Function |
|------------------------------+-------------------|
| 1.00 log2(N) + 1.25e-015 | N |
| 2.00 log2(N) + 5.31e-018 | N*N |
| 1.19 log2(N) + 1.116 | N*log2(N) |
| 1.37 log2(N) + 2.232 | N*log2(N)*log2(N) |
|------------------------------+-------------------|
| 1.21 log2(N) + 0.063 | _interpolation |
| 1.24 log2(N) - 0.610 | _genexp |
| 1.25 log2(N) - 0.968 | _imap |
| 1.30 log2(N) - 1.917 | _map |
To plot the first figure download cdleary.py
and make-figures.py
and run (numpy
and matplotlib
must be installed to plot):
$ python cdleary.py
Or
$ python make-figures.py --sort-function=cdleary._map \
> --sort-function=cdleary._imap \
> --sort-function=cdleary._interpolation \
> --sort-function=cdleary._genexp --sort-function=cdleary._sum \
> --sort-function=cdleary._reduce --sort-function=cdleary._builtins \
> --sort-function=cdleary._accumulator \
> --sequence-creator=cdleary.randrange1_10 --maxn=1000
$('#myForm').bind('submit', function () {
var elements = this.elements;
});
The elements variable will contain all the inputs, selects, textareas and fieldsets within the form.
In C++ operators (for POD types) always act on objects of the same type.
Thus if they are not the same one will be promoted to match the other.
The type of the result of the operation is the same as operands (after conversion).
If either is long double the other is promoted to long double
If either is double the other is promoted to double
If either is float the other is promoted to float
If either is long long unsigned int the other is promoted to long long unsigned int
If either is long long int the other is promoted to long long int
If either is long unsigned int the other is promoted to long unsigned int
If either is long int the other is promoted to long int
If either is unsigned int the other is promoted to unsigned int
If either is int the other is promoted to int
Both operands are promoted to int
Note. The minimum size of operations is int
. So short
/char
are promoted to int
before the operation is done.
In all your expressions the int
is promoted to a float
before the operation is performed. The result of the operation is a float
.
int + float => float + float = float
int * float => float * float = float
float * int => float * float = float
int / float => float / float = float
float / int => float / float = float
int / int = int
int ^ float => <compiler error>
If you are looking for a SwiftUI 2.0 solution that uses View
Struct, here it is:
https://github.com/kenfai/KavSoft-Tutorials-iOS/tree/main/MapsBottomSheet
We can actually turn m x n numeric numpy array into m x 1 numpy string array, please try using the following function, it provides count, inverse_idx and etc, just like numpy.unique:
import numpy as np
def uniqueRow(a):
#This function turn m x n numpy array into m x 1 numpy array storing
#string, and so the np.unique can be used
#Input: an m x n numpy array (a)
#Output unique m' x n numpy array (unique), inverse_indx, and counts
s = np.chararray((a.shape[0],1))
s[:] = '-'
b = (a).astype(np.str)
s2 = np.expand_dims(b[:,0],axis=1) + s + np.expand_dims(b[:,1],axis=1)
n = a.shape[1] - 2
for i in range(0,n):
s2 = s2 + s + np.expand_dims(b[:,i+2],axis=1)
s3, idx, inv_, c = np.unique(s2,return_index = True, return_inverse = True, return_counts = True)
return a[idx], inv_, c
Example:
A = np.array([[ 3.17 9.502 3.291],
[ 9.984 2.773 6.852],
[ 1.172 8.885 4.258],
[ 9.73 7.518 3.227],
[ 8.113 9.563 9.117],
[ 9.984 2.773 6.852],
[ 9.73 7.518 3.227]])
B, inv_, c = uniqueRow(A)
Results:
B:
[[ 1.172 8.885 4.258]
[ 3.17 9.502 3.291]
[ 8.113 9.563 9.117]
[ 9.73 7.518 3.227]
[ 9.984 2.773 6.852]]
inv_:
[3 4 1 0 2 4 0]
c:
[2 1 1 1 2]
Since car
has not been initialized, it has no length, its value is null
. However, the compiler won't even allow you to compile that code as is, throwing the following error: variable car might not have been initialized.
You need to initialize it first, and then you can use .length
:
String car[] = new String[] { "BMW", "Bentley" };
System.out.println(car.length);
If you need to initialize an empty array, you can use the following:
String car[] = new String[] { }; // or simply String car[] = { };
System.out.println(car.length);
If you need to initialize it with a specific size, in order to fill certain positions, you can use the following:
String car[] = new String[3]; // initialize a String[] with length 3
System.out.println(car.length); // 3
car[0] = "BMW";
System.out.println(car.length); // 3
However, I'd recommend that you use a List
instead, if you intend to add elements to it:
List<String> cars = new ArrayList<String>();
System.out.println(cars.size()); // 0
cars.add("BMW");
System.out.println(cars.size()); // 1
The Dart language has aspects of functional programming, so what you want can be written concisely as:
List<String> list = ['one', 'two', 'three', 'four'];
List<Widget> widgets = list.map((name) => new Text(name)).toList();
Read this as "take each name
in list
and map it to a Text
and form them back into a List
".
The syntax a if b else c
is a ternary operator in Python that evaluates to a
if the condition b
is true - otherwise, it evaluates to c
. It can be used in comprehension statements:
>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]
So for your example,
table = ''.join(chr(index) if index in ords_to_keep else replace_with
for index in xrange(15))
You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:
txtBox.CaretIndex=txtBox.Text.Length;
You need to set the caret index at the length, not length-1, because this would put the caret before the last character.
With the positive lookbehind technique:
(?<=\?).*
(We're searching for a text preceded by a question mark here)
Input: derpderp?mystring blahbeh
Output: mystring blahbeh
Basically the ?<=
is a group construct, that requires the escaped question-mark, before any match can be made.
They perform really well, but not all implementations support them.
On windows server 2016 i have used:
dism /online /enable-feature /featurename:IIS-ASPNET45 /all
Also can be done via Powershell:
Install-WindowsFeature .NET-Framework-45-Features
you can do this without jQuery:
var form=document.getElementById('form-id');//retrieve the form as a DOM element
var input = document.createElement('input');//prepare a new input DOM element
input.setAttribute('name', inputName);//set the param name
input.setAttribute('value', inputValue);//set the value
input.setAttribute('type', inputType)//set the type, like "hidden" or other
form.appendChild(input);//append the input to the form
form.submit();//send with added input
Just use Map#get(key)
?
Object value = map.get(myCode);
Here's a tutorial about maps, you may find it useful: http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html.
Edit: you edited your question with the following:
I'm expecting to see a String, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454
Sorry, I'm not too familiar with maps as you can probably guess ;)
You're seeing the outcome of Object#toString()
. But the java.lang.String
should already have one implemented, unless you created a custom implementation with a lowercase s
in the name: java.lang.string
. If it is actually a custom object, then you need to override Object#toString()
to get a "human readable string" whenever you do a System.out.println()
or toString()
on the desired object. For example:
@Override
public String toString() {
return "This is Object X with a property value " + value;
}
Even as it got the most votes, one usually can't take System.Collections.Concurrent.ConcurrentBag<T>
as a thread-safe replacement for System.Collections.Generic.List<T>
as it is (Radek Stromský already pointed it out) not ordered.
But there is a class called System.Collections.Generic.SynchronizedCollection<T>
that is already since .NET 3.0 part of the framework, but it is that well hidden in a location where one does not expect it that it is little known and probably you have never ever stumbled over it (at least I never did).
SynchronizedCollection<T>
is compiled into assembly System.ServiceModel.dll (which is part of the client profile but not of the portable class library).
Try this, maybe can help, it do what you want:
var listArray = new ListArray();_x000D_
let element = {name: 'Edy', age: 27, country: "Brazil"};_x000D_
let element2 = {name: 'Marcus', age: 27, country: "Brazil"};_x000D_
listArray.push(element);_x000D_
listArray.push(element2);_x000D_
_x000D_
console.log(listArray.array)
_x000D_
<script src="https://marcusvi200.github.io/list-array/script/ListArray.js"></script>
_x000D_
Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.
The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.
All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.
There are a few problems here.
First of all, there is no such thing as <button type="cancel">
, so it is treated as just a <button>
. This means that your form will be submitted, instead of the button taking you elsewhere.
Second, javascript:
is only needed in href
or action
attributes, where a URL is expected, to designate JavaScript code. Inside onclick
, where JavaScript is already expected, it merely acts as a label and serves no real purpose.
Finally, it's just generally better design to have a cancel link rather than a cancel button. So you can just do this:
<a href="http://stackoverflow.com/">Cancel</a>
With CSS you can even make it look the same as a button, but with this HTML there is absolutely no confusion as to what it is supposed to do.
I know this is an older thread but I wanted to give what I think to be helpful information.
I personally use PyPy which is really easy to install using pip. I interchangeably use Python/PyPy interpreter, you don't need to change your code at all and I've found it to be roughly 40x faster than the standard python interpreter (Either Python 2x or 3x). I use pyCharm Community Edition to manage my code and I love it.
I like writing code in python as I think it lets you focus more on the task than the language, which is a huge plus for me. And if you need it to be even faster, you can always compile to a binary for Windows, Linux, or Mac (not straight forward but possible with other tools). From my experience, I get about 3.5x speedup over PyPy when compiling, meaning 140x faster than python. PyPy is available for Python 3x and 2x code and again if you use an IDE like PyCharm you can interchange between say PyPy, Cython, and Python very easily (takes a little of initial learning and setup though).
Some people may argue with me on this one, but I find PyPy to be faster than Cython. But they're both great choices though.
Edit: I'd like to make another quick note about compiling: when you compile, the resulting binary is much bigger than your python script as it builds all dependencies into it, etc. But then you get a few distinct benefits: speed!, now the app will work on any machine (depending on which OS you compiled for, if not all. lol) without Python or libraries, it also obfuscates your code and is technically 'production' ready (to a degree). Some compilers also generate C code, which I haven't really looked at or seen if it's useful or just gibberish. Good luck.
Hope that helps.
#!/bin/sh
or #!/bin/bash
has to be first line of the script because if you don't use it on the first line then the system will treat all the commands in that script as different commands. If the first line is #!/bin/sh
then it will consider all commands as a one script and it will show the that this file is running in ps
command and not the commands inside the file.
./echo.sh
ps -ef |grep echo
trainee 3036 2717 0 16:24 pts/0 00:00:00 /bin/sh ./echo.sh
root 3042 2912 0 16:24 pts/1 00:00:00 grep --color=auto echo
This is the correct answer. It will refresh the previous page.
window.location=document.referrer;
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
For small functions like this you could just count by hand how many hops it is to the target, from the instruction under the branch instruction. If it branches backwards make that hop number negative. if that number doesn't require all 16 bits, then for every number to the left of the most significant of your hop number, make them 1's, if the hop number is positive make them all 0's Since most branches are close to they're targets, this saves you a lot of extra arithmetic for most cases.
Update answer for 2021, Xcode 12.X:
pod deintegrate
pod install
Hope this helps!
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
There is of course a lubridate
solution for this:
library(lubridate)
date <- "2009-10-01"
ymd(date) - 5
# [1] "2009-09-26"
is the same as
ymd(date) - days(5)
# [1] "2009-09-26"
Other time formats could be:
ymd(date) - months(5)
# [1] "2009-05-01"
ymd(date) - years(5)
# [1] "2004-10-01"
ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"
There are few problems with the S3/Redirect based approach mentioned by others.
The solution is:
Configure error page rules for your Cloudfront instance. In the error rules specify:
HTTP Response Code: 200
Configure an EC2 instance and setup an nginx server.
I can help in more details with respect to nginx setup, just leave a note. Have learnt it the hard way.
Once the cloud front distribution update. Invalidate your cloudfront cache once to be in the pristine mode. Hit the url in the browser and all should be good.
I've created my own dark color scheme (based on Oblivion from gedit), which I think is very nice to work with.
Preview & details at: http://www.rogerdudler.com/?p=362
We're happy to announce the beta of eclipsecolorthemes.org, a new website to download, create and maintain Eclipse color themes / schemes. The theme editor allows you to copy an existing theme and edit the colors with a live preview of your changes on specific editors. The downloadable themes support a lot of editors (PHP, Java, SQL, Ant, text, HTML, CSS, and more to follow)
There's a growing list of themes already available on the site:
You can read more about the launch here.
A function pointer to a class member is a problem that is really suited to using boost::function. Small example:
#include <boost/function.hpp>
#include <iostream>
class Dog
{
public:
Dog (int i) : tmp(i) {}
void bark ()
{
std::cout << "woof: " << tmp << std::endl;
}
private:
int tmp;
};
int main()
{
Dog* pDog1 = new Dog (1);
Dog* pDog2 = new Dog (2);
//BarkFunction pBark = &Dog::bark;
boost::function<void (Dog*)> f1 = &Dog::bark;
f1(pDog1);
f1(pDog2);
}
Static methods aren't virtual like instance methods so I suppose the Java designers decided they didn't want them in interfaces.
But you can put classes containing static methods inside interfaces. You could try that!
public interface Test {
static class Inner {
public static Object get() {
return 0;
}
}
}
Found a way with two (2) easy codes here. First do a mysqldump:
mysqldump -uUSERNAME -p DATABASE_NAME > database-dump.sql
then grep the sqldump file:
grep -i "Search string" database-dump.sql
It possible also to find/replace and re-import back to the database.
You should also look into commands.getstatusoutput
This returns a tuple of length 2.. The first is the return integer ( 0 - when the commands is successful ) second is the whole output as will be shown in the terminal.
For ls
import commands
s=commands.getstatusoutput('ls')
print s
>> (0, 'file_1\nfile_2\nfile_3')
s[1].split("\n")
>> ['file_1', 'file_2', 'file_3']
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
My status bar and navigation bar overlap after return from landscape view of YTPlayer. Here is my solution after trying @comonitos' version but not work on my iOS 8
- (void)fixNavigationBarPosition {
if (self.navigationController) {
CGRect frame = self.navigationController.navigationBar.frame;
if (frame.origin.y != 20.f) {
frame.origin.y = 20.f;
self.navigationController.navigationBar.frame = frame;
}
}
}
Just call this function whenever you want to fix the position of navigation bar. I called on YTPlayerViewDelegate's playerView:didChangeToState:
- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {
switch (state) {
case kYTPlayerStatePaused:
case kYTPlayerStateEnded:
[self fixNavigationBarPosition];
break;
default:
}
}
Try this...
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
public class StopwatchTest {
public static void main(String[] args) throws Exception {
Stopwatch stopwatch = Stopwatch.createStarted();
Thread.sleep(1000 * 60);
stopwatch.stop(); // optional
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println("Time in milliseconds "+millis);
System.out.println("that took: " + stopwatch);
}
}
By default Bundler will check your system first and if it can't find a gem it will use the sources specified in your Gemfile.
Can you try this,
$ch = curl_init($url);
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...
I believe you have to reference bootstrap.js before bootstrap-datepicker.js
the -client and -server systems are different binaries. They are essentially two different compilers (JITs) interfacing to the same runtime system. The client system is optimal for applications which need fast startup times or small footprints, the server system is optimal for applications where the overall performance is most important. In general the client system is better suited for interactive applications such as GUIs
We run the following code with both switches:
package com.blogspot.sdoulger;
public class LoopTest {
public LoopTest() {
super();
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
spendTime();
long end = System.currentTimeMillis();
System.out.println("Time spent: "+ (end-start));
LoopTest loopTest = new LoopTest();
}
private static void spendTime() {
for (int i =500000000;i>0;i--) {
}
}
}
Note: The code is been compiled only once! The classes are the same in both runs!
With -client:
java.exe -client -classpath C:\mywork\classes com.blogspot.sdoulger.LoopTest
Time spent: 766
With -server:
java.exe -server -classpath C:\mywork\classes com.blogspot.sdoulger.LoopTest
Time spent: 0
It seems that the more aggressive optimazation of the server system, remove the loop as it understands that it does not perform any action!
I'm detecting the back button by this way:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
It works but I have to create a cookie in Chrome to detect that i'm in the page on first time because when i enter in the page without control by cookie, the browser do the back action without click in any back button.
if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null);
window.onpopstate = function () {
if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null )
{
addCookie('cookieChrome',1, 1440);
}
else
{
history.pushState('newjibberish', null, null);
}
};
}
AND VERY IMPORTANT, history.pushState("jibberish", null, null);
duplicates the browser history.
Some one knows who can i fix it?
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
In python
linesWithSessionIdCollect = linesWithSessionId.collect()
linesWithSessionIdCollect
This will printout all the contents of the RDD
The main advantages of ASP.net MVC are:
Enables the full control over the rendered HTML.
Provides clean separation of concerns(SoC).
Enables Test Driven Development (TDD).
Easy integration with JavaScript frameworks.
Following the design of stateless nature of the web.
RESTful urls that enables SEO.
No ViewState and PostBack events
The main advantage of ASP.net Web Form are:
It provides RAD development
Easy development model for developers those coming from winform development.
You can use peseudo elements like this:
input[type=checkbox] {_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
margin-right: 8px;_x000D_
cursor: pointer;_x000D_
font-size: 27px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:after {_x000D_
content: " ";_x000D_
background-color: #9FFF9D;_x000D_
display: inline-block;_x000D_
visibility: visible;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "\2714";_x000D_
}
_x000D_
<label>Checkbox label_x000D_
<input type="checkbox">_x000D_
</label>
_x000D_
solved (for me) using in keytool the args
-sigalg MD5withRSA -keyalg RSA -keysize 1024
and using in jarsigner
-sigalg MD5withRSA -digestalg SHA1
solution found in
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
If your existing code base doesn't lend itself to unit testing, and it's already in production, you might create more problems than you solve by trying to refactor all of your code so that it is unit-testable.
You may be better off putting efforts towards improving your integration testing instead. There's lots of code out there that's just simpler to write without a unit test, and if a QA can validate the functionality against a requirements document, then you're done. Ship it.
The classic example of this in my mind is a SqlDataReader embedded in an ASPX page linked to a GridView. The code is all in the ASPX file. The SQL is in a stored procedure. What do you unit test? If the page does what it's supposed to do, should you really redesign it into several layers so you have something to automate?
It's too late but somewhat may useful to others
The matching wildcard is strict, but no declaration can be found for element 'context:component-scan
which Means you have Missed some Declarations or The Required Declarations Not Found in Your XML
In my case i forgot to add the follwoing
After Adding this the Problem Gone away
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
In 32 bit format system the hexadecimal value 0xff
represents 00000000000000000000000011111111
that is 255(15*16^1+15*16^0)
in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
The correct answer IMO is git clone --mirror. This will fully backup your repo.
Git clone mirror will clone the entire repository, notes, heads, refs, etc. and is typically used to copy an entire repository to a new git server. This will pull down an all branches and everything, the entire repository.
git clone --mirror [email protected]/your-repo.git
Normally cloning a repo does not include all branches, only Master.
Copying the repo folder will only "copy" the branches that have been pulled in...so by default that is Master branch only or other branches you have checked-out previously.
The Git bundle command is also not what you want: "The bundle command will package up everything that would normally be pushed over the wire with a git push command into a binary file that you can email to someone or put on a flash drive, then unbundle into another repository." (From What's the difference between git clone --mirror and git clone --bare)
In some situations, it could be desirable to ensure the Unique key does not exists before create it. In such cases, the script below might help:
IF Exists(SELECT * FROM sys.indexes WHERE name Like '<index_name>')
ALTER TABLE dbo.<target_table_name> DROP CONSTRAINT <index_name>
GO
ALTER TABLE dbo.<target_table_name> ADD CONSTRAINT <index_name> UNIQUE NONCLUSTERED (<col_1>, <col_2>, ..., <col_n>)
GO
IEnumerable
is just an interface and so can't be instantiated directly.
You need to create a concrete class (like a List
)
IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3" };
you can then pass this to anything expecting an IEnumerable
.