This jQuery-based answer posted by @user110902 was useful for me. However, I improved it a little to prevent a flaw mentioned in @B_N 's comment: it failed detecting CapsLock while you press Shift:
$('#example').keypress(function(e) {
var s = String.fromCharCode( e.which );
if (( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey )
|| ( s.toLowerCase() === s && s.toUpperCase() !== s && e.shiftKey )) {
alert('caps is on');
}
});
Like this, it will work even while pressing Shift.
I wasn't happy with any of the answers here, and went looking for a command-line solution.
In macOS Sierra 10.12, Apple introduced a new way for users to remap keys.
If that sounds good to you, take a look at hidutil
.
For example, to remap caps-lock to escape, refer to the key table and find that caps-lock has usage code 0x39 and escape has usage code 0x29. Put these codes or'd with the hex value 0x700000000 in the source and dest like this:
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x700000029}]}'
You may add other mappings in the same command. Personally, I like to remap caps-lock to backspace, and remap backspace to delete:
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x70000002A}, {"HIDKeyboardModifierMappingSrc":0x70000002A,"HIDKeyboardModifierMappingDst":0x70000004C}]}'
To see the current mapping:
hidutil property --get "UserKeyMapping"
Your changes will be lost at system reboot. If you want them to persist, configure them in a launch agent. Here's mine:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Place in ~/Library/LaunchAgents/ -->
<!-- launchctl load com.ldaws.CapslockBackspace.plist -->
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.ldaws.CapslockEsc</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/hidutil</string>
<string>property</string>
<string>--set</string>
<string>{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x70000002A},{"HIDKeyboardModifierMappingSrc":0x70000002A,"HIDKeyboardModifierMappingDst":0x70000004C}]}</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
I've placed this content into a file located at ~/Library/LaunchAgents/com.ldaws.CapslockBackspace.plist
and then executed:
launchctl load com.ldaws.CapslockBackspace.plist
You can remove the time part of a date by using TRUNC
.
select field,datetime_field
from database
where datetime_field >= trunc(sysdate-1,'DD');
That query will give you all rows with dates starting from yesterday. Note the second argument to trunc()
. You can use this to truncate any part of the date.
If your datetime_fied contains '2011-05-04 08:23:54'
, the following date will be returned
trunc(datetime_field, 'HH24') => 2011-05-04 08:00:00
trunc(datetime_field, 'DD') => 2011-05-04 00:00:00
trunc(datetime_field, 'MM') => 2011-05-01 00:00:00
trunc(datetime_field, 'YYYY') => 2011-00-01 00:00:00
You need to wait until the image is loaded before you draw it. Try this instead:
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
}
i.e. draw the image in the onload callback of the image.
I used this conversion:
CString cs = "TEST";
char* c = cs.GetBuffer(m_ncs me.GetLength())
I hope this is useful.
sys.argv
is the list of arguments passed to the Python program. The first argument, sys.argv[0]
, is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason sys.argv[0]
exists is so you can change your program's behaviour depending on how it was invoked. sys.argv[1]
is thus the first argument you actually pass to the program.
Because lists (like most sequences) in Python start indexing at 0, and because indexing past the end of the list is an error, you need to check if the list has length 2 or longer before you can access sys.argv[1]
.
ts-node
node module globally.node
in command line to run below file js
file (The path is for windows, but you can do it for linux as well)
~\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js
ts
file path as a command line argument.In Windows SourceTree, untick Push all tags to remotes
.
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
int num[]=new int[10];
int average=0;
int i=0;
int sum=0;
for (i=0;i<num.length;i++) {
System.out.println("enter a number");
num[i]=in.nextInt();
sum=sum+num[i];
}
average=sum/10;
System.out.println("Average="+average);
}
}
I firstly added one off static table with ALL possibilities of my wildcard results (this company has a 4 character nvarchar code as their localities and they wildcard their locals) i.e. they may have 456? which would give them 456[1] to 456[Z] i.e 0-9 & a-z
I had to write a script to pull the current user (declare them) and pull the masks for the declared user.
Create some temporary tables just basic ones to rank the row numbers for this current user
loop through each result (YOUR Or this Or that etc...)
Insert into the test Table.
Here is the script I used:
Drop Table #UserMasks
Drop Table #TESTUserMasks
Create Table #TESTUserMasks (
[User] [Int] NOT NULL,
[Mask] [Nvarchar](10) NOT NULL)
Create Table #UserMasks (
[RN] [Int] NOT NULL,
[Mask] [Nvarchar](10) NOT NULL)
DECLARE @User INT
SET @User = 74054
Insert Into #UserMasks
select ROW_NUMBER() OVER ( PARTITION BY ProntoUserID ORDER BY Id DESC) AS RN,
REPLACE(mask,'?','') Mask
from dbo.Access_Masks
where prontouserid = @User
DECLARE @TopFlag INT
SET @TopFlag = 1
WHILE (@TopFlag <=(select COUNT(*) from #UserMasks))
BEGIN
Insert Into #TestUserMasks
select (@User),Code from dbo.MaskArrayLookupTable
where code like (select Mask + '%' from #UserMasks Where RN = @TopFlag)
SET @TopFlag = @TopFlag + 1
END
GO
select * from #TESTUserMasks
You probably want this:
string[,] Tablero = new string[3,3];
This will create you a matrix-like array where all rows have the same length.
The array in your sample is a so-called jagged array, i.e. an array of arrays where the elements can be of different size. A jagged array would have to be created in a different way:
string[][] Tablero = new string[3][];
for (int i = 0; i < Tablero.GetLength(0); i++)
{
Tablero[i] = new string[3];
}
You can also use initializers to fill the array elements with data:
string[,] Tablero = new string[,]
{
{"1.1","1.2", "1.3"},
{"2.1","2.2", "2.3"},
{"3.1", "3.2", "3.3"}
};
And in case of a jagged array:
string[][] Tablero = new string[][]
{
new string[] {"1.1","1.2", "1.3"},
new string[] {"2.1","2.2", "2.3"},
new string[] {"3.1", "3.2", "3.3"}
};
DECLARE
the_variable NUMBER;
BEGIN
SELECT my_column INTO the_variable FROM my_table;
END;
Make sure that the query only returns a single row:
By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row
If no rows are returned, PL/SQL raises NO_DATA_FOUND. You can guard against this exception by selecting the result of an aggregate function, such as COUNT(*) or AVG(), where practical. These functions are guaranteed to return a single value, even if no rows match the condition.
A SELECT ... BULK COLLECT INTO statement can return multiple rows. You must set up collection variables to hold the results. You can declare associative arrays or nested tables that grow as needed to hold the entire result set.
The implicit cursor SQL and its attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN provide information about the execution of a SELECT INTO statement.
If you just need a simple backup to an archive, you can try my little utility: https://github.com/loomchild/volume-backup
Example
Backup:
docker run -v some_volume:/volume -v /tmp:/backup --rm loomchild/volume-backup backup archive1
will archive volume named some_volume
to /tmp/archive1.tar.bz2
archive file
Restore:
docker run -v some_volume:/volume -v /tmp:/backup --rm loomchild/volume-backup restore archive1
will wipe and restore volume named some_volume
from /tmp/archive1.tar.bz2
archive file.
More info: https://medium.com/@loomchild/backup-restore-docker-named-volumes-350397b8e362
Two things to do:
Project Settings > Project compiler output > Set it as "Project path(You actual project's path)”+”\out”.
Project Settings > Module > Path > Choose "Inherit project compile path"
First you need to import svg
files by following simple steps.
If image is available in your computer
then select local svg
file.
After that select the image path
and an option to change the size of the image is also available at the right side of dialog if you want to .
in this way svg
image is imported in your project
After that for using this image use the same procedure
@drawable/yourimagename
Just like ASP.NET variant, except put the hidden input with the same name before the actual checkbox (of the same name). Only last values will be sent. This way if a box is checked then its name and value "on" is sent, whereas if it's unchecked then the name of the corresponding hidden input and whatever value you might like to give it will be sent. In the end you will get the $_POST array to read, with all checked and unchecked elements in it, "on" and "false" values, no duplicate keys. Easy to process in PHP.
If you need to duplicate more than a few redirects, you might consider using a map:
# map is outside of server block
map $uri $redirect_uri {
~^/issue1/?$ http://example.com/shop/issues/custom_isse_name1;
~^/issue2/?$ http://example.com/shop/issues/custom_isse_name2;
~^/issue3/?$ http://example.com/shop/issues/custom_isse_name3;
# ... or put these in an included file
}
location / {
try_files $uri $uri/ @redirect-map;
}
location @redirect-map {
if ($redirect_uri) { # redirect if the variable is defined
return 301 $redirect_uri;
}
}
You can use this function to get proper client IP:
public function getClientIP(){
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)){
return $_SERVER["HTTP_X_FORWARDED_FOR"];
}else if (array_key_exists('REMOTE_ADDR', $_SERVER)) {
return $_SERVER["REMOTE_ADDR"];
}else if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
return $_SERVER["HTTP_CLIENT_IP"];
}
return '';
}
I slightly disagree with the above. The unsigned char
simply means: Use the most significant bit instead of treating it as a bit flag for +/- sign when performing arithmetic operations.
It makes significance if you use char
as a number for instance:
typedef char BYTE1;
typedef unsigned char BYTE2;
BYTE1 a;
BYTE2 b;
For variable a
, only 7 bits are available and its range is (-127 to 127) = (+/-)2^7 -1.
For variable b
all 8 bits are available and the range is 0 to 255 (2^8 -1).
If you use char
as character, "unsigned" is completely ignored by the compiler just as comments are removed from your program.
time_point
objects only support arithmetic with other time_point
or duration
objects.
You'll need to convert your long
to a duration
of specified units, then your code should work correctly.
You can of course change the order of the columns in a sql statement. However if you want to abstract tables' physical column order, you can create a view. i.e
CREATE TABLE myTable(
a int NULL,
b varchar(50) NULL,
c datetime NULL
);
CREATE VIEW vw_myTable
AS
SELECT c, a, b
FROM myTable;
select * from myTable;
a b c
- - -
select * from vw_myTable
c a b
- - -
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
You have 2 options: Redirect the output of the script to a file, Introduce a log file in the script and
Here you assume that the script outputs all necessary info, including warning and error messages. You can then redirect the output to a file of your choice.
./runTests &> output.log
The above command redirects both the standard output and the error output to your log file.
Using this approach you don't have to introduce a log file in the script, and so the logic is a tiny bit easier.
In your script add a log file either by hard coding it:
logFile='./path/to/log/file.log'
or passing it by a parameter:
logFile="${1}" # This assumes the first parameter to the script is the log file
It's a good idea to add the timestamp at the time of execution to the log file at the top of the script:
date '+%Y%-m%d-%H%M%S' >> "${logFile}"
You can then redirect your error messages to the log file
if [ condition ]; then
echo "Test cases failed!!" >> "${logFile}";
fi
This will append the error to the log file and continue execution. If you want to stop execution when critical errors occur, you can exit
the script:
if [ condition ]; then
echo "Test cases failed!!" >> "${logFile}";
# Clean up if needed
exit 1;
fi
Note that exit 1
indicates that the program stop execution due to an unspecified error. You can customize this if you like.
Using this approach you can customize your logs and have a different log file for each component of your script.
If you have a relatively small script or want to execute somebody else's script without modifying it to the first approach is more suitable.
If you always want the log file to be at the same location, this is the better option of the 2. Also if you have created a big script with multiple components then you may want to log each part differently and the second approach is your only option.
Now you have two versions of Xcode installed on your machine. Xcode 7.3.1 and Xcode 8.
To test that all words start with an upper case use this:
print all(word[0].isupper() for word in words)
body.bg {
background-size: cover;
background-repeat: no-repeat;
min-height: 100vh;
background: white url(../images/bg-404.jpg) center center no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}
Try This
_x000D_
_x000D_
body.bg {_x000D_
background-size: cover;_x000D_
background-repeat: no-repeat;_x000D_
min-height: 100vh;_x000D_
background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;_x000D_
-webkit-background-size: cover;_x000D_
-moz-background-size: cover;_x000D_
-o-background-size: cover;_x000D_
}
_x000D_
<body class="bg">_x000D_
_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_
I understand that there is a 4000 max set for
NVARCHAR(MAX)
Your understanding is wrong. nvarchar(max)
can store up to (and beyond sometimes) 2GB of data (1 billion double byte characters).
From nchar and nvarchar in Books online the grammar is
nvarchar [ ( n | max ) ]
The |
character means these are alternatives. i.e. you specify either n
or the literal max
.
If you choose to specify a specific n
then this must be between 1 and 4,000 but using max
defines it as a large object datatype (replacement for ntext
which is deprecated).
In fact in SQL Server 2008 it seems that for a variable the 2GB limit can be exceeded indefinitely subject to sufficient space in tempdb
(Shown here)
Regarding the other parts of your question
varchar(n) + varchar(n)
will truncate at 8,000 characters.nvarchar(n) + nvarchar(n)
will truncate at 4,000 characters.varchar(n) + nvarchar(n)
will truncate at 4,000 characters. nvarchar
has higher precedence so the result is nvarchar(4,000)
[n]varchar(max)
+ [n]varchar(max)
won't truncate (for < 2GB).varchar(max)
+ varchar(n)
won't truncate (for < 2GB) and the result will be typed as varchar(max)
.varchar(max)
+ nvarchar(n)
won't truncate (for < 2GB) and the result will be typed as nvarchar(max)
.nvarchar(max)
+ varchar(n)
will first convert the varchar(n)
input to nvarchar(n)
and then do the concatenation. If the length of the varchar(n)
string is greater than 4,000 characters the cast will be to nvarchar(4000)
and truncation will occur.If you use the N
prefix and the string is <= 4,000 characters long it will be typed as nvarchar(n)
where n
is the length of the string. So N'Foo'
will be treated as nvarchar(3)
for example. If the string is longer than 4,000 characters it will be treated as nvarchar(max)
If you don't use the N
prefix and the string is <= 8,000 characters long it will be typed as varchar(n)
where n
is the length of the string. If longer as varchar(max)
For both of the above if the length of the string is zero then n
is set to 1.
1. The CONCAT
function doesn't help here
DECLARE @A5000 VARCHAR(5000) = REPLICATE('A',5000);
SELECT DATALENGTH(@A5000 + @A5000),
DATALENGTH(CONCAT(@A5000,@A5000));
The above returns 8000 for both methods of concatenation.
2. Be careful with +=
DECLARE @A VARCHAR(MAX) = '';
SET @A+= REPLICATE('A',5000) + REPLICATE('A',5000)
DECLARE @B VARCHAR(MAX) = '';
SET @B = @B + REPLICATE('A',5000) + REPLICATE('A',5000)
SELECT DATALENGTH(@A),
DATALENGTH(@B);`
Returns
-------------------- --------------------
8000 10000
Note that @A
encountered truncation.
You are getting truncation either because you are concatenating two non max
datatypes together or because you are concatenating a varchar(4001 - 8000)
string to an nvarchar
typed string (even nvarchar(max)
).
To avoid the second issue simply make sure that all string literals (or at least those with lengths in the 4001 - 8000 range) are prefaced with N
.
To avoid the first issue change the assignment from
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = 'Foo' + 'Bar' + ...;
To
DECLARE @SQL NVARCHAR(MAX) = '';
SET @SQL = @SQL + N'Foo' + N'Bar'
so that an NVARCHAR(MAX)
is involved in the concatenation from the beginning (as the result of each concatenation will also be NVARCHAR(MAX)
this will propagate)
Make sure you have "results to grid" mode selected then you can use
select @SQL as [processing-instruction(x)] FOR XML PATH
The SSMS options allow you to set unlimited length for XML
results. The processing-instruction
bit avoids issues with characters such as <
showing up as <
.
I used base64 for the overcoming the same problem, i.e. people can see my password over my shoulder.
Here is what I did - I created a new "db_auth.cfg" file and created parameters with one being my db password. I set the permission as 750 for the file.
DB_PASSWORD=Z29vZ2xl
In my shell script I used the "source" command to get the file and then decode it back to use in my script.
source path_to_the_file/db_auth.cfg
DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)
I hope this helps.
Mutex is basically mutual exclusion. Only one thread can acquire the resource at once. When one thread acquires the resource, no other thread is allowed to acquire the resource until the thread owning the resource releases. All threads waiting for acquiring resource would be blocked.
Semaphore is used to control the number of threads executing. There will be fixed set of resources. The resource count will gets decremented every time when a thread owns the same. When the semaphore count reaches 0 then no other threads are allowed to acquire the resource. The threads get blocked till other threads owning resource releases.
In short, the main difference is how many threads are allowed to acquire the resource at once ?
I just used this, but I don't know if it works across all browsers.
It works in Firefox:
<a href="myfile.pdf" download>Click to Download</a>
@balusC I did as you wrote . In my case , I've added cookie information to be able to reuse the session .
// get the cookie if need
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
Please use the below kotlin code
webview.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return false
}
})
For more info click here
Based on @ofer.sheffer answer, this is the CMD variant for adding an affix (this is not the question, but this page is still the #1 google result if you search affix). It is a bit different because of the extension.
for %a in (*.*) do ren "%~a" "%~na-affix%~xa"
You can change the "-affix" part.
I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.
For performance reasons, don't draw a circle if you can avoid it. Just draw a rectangle with a width and height of one:
ctx.fillRect(10,10,1,1); // fill in the pixel at (10,10)
There should be a script named mvim in the root of the .bz2 file. Copy this somewhere into your $PATH ( /usr/local/bin would be good ) and you should be sorted.
New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies
section of your package.json. Anytime you use something from scripts
in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.
For example:
npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally
Then in package.json:
// devDependencies has mocha and babel now
"scripts": {
"test": "mocha",
"build": "babel -d lib src",
"prepublish": "babel -d lib src"
}
Then at your command prompt you can run:
npm run build # finds babel
npm test # finds mocha
npm publish # will run babel first
But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:
"scripts": {
"preinstall": "npm i -g themodule"
}
So actually my npm install executes npm install again .. which is weird but seems to work.
Note: you might have issues if you are using the most common setup for npm
where global Node package installs required sudo
. One option is to change your npm
configuration so this isn't necessary:
npm config set prefix ~/npm
, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH
to your ~/.bashrc
.
Here is the example:
SQL> set define off;
SQL> select * from dual where dummy='&var';
no rows selected
SQL> set define on
SQL> /
Enter value for var: X
old 1: select * from dual where dummy='&var'
new 1: select * from dual where dummy='X'
D
-
X
With set define off
, it took a row with &var
value, prompted a user to enter a value for it and replaced &var
with the entered value (in this case, X
).
Angular6 using the renderer2 without any variables and a clean template:
template:
<div (click)="toggleClass($event,'testClass')"></div>
in ts:
toggleClass(event: any, class: string) {
const hasClass = event.target.classList.contains(class);
if(hasClass) {
this.renderer.removeClass(event.target, class);
} else {
this.renderer.addClass(event.target, class);
}
}
One could put this in a directive too ;)
Download SourceTree. It is available for windows7+ and Mac and is highly recommend to upload files on github via interactive UI.
You have to use the viewWithTag
function to find the view with the given tag
.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let point = touch.locationInView(self.view)
if let viewWithTag = self.view.viewWithTag(100) {
print("Tag 100")
viewWithTag.removeFromSuperview()
} else {
print("tag not found")
}
}
I had the Cannot edit in read-only editor
error when trying to edit code after stopping the debug mode (for 2-3 minutes after pressing Shift+F5
).
Turns out the default Node version (v9.11.1) wasn't exiting gracefully, leaving VScode stuck on read-only.
Simply adding "runtimeVersion": "12.4.0"
to my launch.json file fixed it.
alternatively, change your default Node version to the latest stable version (you can see the current version on the DEBUG CONSOLE
when starting debug mode).
The provided solution does not work for instances of types loaded from a remote assembly. To do that, here is a solution that works in all situations, which involves an explicit type re-mapping of the type returned through the CreateInstance call.
This is how I need to create my classInstance, as it was located in a remote assembly.
// sample of my CreateInstance call with an explicit assembly reference
object classInstance = Activator.CreateInstance(assemblyName, type.FullName);
However, even with the answer provided above, you'd still get the same error. Here is how to go about:
// first, create a handle instead of the actual object
ObjectHandle classInstanceHandle = Activator.CreateInstance(assemblyName, type.FullName);
// unwrap the real slim-shady
object classInstance = classInstanceHandle.Unwrap();
// re-map the type to that of the object we retrieved
type = classInstace.GetType();
Then do as the other users mentioned here.
This is valid YAML:
jobs:
- name: A
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
- name: B
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.
Ruby is v2.0 now. Programs like Jekyll (and I am sure many others) require it. I just ran:
sudo apt-get install ruby2.0
check version
ruby --version
Hope that helps
Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like
INSERT INTO HISTORICAL_CAR_STATS (
HISTORICAL_CAR_STATS_ID,
YEAR,
MONTH,
MAKE,
MODEL,
REGION,
AVG_MSRP,
CNT)
SELECT MY_SEQ.nextval,
year,
month,
make,
model,
region,
avg_msrp,
cnt
FROM (SELECT '2010' year,
'12' month,
'ALL' make,
'ALL' model,
REGION,
sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
sum(cnt) cnt
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010'
AND MONTH = '12'
AND MAKE != 'ALL'
GROUP BY REGION)
This is the correct solution for finding a function:
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'fn'
AND name = 'fn_NAME'
After getting feedback, It seems the original solution didn't work. That's why updated the answer as one of the suggestions.
def float_of_2_decimal(float_n)
float_n.to_d.round(2, :truncate).to_f
end
Other answers may work, if you want to have rounded numbers of 2 decimal places. But, If you want to have floating point numbers with first two decimal places without rounding, Those answers won't help.
So, to get a floating point number with first two decimal places, I used this technique. Doesn't work in some cases
def float_of_2_decimal(float_n)
float_n.round(3).to_s[0..3].to_f
end
with 5.666666666666666666666666
, it will return 5.66
instead of rounded 5.67
. Hope it will help someone
The easiest solution is found here install-windows-service-without-installutil-exe by @Hoàng Long
@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"
echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause
If you are using a LinearLayout
you should call myView.bringToFront()
and after you should call parentView.requestLayout()
and parentView.invalidate()
to force the parent to redraw with the new child order.
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
get
returns Collection
and is rather supposed to fetch multiple rows.
count
is a generic way of checking the result:
$user = User::where(...)->first(); // returns Model or null
if (count($user)) // do what you want with $user
// or use this:
$user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException
// count will works with a collection of course:
$users = User::where(...)->get(); // returns Collection always (might be empty)
if (count($users)) // do what you want with $users
import cv2
img=cv2.imread('my_test.jpg')
img_info = img.shape
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])
My_test.jpg link ---> https://i.pinimg.com/originals/8b/ca/f5/8bcaf5e60433070b3210431e9d2a9cd9.jpg
import java.util.*;
public class arrayList {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<String > x=new ArrayList<>();
//inserting element
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
//to show element
System.out.println(x);
//converting arraylist to stringarray
String[]a=x.toArray(new String[x.size()]);
for(String s:a)
System.out.print(s+" ");
}
}
I have updated the code to make it works for me
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
$(this).each(function(idx, jqXHR) {
var index = $.inArray(jqXHR, $.xhrPool);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
});
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.inArray(jqXHR, $.xhrPool);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
}
});
After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.
# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]
# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]
# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...
Requirements:
You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.
Or just extract the first part of your ISO string, it already contains what you want.
Here is an example by splitting on the T
:
"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"
You could convert your integer into a string. As the minus sign will not match the digits, you will have no negative years.
On Postgres 9.6(PgAdmin 4) , this can be set up in Preferences->Paths->Binary paths: - set PostgreSQL Binary Path variable to "C:\Program Files\PostgreSQL\9.6\bin" or where you have installed
By changing runProguard to minifyEnabled, part of the issue gets fixed.
But the fix can cause "Library Projects cannot set application Id" (you can find the fix for this here Android Studio 1.0 and error "Library projects cannot set applicationId").
By removing application Id in the build.gradle file, you should be good to go.
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
works, however it results in a Python warning of
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value
instead
I would guess this is due to some chaining indexing.
Didn't see an example of both in one query. So this example might help.
/**
INTERNATIONAL_ORDERS - table of orders by company by location by day
companyId, country, city, total, date
**/
SELECT country, city, sum(total) totalCityOrders
FROM INTERNATIONAL_ORDERS with (nolock)
WHERE companyId = 884501253109
GROUP BY country, city
HAVING country = 'MX'
ORDER BY sum(total) DESC
This filters the table first by the companyId, then groups it (by country and city) and additionally filters it down to just city aggregations of Mexico. The companyId was not needed in the aggregation but we were able to use WHERE to filter out just the rows we wanted before using GROUP BY.
Most of the cases issue is due to problem with hostname . Please check the hostname ,some times database team will maintain many hostname for connecting same database . Please check with database team regarding this connection issue.
if you have an array
var subcategories=[{name:"test",desc:"test"}];
function hasCategory(nameStr) {
for(let i=0;i<subcategories.length;i++){
if(subcategories[i].name===nameStr){
return true;
}
}
return false;
}
if you have an object
var category={name:"asd",test:""};
if(category.hasOwnProperty('name')){//or category.name!==undefined
return true;
}else{
return false;
}
Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:
http://www.irt.org/script/311.htm
Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.
Here's a concise solution:
_.differenceWith(a, b, _.isEqual);
Spring for Android do this using RestTemplate easily:
final String url = "http://192.168.1.50:9000/greeting";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Greeting greeting = restTemplate.getForObject(url, Greeting.class);
Goals are executed in phases which help determine the order goals get executed in. The best understanding of this is to look at the default Maven lifecycle bindings which shows which goals get run in which phases by default. The compile
phase goals will always be executed before the test
phase goals, which will always be executed before the package
phase goals and so on.
Part of the confusion is exacerbated by the fact that when you execute Maven you can specify a goal or a phase. If you specify a phase then Maven will run all phases up to the phase you specified in order (e.g. if you specify package it will first run through the compile phase and then the test phase and finally the package phase) and for each phase it will run all goals attached to that phase.
When you create a plugin execution in your Maven build file and you only specify the goal then it will bind that goal to a given default phase. For example, the jaxb:xjc
goal binds by default to the generate-resources
phase. However, when you specify the execution you can also explicitly specify the phase for that goal as well.
If you specify a goal when you execute Maven then it will run that goal and only that goal. In other words, if you specify the jar:jar
goal it will only run the jar:jar
goal to package your code into a jar. If you have not previously run the compile goal or prepared your compiled code in some other way this may very likely fail.
Let's, just as example:
public class Test { public Test() { System.out.println("NO ARGS"); } public Test(String s) { this(); System.out.println("1 ARG"); } public static void main(String args[]) { Test t = new Test("s"); } }
It will print
>>> NO ARGS >>> 1 ARG
The correct way to call the constructor is by:
this();
Update: using .indexOf()
to detect if stat
value is one of arr
elements
Pure JavaScript
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
Below solution quite simple.
<pagination
total-items="totalItems"
items-per-page= "itemsPerPage"
ng-model="currentPage"
class="pagination-sm">
</pagination>
<tr ng-repeat="country in countries.slice((currentPage -1) * itemsPerPage, currentPage * itemsPerPage) ">
The third inet_pton
parameter is a pointer to an in_addr
structure. After a successful inet_pton
call, the in_addr
structure will be populated with the address information. The structure's S_addr
field contains the IP address in network byte order (reverse order).
Example :
#include <arpa/inet.h>
uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
int result;
uint32_t IPv4Identifier = 0;
struct in_addr addr;
// store this IP address in sa:
result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
if (result == -1) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
}
else if (result == 0) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
}
else {
IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
}
return IPv4Identifier;
}
I have created an ansible-playbook that allows you to create a linux account that allows password authentication.
See CreateLinuxAccountWithAnsible.
The hashed password is generated using mkpasswd
command. I've provided the ways to install mkpasswd
on different operating systems.
Here are the steps required to use my script:
Replace <your_user_name>
and <your_password>
inside run.sh
with your desired user name and password.
Change the connection information in inventory
so that ansible can connect to the machine to create a user.
Run ./run.sh
to execute the script.
You should add a __eq__
and a __hash__
method to your Data
class, it could check if the __dict__
attributes are equal (same properties) and then if their values are equal, too.
If you did that, you can use
test = Data()
test.n = 5
found = test in myList
The in
keyword checks if test
is in myList
.
If you only want to a a n
property in Data
you could use:
class Data(object):
__slots__ = ['n']
def __init__(self, n):
self.n = n
def __eq__(self, other):
if not isinstance(other, Data):
return False
if self.n != other.n:
return False
return True
def __hash__(self):
return self.n
myList = [ Data(1), Data(2), Data(3) ]
Data(2) in myList #==> True
Data(5) in myList #==> False
Though it is marked as resolved here my KOTLIN RESOLUTION
fun log(properties: Map<String, Any>) {
val propertyPairsList = properties.map { Pair(it.key, it.value) }
val bundle = bundleOf(*propertyPairsList.toTypedArray())
}
bundleOf has vararg parameter
tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:
declare @xml xml
set @xml = "<transaction><item value=""hi"" /></transaction>"
If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:
declare @xml xml
set @xml = "<transaction><item value=""hi "mom" lol"" /></transaction>"
this is what I use for a cross-platform code:
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int main()
{
pollingDelay = 100
//do stuff
//sleep:
#ifdef _WIN32
Sleep(pollingDelay);
#else
usleep(pollingDelay*1000); /* sleep for 100 milliSeconds */
#endif
//do stuff again
return 0;
}
Here is the content of the file MessageBoxManager.cs
#pragma warning disable 0618
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Permissions;
[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]
namespace System.Windows.Forms
{
public class MessageBoxManager
{
private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);
private const int WH_CALLWNDPROCRET = 12;
private const int WM_DESTROY = 0x0002;
private const int WM_INITDIALOG = 0x0110;
private const int WM_TIMER = 0x0113;
private const int WM_USER = 0x400;
private const int DM_GETDEFID = WM_USER + 0;
private const int MBOK = 1;
private const int MBCancel = 2;
private const int MBAbort = 3;
private const int MBRetry = 4;
private const int MBIgnore = 5;
private const int MBYes = 6;
private const int MBNo = 7;
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
private static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
private static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[DllImport("user32.dll")]
private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetDlgCtrlID(IntPtr hwndCtl);
[DllImport("user32.dll")]
private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)]
private static extern bool SetWindowText(IntPtr hWnd, string lpString);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
};
private static HookProc hookProc;
private static EnumChildProc enumProc;
[ThreadStatic]
private static IntPtr hHook;
[ThreadStatic]
private static int nButton;
/// <summary>
/// OK text
/// </summary>
public static string OK = "&OK";
/// <summary>
/// Cancel text
/// </summary>
public static string Cancel = "&Cancel";
/// <summary>
/// Abort text
/// </summary>
public static string Abort = "&Abort";
/// <summary>
/// Retry text
/// </summary>
public static string Retry = "&Retry";
/// <summary>
/// Ignore text
/// </summary>
public static string Ignore = "&Ignore";
/// <summary>
/// Yes text
/// </summary>
public static string Yes = "&Yes";
/// <summary>
/// No text
/// </summary>
public static string No = "&No";
static MessageBoxManager()
{
hookProc = new HookProc(MessageBoxHookProc);
enumProc = new EnumChildProc(MessageBoxEnumProc);
hHook = IntPtr.Zero;
}
/// <summary>
/// Enables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// MessageBoxManager functionality is enabled on current thread only.
/// Each thread that needs MessageBoxManager functionality has to call this method.
/// </remarks>
public static void Register()
{
if (hHook != IntPtr.Zero)
throw new NotSupportedException("One hook per thread allowed.");
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
/// <summary>
/// Disables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// Disables MessageBoxManager functionality on current thread only.
/// </remarks>
public static void Unregister()
{
if (hHook != IntPtr.Zero)
{
UnhookWindowsHookEx(hHook);
hHook = IntPtr.Zero;
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
return CallNextHookEx(hHook, nCode, wParam, lParam);
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = hHook;
if (msg.message == WM_INITDIALOG)
{
int nLength = GetWindowTextLength(msg.hwnd);
StringBuilder className = new StringBuilder(10);
GetClassName(msg.hwnd, className, className.Capacity);
if (className.ToString() == "#32770")
{
nButton = 0;
EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero);
if (nButton == 1)
{
IntPtr hButton = GetDlgItem(msg.hwnd, MBCancel);
if (hButton != IntPtr.Zero)
SetWindowText(hButton, OK);
}
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam)
{
StringBuilder className = new StringBuilder(10);
GetClassName(hWnd, className, className.Capacity);
if (className.ToString() == "Button")
{
int ctlId = GetDlgCtrlID(hWnd);
switch (ctlId)
{
case MBOK:
SetWindowText(hWnd, OK);
break;
case MBCancel:
SetWindowText(hWnd, Cancel);
break;
case MBAbort:
SetWindowText(hWnd, Abort);
break;
case MBRetry:
SetWindowText(hWnd, Retry);
break;
case MBIgnore:
SetWindowText(hWnd, Ignore);
break;
case MBYes:
SetWindowText(hWnd, Yes);
break;
case MBNo:
SetWindowText(hWnd, No);
break;
}
nButton++;
}
return true;
}
}
}
app.service('svc', function(){ this.attr = []; return this; });
app.controller('ctrl', function($scope, svc){
$scope.attr = svc.attr || [];
$scope.$watch('attr', function(neo, old){ /* if necessary */ });
});
app.run(function($rootScope, svc){
$rootScope.svc = svc;
$rootScope.$watch('svc', function(neo, old){ /* change the world */ });
});
Also, I write EDAs (Event-Driven Architectures) so I tend to do something like the following [oversimplified version]:
var Service = function Service($rootScope) {
var $scope = $rootScope.$new(this);
$scope.that = [];
$scope.$watch('that', thatObserver, true);
function thatObserver(what) {
$scope.$broadcast('that:changed', what);
}
};
Then, I put a listener in my controller on the desired channel and just keep my local scope up to date this way.
In conclusion, there's not much of a "Best Practice" -- rather, its mostly preference -- as long as you're keeping things SOLID and employing weak coupling. The reason I would advocate the latter code is because EDAs have the lowest coupling feasible by nature. And if you aren't too concerned about this fact, let us avoid working on the same project together.
Hope this helps...
- To make this answer work with Python 3.x as well, print
is called as a function: in 3.x, only print('foo')
works, whereas 2.x also accepts print 'foo'
.
- For a cross-platform perspective that includes Windows, see kxr's helpful answer.
In bash
, ksh
, or zsh
:
Use an ANSI C-quoted string ($'...'
), which allows using \n
to represent newlines that are expanded to actual newlines before the string is passed to python
:
python -c $'import sys\nfor r in range(10): print("rob")'
Note the \n
between the import
and for
statements to effect a line break.
To pass shell-variable values to such a command, it is safest to use arguments and access them via sys.argv
inside the Python script:
name='rob' # value to pass to the Python script
python -c $'import sys\nfor r in range(10): print(sys.argv[1])' "$name"
See below for a discussion of the pros and cons of using an (escape sequence-preprocessed) double-quoted command string with embedded shell-variable references.
To work safely with $'...'
strings:
\
instances in your original source code.
\<char>
sequences - such as \n
in this case, but also the usual suspects such as \t
, \r
, \b
- are expanded by $'...'
(see man printf
for the supported escapes)'
instances as \'
.If you must remain POSIX-compliant:
Use printf
with a command substitution:
python -c "$(printf %b 'import sys\nfor r in range(10): print("rob")')"
To work safely with this type of string:
\
instances in your original source code.
\<char>
sequences - such as \n
in this case, but also the usual suspects such as \t
, \r
, \b
- are expanded by printf
(see man printf
for the supported escape sequences).Pass a single-quoted string to printf %b
and escape embedded single quotes as '\''
(sic).
Using single quotes protects the string's contents from interpretation by the shell.
That said, for short Python scripts (as in this case) you can use a double-quoted string to incorporate shell variable values into your scripts - as long as you're aware of the associated pitfalls (see next point); e.g., the shell expands $HOME
to the current user's home dir. in the following command:
python -c "$(printf %b "import sys\nfor r in range(10): print('rob is $HOME')")"
However, the generally preferred approach is to pass values from the shell via arguments, and access them via sys.argv
in Python; the equivalent of the above command is:
python -c "$(printf %b 'import sys\nfor r in range(10): print("rob is " + sys.argv[1])')" "$HOME"
While using a double-quoted string is more convenient - it allows you to use embedded single quotes unescaped and embedded double quotes as \"
- it also makes the string subject to interpretation by the shell, which may or may not be the intent; $
and `
characters in your source code that are not meant for the shell may cause a syntax error or alter the string unexpectedly.
\
processing in double-quoted strings can get in the way; for instance, to get Python to produce literal output ro\b
, you must pass ro\\b
to it; with a '...'
shell string and doubled \
instances, we get:python -c "$(printf %b 'import sys\nprint("ro\\\\bs")')" # ok: 'ro\bs'
"..."
shell string:python -c "$(printf %b "import sys\nprint('ro\\\\bs')")" # !! INCORRECT: 'rs'
"\b"
and "\\b"
as literal \b
, requiring a dizzying number of additional \
instances to achieve the desired effect:python -c "$(printf %b "import sys\nprint('ro\\\\\\\\bs')")"
To pass the code via stdin
rather than -c
:
Note: I'm focusing on single-line solutions here; xorho's answer shows how to use a multi-line here-document - be sure to quote the delimiter, however; e.g., <<'EOF'
, unless you explicitly want the shell to expand the string up front (which comes with the caveats noted above).
In bash
, ksh
, or zsh
:
Combine an ANSI C-quoted string ($'...'
) with a here-string (<<<...
):
python - <<<$'import sys\nfor r in range(10): print("rob")'
-
tells python
explicitly to read from stdin (which it does by default).
-
is optional in this case, but if you also want to pass arguments to the scripts, you do need it to disambiguate the argument from a script filename:
python - 'rob' <<<$'import sys\nfor r in range(10): print(sys.argv[1])'
If you must remain POSIX-compliant:
Use printf
as above, but with a pipeline so as to pass its output via stdin:
printf %b 'import sys\nfor r in range(10): print("rob")' | python
With an argument:
printf %b 'import sys\nfor r in range(10): print(sys.argv[1])' | python - 'rob'
After looking for an answer for the question for months, I finally find a really best solution: writing a simple script.
#!/usr/bin/expect
set timeout 20
set cmd [lrange $argv 1 end]
set password [lindex $argv 0]
eval spawn $cmd
expect "assword:" # matches both 'Password' and 'password'
send "$password\r";
interact
Put it to /usr/bin/exp
, then you can use:
exp <password> ssh <anything>
exp <password> scp <anysrc> <anydst>
Done!
We can get the details and status of session from below query as:
select ' Sid, Serial#, Aud sid : '|| s.sid||' , '||s.serial#||' , '||
s.audsid||chr(10)|| ' DB User / OS User : '||s.username||
' / '||s.osuser||chr(10)|| ' Machine - Terminal : '||
s.machine||' - '|| s.terminal||chr(10)||
' OS Process Ids : '||
s.process||' (Client) '||p.spid||' (Server)'|| chr(10)||
' Client Program Name : '||s.program "Session Info"
from v$process p,v$session s
where p.addr = s.paddr
and s.sid = nvl('&SID',s.sid)
and nvl(s.terminal,' ') = nvl('&Terminal',nvl(s.terminal,' '))
and s.process = nvl('&Process',s.process)
and p.spid = nvl('&spid',p.spid)
and s.username = nvl('&username',s.username)
and nvl(s.osuser,' ') = nvl('&OSUser',nvl(s.osuser,' '))
and nvl(s.machine,' ') = nvl('&machine',nvl(s.machine,' '))
and nvl('&SID',nvl('&TERMINAL',nvl('&PROCESS',nvl('&SPID',nvl('&USERNAME',
nvl('&OSUSER',nvl('&MACHINE','NO VALUES'))))))) <> 'NO VALUES'
/
For more details: https://ora-data.blogspot.in/2016/11/query-session-details.html
Thanks,
I recieved a similar error:
AttributeError: module 'pandas' has no attribute 'DataFrame'
The cause of my error was that I ran pip install of pandas as root, and my user did not have permission to the directory.
My fix was to run:
sudo chmod -R 755 /usr/local/lib/python3.6/site-packages
You should either use
if str1[0] == '"' and str1[-1] == '"'
or
if str1.startswith('"') and str1.endswith('"')
but not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for...
import time
time.strftime('%H:%M%p %Z on %b %d, %Y')
If You want to import settings on PuTTY Portable
You can use the putty.reg
file.
Just put it to this path [path_to_Your_portable_apps]PuTTYPortable\Data\settings\putty.reg
. Program will import it
$("#theDiv").append("<img id='theImg' src='theImg.png'/>");
You need to read the documentation here.
Note for git submodule users - the solutions here will not work for you as-is.
Let's say you have a parent repository called dev
, for example, and your submodule repository is called api
.
if you are inside of api
and you get the error mentioned in this question:
error: bad index file sha1 signature
fatal: index file corrupt
The index
file will NOT be inside of a .git
folder. In fact, the .git
won't even be a folder - it will will be a text document with the location of the real .git data for this repository. Likely something like this:
~/dev/api $ cat .git
gitdir: ../.git/modules/api
So, instead of rm -f .git/index
, you will need to do this:
rm -f ../.git/modules/api/index
git reset
or, more generally,
rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index
git reset
Spinning off the closing question, "how do I convert a to type Test::A
" rather than being rigid about the requirement to have a cast in there, and answering several years late only because this seems to be a popular question and nobody else has mentioned the alternative, per the C++11 standard:
5.2.9 Static cast
... an expression
e
can be explicitly converted to a typeT
using astatic_cast
of the formstatic_cast<T>(e)
if the declarationT t(e);
is well-formed, for some invented temporary variablet
(8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.
Therefore directly using the form t(e)
will also work, and you might prefer it for neatness:
auto result = Test(a);
import torch
>>>a = torch.Tensor([1,2,3,4,5])
>>>a.size()
torch.Size([5])
#use view to reshape
>>>b = a.view(1,a.shape[0])
>>>b
tensor([[1., 2., 3., 4., 5.]])
>>>b.size()
torch.Size([1, 5])
>>>b.type()
'torch.FloatTensor'
What you need is overflow-y: scroll;
textarea {_x000D_
overflow-y: scroll;_x000D_
height: 100px;_x000D_
resize: none; /* Remove this if you want the user to resize the textarea */_x000D_
}
_x000D_
<textarea></textarea>
_x000D_
If your collection is not a List
(and thus you can't use get(int index)
), then you can use the iterator:
Iterator iter = collection.iterator();
if (iter.hasNext()) {
Object first = iter.next();
}
Everything is here : http://blog.progs.be/542/date-to-java-time
The answer with "round-tripping" is not exact : when you do
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
if your system timezone is not UTC/GMT, you change the time !
You can use reliable library GSON
private static final Type DATA_TYPE_JSON =
new TypeToken<JSONObject>() {}.getType();
JSONObject orderJSON = new JSONObject();
orderJSON.put("noOfLayers", "2");
orderJSON.put("baseMaterial", "mat");
System.out.println("JSON == "+orderJSON.toString());
String dataAsJson = new Gson().toJson(orderJSON, DATA_TYPE_JSON);
System.out.println("Value of dataAsJson == "+dataAsJson.toString());
String data = new Gson().toJson(dataAsJson);
System.out.println("Value of jsonString == "+data.toString());
I am new to AJAX and I have tried this and it works well.
function q1mrks(country,m) {
// alert("hellow");
if (country.length==0) {
//alert("hellow");
document.getElementById("q1mrks").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("q1mrks").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../location/cal_marks.php?q1mrks="+country+"&marks="+m,true);
//mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
xmlhttp.send();
}
You can append to your PATH
in a minimal fashion. No need for
parentheses unless you're appending more than one element. It also
usually doesn't need quotes. So the simple, short way to append is:
path+=/some/new/bin/dir
This lower-case syntax is using path
as an array, yet also
affects its upper-case partner equivalent, PATH
(to which it is
"bound" via typeset
).
(Notice that no :
is needed/wanted as a separator.)
Then the common pattern for testing a new script/executable becomes:
path+=$PWD/.
# or
path+=$PWD/bin
You can sprinkle path settings around your .zshrc
(as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)
).
Treating path
this way (as an array) also means: no need to do a
rehash
to get the newly pathed commands to be found.
Also take a look at vared path
as a dynamic way to edit path
(and other things).
You may only be interested in path
for this question, but since
we're talking about exports and arrays, note that
arrays generally cannot be exported.
You can even prevent PATH
from taking on duplicate entries
(refer to
this
and this):
typeset -U path
<div>
with some proportions
div {
position: relative;
width: 100%;
height: 100%;
}
<img>
's with their own proportions
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: auto; /* to keep proportions */
height: auto; /* to keep proportions */
max-width: 100%; /* not to stand out from div */
max-height: 100%; /* not to stand out from div */
margin: auto auto 0; /* position to bottom and center */
}
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$adsi.Children | where {$_.SchemaClassName -eq 'user'} | Foreach-Object {
$groups = $_.Groups() | Foreach-Object {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
$_ | Select-Object @{n='UserName';e={$_.Name}},@{n='Groups';e={$groups -join ';'}}
}
This is what the res.locals object is for. Setting variables directly on the request object is not supported or documented. res.locals is guaranteed to hold state over the life of a request.
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
app.use(function(req, res, next) {
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});
To retrieve the variable in the next middleware:
app.use(function(req, res, next) {
if (res.locals.authenticated) {
console.log(res.locals.user.id);
}
next();
});
Swift 4.2 - 5.1 Extension
public extension UIDevice {
class var isPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
class var isPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
class var isTV: Bool {
return UIDevice.current.userInterfaceIdiom == .tv
}
class var isCarPlay: Bool {
return UIDevice.current.userInterfaceIdiom == .carPlay
}
}
Usage
if UIDevice.isPad {
// Do something
}
JScript is Microsoft's implementation of the ECMAScript specification. JavaScript is the Mozilla implementation of the specification.
Update 10/11/2020 to reflect the latest brew changes.
Brew
already provide a command to uninstall itself (this will remove everything you installed with Homebrew):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
If you failed to run this command due to permission (like run as second user), run again with sudo
Then you can install again:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
You can also check like struct_var == (struct{})
. This does not allow you to compare to nil but it does check if it is initialized or not. Be careful while using this method. If your struct can have zero values for all of its fields you won't have great time.
package main
import "fmt"
type A struct {
Name string
}
func main() {
a := A{"Hello"}
var b A
if a == (A{}) {
fmt.Println("A is empty") // Does not print
}
if b == (A{}) {
fmt.Println("B is empty") // Prints
}
}
First, I would check what i
gets initialized to, to see if the elements returned by getElementsByName
are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0
, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).
Also, for your if-condition, this should suffice:
if (!timetemp[0].value) {
// The value is empty.
}
else {
// The value is not empty.
}
The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.
In my particular case, I had a similar error on a legacy website used in my organization. To solve the issue, I had to list the website a a "Trusted site".
To do so:
I'm leaving this here in the remote case it will help someone.
The simplest way of installing SBT on ubuntu is the deb
package provided by Typesafe.
Run the following shell commands:
wget http://apt.typesafe.com/repo-deb-build-0002.deb
sudo dpkg -i repo-deb-build-0002.deb
sudo apt-get update
sudo apt-get install sbt
And you're done !
function setValToAssessment(id)
{
$.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
{
var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm');
$.each(response,function(key,value){
$("<input type='text' value='"+value+"' >")
.attr("id", key)
.attr("name", key)
.appendTo("form");
});
$('#hiddenForm').appendTo('body').submit();
// window.location.href = "<?=URL.$param->module?>/assessment";
});
}
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
Set the Screen orientation to portrait in Manifest file under the activity Tag.
Here the example
You need to enter in every Activity
for portrait
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"
for landscape
android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.thcb.app">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity2"
android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
URL url = new URL(yourUrl, "/api/v1/status.xml");
According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");
Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html
Step : 1 Import webkit
in ViewController.swift
import WebKit
Step : 2 Declare variable of webView.
var webView : WKWebView!
Step : 3 Adding Delegate of WKNavigationDelegate
class ViewController: UIViewController , WKNavigationDelegate{
Step : 4 Adding code in ViewDidLoad
.
let myBlog = "https://iosdevcenters.blogspot.com/"
let url = NSURL(string: myBlog)
let request = NSURLRequest(URL: url!)
// init and load request in webview.
webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.loadRequest(request)
self.view.addSubview(webView)
self.view.sendSubviewToBack(webView)
Step : 5 Edit the info.plist
adding
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>google.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
You will have to create an auto-increment field with the sequence object (this object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".
@Component acts as @Bean annotation in configuration class , register bean in spring context. Also it is parent for @Service, @Repository and @Controller annotation.
@Service, extends @Component annotation and has only naming difference.
@Repository - extends @Component annotation and translate all database exceptions into DataAccessException.
@Controller - acts as controller in MVC pattern. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations.
I was too getting this error, but i have solved this using below concept.
This error comes because of not configuring java properly.
Arrays in java are objects, and all objects are passed by reference. In order to really "copy" an array, instead of creating another name for an array, you have to go and create a new array and copy over all the values. Note that System.arrayCopy will copy 1-dimensional arrays fully, but NOT 2-dimensional arrays. The reason is that a 2D array is in fact a 1D array of 1D arrays, and arrayCopy copies over pointers to the same internal 1D arrays.
You can't initialize your testArray
field this way, because the application resources still aren't ready.
Just change the code to:
package com.xtensivearts.episode.seven;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class Episode7 extends ListActivity {
String[] mTestArray;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
mTestArray = getResources().getStringArray(R.array.testArray);
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
You could put \s*
inbetween every character in your search string so if you were looking for cat you would use c\s*a\s*t\s*s\s*s
It's long but you could build the string dynamically of course.
You can see it working here: http://www.rubular.com/r/zzWwvppSpE
There are a few ways to get the same result:
from __future__ import print_function
import sys
import inspect
def what_is_my_name():
print(inspect.stack()[0][0].f_code.co_name)
print(inspect.stack()[0][3])
print(inspect.currentframe().f_code.co_name)
print(sys._getframe().f_code.co_name)
Note that the inspect.stack
calls are thousands of times slower than the alternatives:
$ python -m timeit -s 'import inspect, sys' 'inspect.stack()[0][0].f_code.co_name'
1000 loops, best of 3: 499 usec per loop
$ python -m timeit -s 'import inspect, sys' 'inspect.stack()[0][3]'
1000 loops, best of 3: 497 usec per loop
$ python -m timeit -s 'import inspect, sys' 'inspect.currentframe().f_code.co_name'
10000000 loops, best of 3: 0.1 usec per loop
$ python -m timeit -s 'import inspect, sys' 'sys._getframe().f_code.co_name'
10000000 loops, best of 3: 0.135 usec per loop
Best approach for Bootstap 3.x -- using CSS flexbox (and requires minimal CSS)..
.equal {
display: flex;
display: -webkit-flex;
flex-wrap: wrap;
}
Bootstrap same height flexbox example
To only apply the same height flexbox at specific breakpoints (responsive), use a media query. For example, here is sm
(768px) and up:
@media (min-width: 768px) {
.row.equal {
display: flex;
flex-wrap: wrap;
}
}
This solution also works well for multiple rows (column wrapping):
https://www.bootply.com/gCEXzPMehZ
Other workarounds
These options will be recommended by others, but are not a good idea for responsive design. These only work for simple single row layouts w/o column wrapping.
1) Using huge negative margins & padding
2) Using display:table-cell (this solution also effects the responsive grid, so a @media query can be used to only apply table
display on wider screens before the columns stack vertically)
Flexbox is now used by default in Bootstrap 4 so there is no need for the extra CSS to make equal height columns: http://www.codeply.com/go/IJYRI4LPwU
Example:
<div class="container">
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>
</div>
public class ThreadParameter
{
public int Port { get; set; }
public string Path { get; set; }
}
Thread t = new Thread(new ParameterizedThreadStart(Startup));
t.Start(new ThreadParameter() { Port = port, Path = path});
Create an object with the port and path objects and pass it to the Startup method.
You will need to install a local mailserver in order to do this. If you want to send it to external e-mail addresses, it might end up in unwanted e-mails or it may not arrive at all.
A good mailserver which I use (I use it on Linux, but it's also available for Windows) is Axigen: http://www.axigen.com/mail-server/download/
You might need some experience with mailservers to install it, but once it works, you can do anything you want with it.
If a function does not return anything, e.g.:
def test():
pass
it has an implicit return value of None
.
Thus, as your pick*
methods do not return anything, e.g.:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
the lines that call them, e.g.:
word = pickEasy()
set word
to None
, so wordInput
in getInput
is None
. This means that:
if guess in wordInput:
is the equivalent of:
if guess in None:
and None
is an instance of NoneType
which does not provide iterator/iteration functionality, so you get that type error.
The fix is to add the return type:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
If you are having issues when using "type": "module"
in package.json
(described in https://github.com/TypeStrong/ts-node/issues/1007) use the following config:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --loader ts-node/esm --experimental-specifier-resolution ./src/index.ts"
}
or in the command line
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "node --loader ts-node/esm --experimental-specifier-resolution src/index.ts"
Addition to the accepted answer:
if you are going to use
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)
this will create actionlink where you can't create new custom attribute or style for the link.
However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })
You can use a simple API from http://www.geoplugin.net/
$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".getRealIpAddr());
echo $xml->geoplugin_countryName ;
echo "<pre>";
foreach ($xml as $key => $value)
{
echo $key , "= " , $value , " \n" ;
}
echo "</pre>";
Function Used
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
Output
United States
geoplugin_city= San Antonio
geoplugin_region= TX
geoplugin_areaCode= 210
geoplugin_dmaCode= 641
geoplugin_countryCode= US
geoplugin_countryName= United States
geoplugin_continentCode= NA
geoplugin_latitude= 29.488899230957
geoplugin_longitude= -98.398696899414
geoplugin_regionCode= TX
geoplugin_regionName= Texas
geoplugin_currencyCode= USD
geoplugin_currencySymbol= $
geoplugin_currencyConverter= 1
It makes you have so many options you can play around with
Thanks
:)
The Nan example above misses one piece, which makes it less generic. To do this more "generically" use df['column_name'].value_counts()
This will give you the counts of each value in that column.
d=['A','A','A','B','C','C'," " ," "," "," "," ","-1"] # for simplicity
df=pd.DataFrame(d)
df.columns=["col1"]
df["col1"].value_counts()
5
A 3
C 2
-1 1
B 1
dtype: int64
"""len(df) give you 12, so we know the rest must be Nan's of some form, while also having a peek into other invalid entries, especially when you might want to ignore them like -1, 0 , "", also"""
@Joao Marcos solution works for me but I had to modify the code to make it work on IE, below if what the code looks like
downloadFile(url,filename) {
var that = this;
const extension = url.split('/').pop().split('?')[0].split('.').pop();
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.responseType = "blob";
req.onload = function (event) {
const fileName = `${filename}.${extension}`;
const blob = req.response;
if (window.navigator.msSaveBlob) { // IE
window.navigator.msSaveOrOpenBlob(blob, fileName);
}
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
URL.revokeObjectURL(link.href);
};
req.send();
},
go path could be every where you want just create a directory and set global path variable in the name of GOPATH to your environment.
mkdir ~/go
export GOPATH=~/go
go get github.com/go-sql-driver/mysql
DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
DECLARE @cnt int
SET @city = 'London'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
RETURN @cnt
Very close, try:
questionText = questionText.replace(/[0-9]/g, '');
replace
doesn't work on the existing string, it returns a new one. If you want to use it, you need to keep it!
Similarly, you can use a new variable:
var withNoDigits = questionText.replace(/[0-9]/g, '');
One last trick to remove whole blocks of digits at once, but that one may go too far:
questionText = questionText.replace(/\d+/g, '');
From the JDK source:
static <T> Function<T, T> identity() {
return t -> t;
}
So, no, as long as it is syntactically correct.
i=-62 . If you want to convert it to a unsigned representation. It would be 4294967234 for a 32 bit integer. A simple way would be to
num=-62
unsigned int n;
n = num
cout<<n;
4294967234
You can use dirname
:
os.path.dirname(path)
Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().
And given the full path, then you can split normally to get the last portion of the path. For example, by using basename
:
os.path.basename(path)
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string ('').
All together:
>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'
Create a configuration file and put your entries there.
SERVER_PORT=10000
THREAD_POOL_COUNT=3
ROOT_DIR=/home/
You can load this file using Properties.load(fileName)
and retrieved values you get(key)
;
I would suggest:
DECLARE @sqlStatement nvarchar(MAX),
@tableName nvarchar(50) = 'TripEvent',
@columnName nvarchar(50) = 'CreatedDate';
SELECT @sqlStatement = 'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + dc.name + ';'
FROM sys.default_constraints AS dc
LEFT JOIN sys.columns AS sc
ON (dc.parent_column_id = sc.column_id)
WHERE dc.parent_object_id = OBJECT_ID(@tableName)
AND type_desc = 'DEFAULT_CONSTRAINT'
AND sc.name = @columnName
PRINT' ['+@tableName+']:'+@@SERVERNAME+'.'+DB_NAME()+'@'+CONVERT(VarChar, GETDATE(), 127)+'; '+@sqlStatement;
IF(LEN(@sqlStatement)>0)EXEC sp_executesql @sqlStatement
In case you want to store it to a file, you solve it using bbox_inches="tight"
argument:
plt.savefig('myfile.png', bbox_inches = "tight")
Unit Testing - As the name suggests, this method tests at the object level. Individual software components are tested for any errors. Knowledge of the program is needed for this test and the test codes are created to check if the software behaves as it is intended to.
Functional Testing - Is carried out without any knowledge of the internal working of the system. The tester will try to use the system by just following requirements, by providing different inputs and testing the generated outputs. This test is also known as closed-box testing or black-box.
Acceptance Testing - This is the last test that is conducted before the software is handed over to the client. It is carried out to ensure that the developed software meets all the customer requirements. There are two types of acceptance testing - one that is carried out by the members of the development team, known as internal acceptance testing (Alpha testing), and the other that is carried out by the customer or end user known as (Beta testing)
Integration Testing - Individual modules that are already subjected to unit testing are integrated with one another. Generally the two approachs are followed :
1) Top-Down
2) Bottom-Up
Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:
In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75
Doing some rough math:
75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB
So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.
If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.
To get reference to UIViewController having UIView, you could make extension of UIResponder (which is super class for UIView and UIViewController), which allows to go up through the responder chain and thus reaching UIViewController (otherwise returning nil).
extension UIResponder {
func getParentViewController() -> UIViewController? {
if self.nextResponder() is UIViewController {
return self.nextResponder() as? UIViewController
} else {
if self.nextResponder() != nil {
return (self.nextResponder()!).getParentViewController()
}
else {return nil}
}
}
}
//Swift 3
extension UIResponder {
func getParentViewController() -> UIViewController? {
if self.next is UIViewController {
return self.next as? UIViewController
} else {
if self.next != nil {
return (self.next!).getParentViewController()
}
else {return nil}
}
}
}
let vc = UIViewController()
let view = UIView()
vc.view.addSubview(view)
view.getParentViewController() //provide reference to vc
Just checkout the commit you wants your new branch start from and create a new branch
git checkout -b newbranch 6e559cb95
("Jesse" or "jesse")
The above expression tests whether or not "Jesse"
evaluates to True
. If it does, then the expression will return it; otherwise, it will return "jesse"
. The expression is equivalent to writing:
"Jesse" if "Jesse" else "jesse"
Because "Jesse"
is a non-empty string though, it will always evaluate to True
and thus be returned:
>>> bool("Jesse") # Non-empty strings evaluate to True in Python
True
>>> bool("") # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>
This means that the expression:
name == ("Jesse" or "jesse")
is basically equivalent to writing this:
name == "Jesse"
In order to fix your problem, you can use the in
operator:
# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):
Or, you can lowercase the value of name
with str.lower
and then compare it to "jesse"
directly:
# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":
Its pretty old question but still I would like say about one more option using vi/vim
editor to visualize the tabs. If you have vi/vim
installed then open a Makefile
(e.g. vim Makefile
) and enter :set list
. This will show number of tabs inserted as below,
%-linux: force$
^I@if [ "$(GCC_VERSION)" = "2.96" ] ; then \$
^I^Iecho ===== Generating build tree for legacy $@ architecture =====; \$
^I^I$(CONFIGURE) $(CWD) $@ legacy; \$
^Ielse \$
^I^Iecho ===== Generating build tree for $@ architecture =====; \$
^I^I$(CONFIGURE) $(CWD) $@; \$
^Ifi$
^Icd build-$@;make$
info
If a 2 digit month and date is desired (2016/01/01 vs 2016/1/1)
code
var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);
output
2016/10/06
fiddle
https://jsfiddle.net/Hastig/1xuu7z7h/
credit
More info from and credit to this answer
more
To learn more about .slice
the try it yourself editor at w3schools helped me understand better how to use it.
Just go to vmvare edit->preferences->shared vms. Click on change settings and disable sharing.click on OK.xampp will work fine.
This should work for all IE8 minor versions
if ($.browser.msie && parseInt($.browser.version, 10) === 8) {
alert('IE8');
} else {
alert('Non IE8');
}
-- update
Please note that $.browser is removed from jQuery 1.9
If you want to only trigger validation when the input looses focus you can use onBlur
Trivia: React <17 listens to blur
event and >=17 listens to focusout
event.
As others said, Sessions are clever and has more advantage of hiding the information from the client.
But Cookie still has at least one advantage, you can access your Cookies from Javascript(For example ngCookies). With PHP session you can't access it anywhere outside PHP script.
The best approach to this problem is first making the database column UNIQUE
ALTER TABLE table_name ADD UNIQUE KEY
THEN INSERT IGNORE INTO table_name
,the value won't be inserted if it results in a duplicate key/already exists in the table.
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
Try something like this:
var node=document.createElement("LI");
var textnode=document.createTextNode(firstname);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);
This worked for me.
Object.keys(myMap).map( key => {
console.log("key: " + key);
console.log("value: " + myMap[key]);
});
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property]
or, even worse, x.key
will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty
is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object
will give you your desired effect.
Since using hasOwnProperty
is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
The above is a working, cross-browser, solution to hasOwnProperty
, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
I'm using OS X 10.10, open the shell, type
export PATH=$PATH:/usr/local/mysql/bin
it works temporary.if you use Command+T to open a new tab ,mysql command will not work anymore.
We need to create a .bash_profile file to make it work each time you open a new tab.
nano ~/.bash_profile
add the following line to the file.
# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc
Save the file, then open a new shell tab, it works like a charm..
by the way, why not try https://github.com/dbcli/mycli
pip install -U mycli
it's a tool way better than the mysqlcli.. A command line client for MySQL that can do auto-completion and syntax highlighting
First check cocoapods version
like pod --version
then update like sudo gem install cocoapods --pre
after update you can also check cocoapods version.
Using the spread operator:
const a = [1,2,3]
const [, ...rest] = a.reverse();
const withoutLast = rest.reverse();
console.log(withoutLast)
_x000D_
Clean Build folder + Build
will clear any error you may have even after fixing your code.
Don't forget to ensure you are working with purely integers.
var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
DATA
.replace( /[^\d]/g, '' )
.replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
return DATA;
});
Sample from apache conf:
#Default value is 2 minutes
**Timeout 600**
ProxyRequests off
ProxyPass /app balancer://MyApp stickysession=JSESSIONID lbmethod=bytraffic nofailover=On
ProxyPassReverse /app balancer://MyApp
ProxyTimeout 600
<Proxy balancer://MyApp>
BalancerMember http://node1:8080/ route=node1 retry=1 max=25 timeout=600
.........
</Proxy>
Example:
int x = Convert.ToInt32(this.txtboxname.Text) + 1 //You dont need the "this"
txtboxname.Text = x.ToString();
The x.ToString()
makes the integer into string to show that in the text box.
Result:
:)
What include
does is copying all the contents from the file (which is the argument inside the <>
or the ""
), so when the preproccesor finishes its work main.cpp
will look like:
// iostream stuff
int foo(int a){
return ++a;
}
int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}
So foo will be defined in main.cpp
, but a definition also exists in foop.cpp
, so the compiler "gets confused" because of the function duplication.
$('element').html('<h1>TEXT TO INSERT</h1>');
or
$('element').text('TEXT TO INSERT');
Lookup types, introduced in TypeScript 2.1 allow another pattern for simulating string enums:
// String enums in TypeScript 2.1
const EntityType = {
Foo: 'Foo' as 'Foo',
Bar: 'Bar' as 'Bar'
};
function doIt(entity: keyof typeof EntityType) {
// ...
}
EntityType.Foo // 'Foo'
doIt(EntityType.Foo); //
doIt(EntityType.Bar); //
doIt('Foo'); //
doIt('Bad'); //
With version 2.4, TypeScript introduced native support for string enums, so the solution above is not needed. From the TS docs:
enum Colors {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
The problem with setting a background image is it removes blurring. You can remove it without setting a background image. See my answer here.
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
By default CM10 only allows root access from Apps not ADB. Go to Settings -> Developer options -> Root access, and change option to "Apps and ADB".
and if you want to check div has a perticular children(say <p>
use:
if ($('#myfav').children('p').length > 0) {
// do something
}
If you need both words are close each other, for example no more than 3 lines, you can do this:
find . -exec grep -Hn -C 3 "abc" {} \; | grep -C 3 "efg"
Same example but filtering only *.txt files:
find . -name *.txt -exec grep -Hn -C 3 "abc" {} \; | grep -C 3 "efg"
And also you can replace grep
command with egrep
command if you want also find with regular expressions.
C++11 standard on ==
for std::vector
Others have mentioned that operator==
does compare vector contents and works, but here is a quote from the C++11 N3337 standard draft which I believe implies that.
We first look at Chapter 23.2.1 "General container requirements", which documents things that must be valid for all containers, including therefore std::vector
.
That section Table 96 "Container requirements" which contains an entry:
Expression Operational semantics =========== ====================== a == b distance(a.begin(), a.end()) == distance(b.begin(), b.end()) && equal(a.begin(), a.end(), b.begin())
The distance
part of the semantics means that the size of both containers are the same, but stated in a generalized iterator friendly way for non random access addressable containers. distance()
is defined at 24.4.4 "Iterator operations".
Then the key question is what does equal()
mean. At the end of the table we see:
Notes: the algorithm equal() is defined in Clause 25.
and in section 25.2.11 "Equal" we find its definition:
template<class InputIterator1, class InputIterator2> bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2); template<class InputIterator1, class InputIterator2, class BinaryPredicate> bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred);
1 Returns: true if for every iterator i in the range
[first1,last1)
the following corresponding conditions hold:*i == *(first2 + (i - first1))
,pred(*i, *(first2 + (i - first1))) != false
. Otherwise, returns false.
In our case, we care about the overloaded version without BinaryPredicate
version, which corresponds to the first pseudo code definition *i == *(first2 + (i - first1))
, which we see is just an iterator-friendly definition of "all iterated items are the same".
Similar questions for other containers:
I have never done so, but it seems like
MATCH (head, head, body) AGAINST ('some words' IN BOOLEAN MODE)
Should give a double weight to matches found in the head.
Just read this comment on the docs page, Thought it might be of value to you:
Posted by Patrick O'Lone on December 9 2002 6:51am
It should be noted in the documentation that IN BOOLEAN MODE will almost always return a relevance of 1.0. In order to get a relevance that is meaningful, you'll need to:
SELECT MATCH('Content') AGAINST ('keyword1 keyword2') as Relevance
FROM table
WHERE MATCH ('Content') AGAINST('+keyword1+keyword2' IN BOOLEAN MODE)
HAVING Relevance > 0.2
ORDER BY Relevance DESC
Notice that you are doing a regular relevance query to obtain relevance factors combined with a WHERE clause that uses BOOLEAN MODE. The BOOLEAN MODE gives you the subset that fulfills the requirements of the BOOLEAN search, the relevance query fulfills the relevance factor, and the HAVING clause (in this case) ensures that the document is relevant to the search (i.e. documents that score less than 0.2 are considered irrelevant). This also allows you to order by relevance.
This may or may not be a bug in the way that IN BOOLEAN MODE operates, although the comments I've read on the mailing list suggest that IN BOOLEAN MODE's relevance ranking is not very complicated, thus lending itself poorly for actually providing relevant documents. BTW - I didn't notice a performance loss for doing this, since it appears MySQL only performs the FULLTEXT search once, even though the two MATCH clauses are different. Use EXPLAIN to prove this.
So it would seem you may not need to worry about calling the fulltext search twice, though you still should "use EXPLAIN to prove this"
WebElement element = driver.findElement(locator);
Assert.assertNull(element);
The above assertion will pass if element is not present.
This works if you are on ubuntu/trusty64 box:
vagrant ssh
Once you are in the ubuntu box:
sudo su
Now you are root user. You can update root password as shown below:
sudo -i
passwd
Now edit the below line in the file /etc/ssh/sshd_config
PermitRootLogin yes
Also, it is convenient to create your own alternate username:
adduser johndoe
Wait until it asks for password.
There are some problems with the accepted answer when you're using Swift 3! This answer (inspired from NAZIK) works with Swift 3 and the new iPhone models:
import UIKit
public extension UIDevice {
var modelName: String {
#if (arch(i386) || arch(x86_64)) && os(iOS)
let DEVICE_IS_SIMULATOR = true
#else
let DEVICE_IS_SIMULATOR = false
#endif
var machineString = String()
if DEVICE_IS_SIMULATOR == true
{
if let dir = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
machineString = dir
}
}
else {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
machineString = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 , value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
}
switch machineString {
case "iPod4,1": return "iPod Touch 4G"
case "iPod5,1": return "iPod Touch 5G"
case "iPod7,1": return "iPod Touch 6G"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone 9,4": return "iPhone 7 Plus"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4": return "iPad Pro (9.7 inch)"
case "iPad6,7", "iPad6,8": return "iPad Pro (12.9 inch)"
case "AppleTV5,3": return "Apple TV"
default: return machineString
}
}
}
See String.replaceAll
.
Use the regex "\s"
and replace with " "
.
Then use String.trim
.
Try following these steps:
The another solution is service volume, You can define a service volume and mount host's PostgreSQL Data directory in that volume. Check out the given compose file for details.
version: '2'
services:
db:
image: postgres:9.6.1
volumes:
- "/var/lib/postgresql/data:/var/lib/postgresql/data"
ports:
- "5432:5432"
By doing this, another PostgreSQL service will run under container but uses same data directory which host PostgreSQL service is using.
You can change the value of a static readonly string
only in the static
constructor of the class or a variable initializer, whereas you cannot change the value of a const
string anywhere.
Have you tried passing the Update panel's client id to the __doPostBack function? My team has done this to refresh an update panel and as far as I know it worked.
__doPostBack(UpdatePanelClientID, '**Some String**');
Oh - the ugliness of Windows... Order of includes are important here. You need to include winsock2.h before windows.h. Since windows.h is probably included from your precompiled header (stdafx.h), you will need to include winsock2.h from there:
#include <winsock2.h>
#include <windows.h>
I second Jon Skeet's answer and want to add the following links for everyone who want to know more about "volatile" and Interlocked:
Atomicity, volatility and immutability are different, part two
Atomicity, volatility and immutability are different, part three
Sayonara Volatile - (Wayback Machine snapshot of Joe Duffy's Weblog as it appeared in 2012)
In Rails 5+ you can simply use the function as demonstrated below with simple example:
module ApplicationHelper
# format datetime in the format #2018-12-01 12:12 PM
def datetime_format(datetime = nil)
if datetime
datetime.strftime('%Y-%m-%d %H:%M %p')
else
'NA'
end
end
end
class ExamplesController < ApplicationController
def index
current_datetime = helpers.datetime_format DateTime.now
raise current_datetime.inspect
end
end
OUTPUT
"2018-12-10 01:01 AM"
In order to give a value in the table, we need to give a command:
php artisan make:migration create_users_table
and after then this command line
php artisan migrate
......
You can do this:
DB::transaction(function() {
//
});
Everything inside the Closure executes within a transaction. If an exception occurs it will rollback automatically.
I had this issue when I upgraded my project to 4.5 framework and the GridView
had Empty Data Template. Something changed and the following statement which previously was returning the Empty Data Template was now returning the Header Row.
GridViewRow dr = (GridViewRow)this.grdViewRoleMembership.Controls[0].Controls[0];
I changed it to below and the error went away and the GridView started working as expected.
GridViewRow dr = (GridViewRow)this.grdViewRoleMembership.Controls[0].Controls[1];
I hope this helps someone.
I think the best way to look at why this doesn't work is that :before and :after insert their content before or after the content within the tag you're applying them to. So it works with divs or spans (or most other tags) because you can put content inside them.
<div>
:before
Content
:after
</div>
However, an img is a self-contained, self-closing tag, and since it has no separate closing tag, you can't put anything inside of it. (That would need to look like <img>Content</img>
, but of course that doesn't work.)
I know this is an old topic, but it pops up first on Google, so hopefully this will help others learn.
After wasting a lot of time I finally found this silly mistake which might help you as well.
Example:
Closure
Route::post('login', function () {
return response()->json(['key' => 'value'], 200); //Make sure your response is there.
});
Controller Action
Route::post('login','AuthController@login');
class AuthController extends Controller {
...
public function login() {
return response()->json(['key' => 'value'], 200); //Make sure your response is there.
}
...
}
Test CORS
Chrome -> Developer Tools -> Network tab
If anything goes wrong then your response headers won't be here.
Check out BoxShadow and BoxDecoration
A Container
can take a BoxDecoration
(going off of the code you had originally posted) which takes a boxShadow
return Container(
margin: EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)
),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 3), // changes position of shadow
),
],
),
)
Screenshot
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
I find this to be the best solution for me. Let the Date object calculate it for you.
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.
We use Array.from({length: 500})
since 2017.
$("#date").datepicker.regional[""].dateFormat = 'dd/mm/yy';
$("#date").datepicker("setDate", new Date());
Always work for me
As of 1st September 2014, the best locations by price for C and C++ standards documents in PDF are:
C++17 – ISO/IEC 14882:2017: $116 from ansi.org
C++14 – ISO/IEC 14882:2014: $90 NZD (about $60 US) from Standards New Zealand
C++11 – ISO/IEC 14882:2011: $60 from ansi.org $60 from Techstreet
C++03 – ISO 14882:2003: $30 from ansi.org $48 from SAI Global
C++98 – ISO/IEC 14882:1998: $90 NZD (about $60 US) from Standards New Zealand
C17/C18 – ISO/IEC 9899:2018: $185 from SAI Global / $116 from INCITS/ANSI / N2176 / c17_updated_proposed_fdis.pdf draft from November 2017 (Link broken, see Wayback Machine N2176)
C11 – ISO/IEC 9899:2011: $30 $60 from ansi.org / WG14 draft version N1570
C99 – ISO 9899:1999: $30 $60 from ansi.org / WG14 draft version N1256
C90 – AS 3955-1991: $141 from ansi.org $175 from Techstreet (the Australian version of C90, identical to ISO 9899:1990)
C90 – 9899:1990 Hardcopy available from SAI Global ($88 + shipping)
You cannot usually get old revisions of a standard (any standard) directly from the standards bodies shortly after a new edition of the standard is released. Thus, standards for C89, C90, C99, C++98, C++03 will be hard to find for purchase from a standards body. If you need an old revision of a standard, check Techstreet as one possible source. For example, it can still provide the Canadian version CAN/CSA-ISO/IEC 9899:1990 standard in PDF, for a fee.
Print copies of the standards are available from national standards bodies and ISO but are very expensive.
If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of Herb Schildt's book The Annotated ANSI Standard at Amazon, which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors).
The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute):
The working drafts for future standards are often available from the committee websites:
If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet:
ANSI X3.159-198 (C89): I cannot find a PDF of C89, but it is almost the same as the below draft for ISO/IEC 9899:1990 (C90). The only differences are in the boilerplate and section numbering.
ISO/IEC 9899:1990 (C90): https://www.pdf-archive.com/2014/10/02/ansi-iso-9899-1990-1/ansi-iso-9899-1990-1.pdf
(Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as "ANSI/ISO: 9899/99" although this isn't the right name of the later made standard of it, the right name is "ISO/IEC 9899:1990")
ISO/IEC 9899:1999 (C99): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
ISO/IEC 9899:2011 (C11): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
ISO/IEC 9899:2018 (C17/C18): https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf (N2176)
ISO/IEC 14882:1998 (C++98): http://www.lirmm.fr/~ducour/Doc-objets/ISO+IEC+14882-1998.pdf
ISO/IEC 14882:2003 (C++03): https://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf
ISO/IEC 14882:2011 (C++11): http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
ISO/IEC 14882:2014 (C++14): https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true
ISO/IEC 14882:2017 (C++17): http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf
ISO/IEC 14882:2020 (C++20): https://isocpp.org/files/papers/N4860.pdf
Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them.
Even though the draft versions might be very close to the final ratified versions of the standards, some of this post's editors would strongly advise you to get a copy of the actual documents — especially if you're planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash.
It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for "INCITS/ISO/IEC" instead of "ISO/IEC" when looking for a standard is the key. By doing so, one of this post's editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for "INCITS/ISO/IEC 9899:2011" instead of "ISO/IEC 9899:2011" on webstore.ansi.org you will find the reasonably priced PDF version.
The site https://wg21.link/ provides short-URL links to the C++ current working draft and draft standards, and committee papers:
The current draft of the standard is maintained as LaTeX sources on Github. These sources can be converted to HTML using cxxdraft-htmlgen. The following sites maintain HTML pages so generated:
Tim Song also maintains generated HTML and PDF versions of the Networking TS and Ranges TS.
In order to help those getting a Network On Main Thread Exception with an SDK Target >9. This is using droopie's code above but will work similarly for any.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
android.os.NetworkOnMainThreadException
You can use AsyncTask as below
public void onClickMail(View view) {
new SendEmailAsyncTask().execute();
}
class SendEmailAsyncTask extends AsyncTask <Void, Void, Boolean> {
Mail m = new Mail("[email protected]", "my password");
public SendEmailAsyncTask() {
if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "SendEmailAsyncTask()");
String[] toArr = { "to [email protected]"};
m.setTo(toArr);
m.setFrom("from [email protected]");
m.setSubject("Email from Android");
m.setBody("body.");
}
@Override
protected Boolean doInBackground(Void... params) {
if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "doInBackground()");
try {
m.send();
return true;
} catch (AuthenticationFailedException e) {
Log.e(SendEmailAsyncTask.class.getName(), "Bad account details");
e.printStackTrace();
return false;
} catch (MessagingException e) {
Log.e(SendEmailAsyncTask.class.getName(), m.getTo(null) + "failed");
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Now days I believe it's preferred to use a function form of typeof() so...
if(filename === undefined || typeof(filename) !== "string" || filename === "") {
console.log("no filename aborted.");
return;
}
I've run into issues with Webclient.Downloadstring before. If you do, you can try this:
WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
You could also use the following:
<template ngFor let-item [ngForOf]="itemsList">
<div *ng-if="conditon(item)"></div>
</template>
This will only show the div if your items matches the condition
See the angular documentation for more information If you would also need the index, use the following:
<template ngFor let-item [ngForOf]="itemsList" let-i="index">
<div *ng-if="conditon(item, i)"></div>
</template>
Here's what I put together. It works on the select mobile device I needed it for, but I'm not sure how universal the solution is
<a href="mailto:[email protected]?subject=Me&body=%3Chtml%20xmlns%3D%22http:%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%3C%2Fhead%3E%3Cbody%3EPlease%20%3Ca%20href%3D%22http:%2F%2Fwww.w3.org%22%3Eclick%3C%2Fa%3E%20me%3C%2Fbody%3E%3C%2Fhtml%3E">
For whom want to install ext-dom on php 7.1 and up run this command:
sudo apt install php-xml