var array = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17],
c = {}, // counters
s = []; // sortable array
for (var i=0; i<array.length; i++) {
c[array[i]] = c[array[i]] || 0; // initialize
c[array[i]]++;
} // count occurrences
for (var key in c) {
s.push([key, c[key]])
} // build sortable array from counters
s.sort(function(a, b) {return b[1]-a[1];});
var firstMode = s[0][0];
console.log(firstMode);
There are many simple ways to find the mode of a list in Python such as:
import statistics
statistics.mode([1,2,3,3])
>>> 3
Or, you could find the max by its count
max(array, key = array.count)
The problem with those two methods are that they don't work with multiple modes. The first returns an error, while the second returns the first mode.
In order to find the modes of a set, you could use this function:
def mode(array):
most = max(list(map(array.count, array)))
return list(set(filter(lambda x: array.count(x) == most, array)))
If you want to use numpy only:
x = [-1, 2, 1, 3, 3]
vals,counts = np.unique(x, return_counts=True)
gives
(array([-1, 1, 2, 3]), array([1, 1, 1, 2]))
And extract it:
index = np.argmax(counts)
return vals[index]
You should be able to do this in N operations, meaning in just one pass, O(n) time.
Use a map or int[] (if the problem is only for ints) to increment the counters, and also use a variable that keeps the key which has the max count seen. Everytime you increment a counter, ask what the value is and compare it to the key you used last, if the value is bigger update the key.
public class Mode {
public static int mode(final int[] n) {
int maxKey = 0;
int maxCounts = 0;
int[] counts = new int[n.length];
for (int i=0; i < n.length; i++) {
counts[n[i]]++;
if (maxCounts < counts[n[i]]) {
maxCounts = counts[n[i]];
maxKey = n[i];
}
}
return maxKey;
}
public static void main(String[] args) {
int[] n = new int[] { 3,7,4,1,3,8,9,3,7,1 };
System.out.println(mode(n));
}
}
The problem here is the performance, if you have a lot of rows it will be a problem.
If it is your case, please try with this:
import pandas as pd
source = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'],
'City' : ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
'Short_name' : ['NY','New','Spb','NY']})
source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])
source.groupby(['Country','City']).Short_name.value_counts().groupby['Country','City']).first()
I arrived at this page looking to turn off scale mode for good, so I figured I would share what I found:
VBoxManage setextradata global GUI/Input/MachineShortcuts "ScaleMode=None"
Running this in my host's terminal worked like a charm for me.
Source: https://forums.virtualbox.org/viewtopic.php?f=8&t=47821
sys.executable
contains full path of the currently running Python interpreter.
import sys
print(sys.executable)
which is now documented here
If you mean that both ProductName
fields are to have the same value, then:
SELECT a.ProductName,a.NumberofProducts,b.ProductName,b.NumberofProductsSold FROM Table1 a, Table2 b WHERE a.ProductName=b.ProductName;
Or, if you want the ProductName
column to be displayed only once,
SELECT a.ProductName,a.NumberofProducts,b.NumberofProductsSold FROM Table1 a, Table2 b WHERE a.ProductName=b.ProductName;
Otherwise,if any row of Table1 can be associated with any row from Table2 (even though I really wonder why anyone'd want to do that), you could give this a look.
Since a lot of people find this question because of having trouble with dynamically access attributes of an object, I will just point out that you can do this in PHP: $valueRow->{"valueName"}
In context (removed HTML output for readability):
$valueRows = json_decode("{...}"); // Rows of unordered values decoded from a JSON object
foreach ($valueRows as $valueRow) {
foreach ($references as $reference) {
if (isset($valueRow->{$reference->valueName})) {
$tableHtml .= $valueRow->{$reference->valueName};
}
else {
$tableHtml .= " ";
}
}
}
As a general rule, processes running without root privileges cannot bind to ports below 1024.
So try a higher port, or run with elevated privileges via sudo
. You can downgrade privileges after you have bound to the low port using process.setgid
and process.setuid
.
When running your apps on heroku you have to use the port as specified in the PORT environment variable.
See http://devcenter.heroku.com/articles/node-js
const server = require('http').createServer();
const port = process.env.PORT || 3000;
server.listen(port, () => console.log(`Listening on ${port}`));
You can do this with this code also.
public class WriteSDCard extends Activity {
private static final String TAG = "MEDIA";
private TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
/** Method to check whether external media available and writable. This is adapted from
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
/** Method to write ascii text characters to file on SD card. Note that you must add a
WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
a FileNotFound Exception because you won't have write permission. */
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
/** Method to read in a text file placed in the res/raw directory of the application. The
method reads in all lines of the file sequentially. */
private void readRaw(){
tv.append("\nData read from res/raw/textfile.txt:");
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer size
// More efficient (less readable) implementation of above is the composite expression
/*BufferedReader br = new BufferedReader(new InputStreamReader(
this.getResources().openRawResource(R.raw.textfile)), 8192);*/
try {
String test;
while (true){
test = br.readLine();
// readLine() returns null if no more lines in the file
if(test == null) break;
tv.append("\n"+" "+test);
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nThat is all");
}
}
doc_val_check == ""; // == is equality check operator
should be
doc_val_check = ""; // = is assign operator. you need to set empty value
// so you need =
You can write you full code like this:
var doc_val_check = $.trim( $('#doc_title').val() ); // take value of text
// field using .val()
if (doc_val_check.length) {
doc_val_check = ""; // this will not update your text field
}
To update you text field with a ""
you need to try
$('#doc_title').attr('value', doc_val_check);
// or
$('doc_title').val(doc_val_check);
But I think you don't need above process.
$('#doc_title').val("");
.val()
use to set/ get value in text field. With parameter it acts as setter and without parameter acts as getter.
Read more about .val()
var isEqual = function(f,s) {
if (f === s) return true;
if (Array.isArray(f)&&Array.isArray(s)) {
return isEqual(f.sort(), s.sort());
}
if (_.isObject(f)) {
return isEqual(f, s);
}
return _.isEqual(f, s);
};
Like andynormancx' post, use this (if you're working in an Unix environment):
scriptname > /dev/null
Or you can use this (if you're working in a Windows environment):
scriptname > nul
Here is another way to change DNS by using WMIC (Windows Management Instrumentation Command-line).
The commands must be run as administrator to apply.
Clear DNS servers:
wmic nicconfig where (IPEnabled=TRUE) call SetDNSServerSearchOrder ()
Set 1 DNS server:
wmic nicconfig where (IPEnabled=TRUE) call SetDNSServerSearchOrder ("8.8.8.8")
Set 2 DNS servers:
wmic nicconfig where (IPEnabled=TRUE) call SetDNSServerSearchOrder ("8.8.8.8", "8.8.4.4")
Set 2 DNS servers on a particular network adapter:
wmic nicconfig where "(IPEnabled=TRUE) and (Description = 'Local Area Connection')" call SetDNSServerSearchOrder ("8.8.8.8", "8.8.4.4")
Another example for setting the domain search list:
wmic nicconfig call SetDNSSuffixSearchOrder ("domain.tld")
It's used to add padding in UIScrollView
Without contentInset
, a table view is like this:
Then set contentInset
:
tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
The effect is as below:
Seems to be better, right?
And I write a blog to study the contentInset
, criticism is welcome.
You also can do like this:
default: &default
adapter: mysql2
encoding: utf8
username: root
password:
host: 127.0.0.1
port: 3306
development:
<<: *default
database: development_db_name
test:
<<: *default
database: test_db_name
production:
<<: *default
database: production_db_name
The &
makes the command run in the background.
From man bash
:
If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.
Casting the values to an int or float seems to fix it. For example:
$coordinates => array(
(float) $ap->latitude,
(float) $ap->longitude
);
<input id="new" >
<button onselect="myFunction()">it</button>
<script>
function myFunction() {
document.getElementById("new").value = "a";
}
</script>
Using DataFlow as svick suggested may be overkill, and Stephen's answer does not provide the means to control the concurrency of the operation. However, that can be achieved rather simply:
public static async Task RunWithMaxDegreeOfConcurrency<T>(
int maxDegreeOfConcurrency, IEnumerable<T> collection, Func<T, Task> taskFactory)
{
var activeTasks = new List<Task>(maxDegreeOfConcurrency);
foreach (var task in collection.Select(taskFactory))
{
activeTasks.Add(task);
if (activeTasks.Count == maxDegreeOfConcurrency)
{
await Task.WhenAny(activeTasks.ToArray());
//observe exceptions here
activeTasks.RemoveAll(t => t.IsCompleted);
}
}
await Task.WhenAll(activeTasks.ToArray()).ContinueWith(t =>
{
//observe exceptions in a manner consistent with the above
});
}
The ToArray()
calls can be optimized by using an array instead of a list and replacing completed tasks, but I doubt it would make much of a difference in most scenarios. Sample usage per the OP's question:
RunWithMaxDegreeOfConcurrency(10, ids, async i =>
{
ICustomerRepo repo = new CustomerRepo();
var cust = await repo.GetCustomer(i);
customers.Add(cust);
});
EDIT Fellow SO user and TPL wiz Eli Arbel pointed me to a related article from Stephen Toub. As usual, his implementation is both elegant and efficient:
public static Task ForEachAsync<T>(
this IEnumerable<T> source, int dop, Func<T, Task> body)
{
return Task.WhenAll(
from partition in Partitioner.Create(source).GetPartitions(dop)
select Task.Run(async delegate {
using (partition)
while (partition.MoveNext())
await body(partition.Current).ContinueWith(t =>
{
//observe exceptions
});
}));
}
Try this:
jsonResponse = json.loads(response.decode('utf-8'))
You haven't specified the database. If it is one that allows analytical functions it may be faster to use this approach than the GROUP BY one(definitely faster in Oracle, most likely faster in the late SQL Server editions, don't know about others).
Syntax in SQL Server would be:
SELECT c.*, p.*
FROM customer c INNER JOIN
(SELECT RANK() OVER (PARTITION BY customer_id ORDER BY date DESC) r, *
FROM purchase) p
ON (c.id = p.customer_id)
WHERE p.r = 1
Just want to point out you do not need to specify all dimensions of the array.
The leftmost dimension can be 'guessed' by the compiler.
#include <stdio.h>
int main(void) {
int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
printf("sizeof arr is %d bytes\n", (int)sizeof arr);
printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
return 0;
}
There is an almost imperceptible setting that fixed this issue for me. If there is a particular source file in which the breakpoint isn't hitting, it could be listed in
For some reason unknown to me, VS 2013 decided to place a source file there, and subsequently, I couldn't hit breakpoint in that file anymore. This may be the culprit for "source code is different from the original version".
I've never actually seen that 1.0.* feature work in VS2005 or VS2008. Is there something that needs to be done to set VS to increment the values?
If AssemblyInfo.cs is hardcoded with 1.0.*, then where are the real build/revision stored?
After putting 1.0.* in AssemblyInfo, we can't use the following statement because ProductVersion now has an invalid value - it's using 1.0.* and not the value assigned by VS:
Version version = new Version(Application.ProductVersion);
Sigh - this seems to be one of those things that everyone asks about but somehow there's never a solid answer. Years ago I saw solutions for generating a revision number and saving it into AssemblyInfo as part of a post-build process. I hoped that sort of dance wouldn't be required for VS2008. Maybe VS2010?
Your selector for the .show()
and .hide()
are not pointing to anything in the code.
Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
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) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}
Update
Apple has clarified that slicing occurs independent of enabling bitcode. I've observed this in practice as well where a non-bitcode enabled app will only be downloaded as the architecture appropriate for the target device.
Original
Bitcode. Archive your app for submission to the App Store in an intermediate representation, which is compiled into 64- or 32-bit executables for the target devices when delivered.
Slicing. Artwork incorporated into the Asset Catalog and tagged for a platform allows the App Store to deliver only what is needed for installation.
The way I read this, if you support bitcode, downloaders of your app will only get the compiled architecture needed for their own device.
I solved the issue without reinstalling node using the commands below:
$ npm uninstall --global gulp gulp-cli
$ rm /usr/local/share/man/man1/gulp.1
$ npm install --global gulp-cli
Use the document.createElement function and then add it as a child of your select.
var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);
If you are using Python on Ubuntu and you only want it to work on Ubuntu a substantially faster way is the use the terminal's locate
program like this.
import subprocess
def find_files(file_name):
command = ['locate', file_name]
output = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]
output = output.decode()
search_results = output.split('\n')
return search_results
search_results
is a list
of the absolute file paths. This is 10,000's of times faster than the methods above and for one search I've done it was ~72,000 times faster.
Try this:
SELECT *
FROM (SELECT * FROM (
SELECT
id,
client_id,
create_time,
ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
)
WHERE rn=1
ORDER BY create_time desc) alias_name
WHERE rownum <= 100
ORDER BY rownum;
Or TOP:
SELECT TOP 2 * FROM Customers; //But not supported in Oracle
NOTE: I suppose that your internal query is fine. Please share your output of this.
Simple just check your teminal in Visual Studio Code Because me was running my node app and i hibernate my laptop then next morning i turn my laptop on back to development of software. THen i run the again command nodemon app.js First waas running from night and the second was running my latest command so two command prompts are listening to same ports that's why you are getting this issue. Simple Close one termianl or all terminal then run your node app.js or nodemon app.js
to detect when the iframe has loaded and its document is ready?
It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).
If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:
<img id="x" ... />
<script type="text/javascript">
document.getElementById('x').onload= function() {
...
};
</script>
there is no guarantee that the item won't already have loaded by the time the script executes.
The ways out of load-races are:
on IE, you can use the ‘readyState’ property to see if something's already loaded;
if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;
the old-school way of including it in the markup:
<img onload="callback(this)" ... />
Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.
I know you asked to Rebase, but I'd Cherry-Pick the commits I wanted to move from Branch2 to Branch1 instead. That way, I wouldn't need to care about when which branch was created from master, and I'd have more control over the merging.
a -- b -- c <-- Master
\ \
\ d -- e -- f -- g <-- Branch1 (Cherry-Pick f & g)
\
f -- g <-- Branch2
The following function works for me:
String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;
Now call the functions like this:
"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");
Simply copy and paste this code in your browser console to TEST.
You can use this code: You shouldn't use this code:
byte[] bytes = streamReader.CurrentEncoding.GetBytes(streamReader.ReadToEnd());
Please see the comment to this answer as to why. I will leave the answer, so people know about the problems with this approach, because I didn't up till now.
Here is a working version of the "build defs". This is similar to my previous answer but I figured out the build month. (You just can't compute build month in a #if
statement, but you can use a ternary expression that will be compiled down to a constant.)
Also, according to the documentation, if the compiler cannot get the time of day it will give you question marks for these strings. So I added tests for this case, and made the various macros return an obviously wrong value (99) if this happens.
#ifndef BUILD_DEFS_H
#define BUILD_DEFS_H
// Example of __DATE__ string: "Jul 27 2012"
// Example of __TIME__ string: "21:06:19"
#define COMPUTE_BUILD_YEAR \
( \
(__DATE__[ 7] - '0') * 1000 + \
(__DATE__[ 8] - '0') * 100 + \
(__DATE__[ 9] - '0') * 10 + \
(__DATE__[10] - '0') \
)
#define COMPUTE_BUILD_DAY \
( \
((__DATE__[4] >= '0') ? (__DATE__[4] - '0') * 10 : 0) + \
(__DATE__[5] - '0') \
)
#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')
#define COMPUTE_BUILD_MONTH \
( \
(BUILD_MONTH_IS_JAN) ? 1 : \
(BUILD_MONTH_IS_FEB) ? 2 : \
(BUILD_MONTH_IS_MAR) ? 3 : \
(BUILD_MONTH_IS_APR) ? 4 : \
(BUILD_MONTH_IS_MAY) ? 5 : \
(BUILD_MONTH_IS_JUN) ? 6 : \
(BUILD_MONTH_IS_JUL) ? 7 : \
(BUILD_MONTH_IS_AUG) ? 8 : \
(BUILD_MONTH_IS_SEP) ? 9 : \
(BUILD_MONTH_IS_OCT) ? 10 : \
(BUILD_MONTH_IS_NOV) ? 11 : \
(BUILD_MONTH_IS_DEC) ? 12 : \
/* error default */ 99 \
)
#define COMPUTE_BUILD_HOUR ((__TIME__[0] - '0') * 10 + __TIME__[1] - '0')
#define COMPUTE_BUILD_MIN ((__TIME__[3] - '0') * 10 + __TIME__[4] - '0')
#define COMPUTE_BUILD_SEC ((__TIME__[6] - '0') * 10 + __TIME__[7] - '0')
#define BUILD_DATE_IS_BAD (__DATE__[0] == '?')
#define BUILD_YEAR ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_YEAR)
#define BUILD_MONTH ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_MONTH)
#define BUILD_DAY ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_DAY)
#define BUILD_TIME_IS_BAD (__TIME__[0] == '?')
#define BUILD_HOUR ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_HOUR)
#define BUILD_MIN ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_MIN)
#define BUILD_SEC ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_SEC)
#endif // BUILD_DEFS_H
With the following test code, the above works great:
printf("%04d-%02d-%02dT%02d:%02d:%02d\n", BUILD_YEAR, BUILD_MONTH, BUILD_DAY, BUILD_HOUR, BUILD_MIN, BUILD_SEC);
However, when I try to use those macros with your stringizing macro, it stringizes the literal expression! I don't know of any way to get the compiler to reduce the expression to a literal integer value and then stringize.
Also, if you try to statically initialize an array of values using these macros, the compiler complains with an error: initializer element is not constant
message. So you cannot do what you want with these macros.
At this point I'm thinking that your best bet is the Python script that just generates a new include file for you. You can pre-compute anything you want in any format you want. If you don't want Python we can write an AWK script or even a C program.
For the first part of the question, I just do a dump of both and diff them. Not sure about mysql, but postgres pg_dump has a command to just dump the schema without the table contents, so you can see if you've changed the schema any.
There is an alternative if you want to use of
and not switch to in
. You can use KeyValuePipe
introduced in 6.1. You can easily iterate over an object:
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
In Rails 4 all I had to do was the def change
def change
rename_table :old_table_name, :new_table_name
end
And all of my indexes were taken care of for me. I did not need to manually update the indexes by removing the old ones and adding new ones.
And it works using the change for going up or down in regards to the indexes as well.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;
itoa(a,arr,10) ; // itoa() is a function of stdlib.h file that convert integer
// int to array itoa( integer, targated array, base u want to
//convert like decimal have 10
for( int i= 0 ; i < strlen(arr); i++) // strlen() function in string file thar return string length
printf("%c",arr[i]);
}
Using vlines
:
import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p = plot(x, y, "o")
vlines(70,100,250)
The basic call signatures are:
vlines(x, ymin, ymax)
hlines(y, xmin, xmax)
I've been using this little cheat for a while now. You might enjoy it. nest the table you want to center in another table:
<table height=100% width=100%>
<td align=center valign=center>
(add your table here)
</td>
</table>
the align and valign put the table exactly in the middle of the screen, no matter what else is going on.
You can also try [BugSense] Reason: Spam Redirect to another url. BugSense collects and analyzed all crash reports and gives you meaningful and visual reports. It's free and it's only 1 line of code in order to integrate.
Disclaimer: I am a co-founder
Node v0.6.x has a stable zlib module in core now - there are some examples on how to use it server-side in the docs too.
An example (taken from the docs):
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
var raw = fs.createReadStream('index.html');
var acceptEncoding = request.headers['accept-encoding'];
if (!acceptEncoding) {
acceptEncoding = '';
}
// Note: this is not a conformant accept-encoding parser.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
if (acceptEncoding.match(/\bdeflate\b/)) {
response.writeHead(200, { 'content-encoding': 'deflate' });
raw.pipe(zlib.createDeflate()).pipe(response);
} else if (acceptEncoding.match(/\bgzip\b/)) {
response.writeHead(200, { 'content-encoding': 'gzip' });
raw.pipe(zlib.createGzip()).pipe(response);
} else {
response.writeHead(200, {});
raw.pipe(response);
}
}).listen(1337);
Use the namespace System.Net.Mail. Here is a link to the MSDN page
You can send emails using SmtpClient class.
I paraphrased the code sample, so checkout MSDNfor details.
MailMessage message = new MailMessage(
"[email protected]",
"[email protected]",
"Subject goes here",
"Body goes here");
SmtpClient client = new SmtpClient(server);
client.Send(message);
The best way to send many emails would be to put something like this in forloop and send away!
I'll never easily remember these cryptic command modifiers so I took the top answer and turned it into a function in my ~/.bashrc
file:
cgrep() {
# For files that are arrays 10's of thousands of characters print.
# Use cpgrep to print 30 characters before and after search patttern.
if [ $# -eq 2 ] ; then
# Format was 'cgrep "search string" /path/to/filename'
grep -o -P ".{0,30}$1.{0,30}" "$2"
else
# Format was 'cat /path/to/filename | cgrep "search string"
grep -o -P ".{0,30}$1.{0,30}"
fi
} # cgrep()
Here's what it looks like in action:
$ ll /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
-rw-r--r-- 1 rick rick 25780 Jul 3 19:05 /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
$ cat /tmp/rick/scp.Mf7UdS/Mf7UdS.Source | cgrep "Link to iconic"
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
$ cgrep "Link to iconic" /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
The file in question is one continuous 25K line and it is hopeless to find what you are looking for using regular grep
.
Notice the two different ways you can call cgrep
that parallels grep
method.
There is a "niftier" way of creating the function where "$2" is only passed when set which would save 4 lines of code. I don't have it handy though. Something like ${parm2} $parm2
. If I find it I'll revise the function and this answer.
Incidentally, .ogv files are video, so "video/ogg", .ogg files are Vorbis audio, so "audio/ogg" and .oga files are general Ogg audio, so also "audio/ogg". Checked in Firefox and work. "application/ogg" is deprecated for all audio or video uses. See http://www.rfc-editor.org/rfc/rfc5334.txt
The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.
On other servers, where the same services are consumed, the certificates were configured as follows:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"
As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"
Once that change was made, all was well. Thanks to everyone who offered assistance.
When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser
as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.
One option is to read the whole body using ioutil.ReadAll()
, which gives you the body as a byte slice.
You may use bytes.NewBuffer()
to obtain an io.Reader
from a byte slice.
The last missing piece is to make the io.Reader
an io.ReadCloser
, because bytes.Buffer
does not have a Close()
method. For this you may use ioutil.NopCloser()
which wraps an io.Reader
, and returns an io.ReadCloser
, whose added Close()
method will be a no-op (does nothing).
Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.
Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!
If you also want to read the response body, then you have to wrap the http.ResponseWriter
you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).
Here's a simple ResponseWriter
wrapper, which just caches the data, so it'll be available after the subsequent handler returns:
type MyResponseWriter struct {
http.ResponseWriter
buf *bytes.Buffer
}
func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
return mrw.buf.Write(p)
}
Note that MyResponseWriter.Write()
just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write()
method) and write the data immediately to the wrapped / embedded ResponseWriter
. You may even modify the data. You have full control.
Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.
Putting the pieces together, here's a full working example:
func loginmw(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(w, "can't read body", http.StatusBadRequest)
return
}
// Work / inspect body. You may even modify it!
// And now set a new body, which will simulate the same data we read:
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
// Create a response wrapper:
mrw := &MyResponseWriter{
ResponseWriter: w,
buf: &bytes.Buffer{},
}
// Call next handler, passing the response wrapper:
handler.ServeHTTP(mrw, r)
// Now inspect response, and finally send it out:
// (You can also modify it before sending it out!)
if _, err := io.Copy(w, mrw.buf); err != nil {
log.Printf("Failed to send out response: %v", err)
}
})
}
For Windows 10 x64
and Python
:
Open a Visual Studio x64 command prompt, and use dumpbin:
dumpbin /dependents [Python Module DLL or PYD file]
If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.
Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.
I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.
It was giving this error: ImportError: DLL load failed: The specified module could not be found
Opened a Visual Studio x64 command prompt.
Under Windows, a .pyd
file is a .dll
file in disguise, so we want to run dumpbin on this file.
cd MyLibrary\build\lib.win-amd64-3.7\Debug
dumpbin /dependents MyLibrary.cp37-win_amd64.pyd
which prints this:
Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file MyLibrary.cp37-win_amd64.pyd
File Type: DLL
Image has the following dependencies:
clang_rt.asan_dbg_dynamic-x86_64.dll
gtestd.dll
tbb_debug.dll
python37.dll
KERNEL32.dll
MSVCP140D.dll
VCOMP140D.DLL
VCRUNTIME140D.dll
VCRUNTIME140_1D.dll
ucrtbased.dll
Summary
1000 .00cfg
D6000 .data
7000 .idata
46000 .pdata
341000 .rdata
23000 .reloc
1000 .rsrc
856000 .text
Searched for clang_rt.asan_dbg_dynamic-x86_64.dll
, copied it into the same directory, problem solved.
Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.
Please feel free to add your own case studies here! I've made it a community wiki answer.
Take a look at ArrayList#addAll(Collection)
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behaviour of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behaviour of this call is undefined if the specified collection is this list, and this list is nonempty.)
So basically you could use
ArrayList<String> listOfStrings = new ArrayList<>(list.size());
listOfStrings.addAll(list);
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array(),
array('id' => 'ASC')
);
I would vote against display: inline-block
since its not supported across browsers, IE < 8 specifically.
.wrapper {
width:500px; /* Adjust to a total width of both .left and .right */
margin: 0 auto;
}
.left {
float: left;
width: 49%; /* Not 50% because of 1px border. */
border: 1px solid #000;
}
.right {
float: right;
width: 49%; /* Not 50% because of 1px border. */
border: 1px solid #F00;
}
<div class="wrapper">
<div class="left">Div 1</div>
<div class="right">Div 2</div>
</div>
EDIT: If no spacing between the cells is desired just change both .left
and .right
to use float: left;
I'd recomment using good old javascript:
document.getElementById("addRunner").reset();
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
Beware of your environment!
For example, this doesn’t seem to work in ECMAscript
y ^= x ^= y ^= x;
But this does
x ^= y ^= x; y ^= x;
My advise? Assume as little as possible.
With user defined functions, you have to declare every parameter, even if they have a default value.
The following would execute successfully:
IF dbo.CheckIfSFExists( 23, default ) = 0
SET @retValue = 'bla bla bla;
Here is an overview in a table format in order to show the differences between Pool.apply
, Pool.apply_async
, Pool.map
and Pool.map_async
. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:
| Multi-args Concurrence Blocking Ordered-results
---------------------------------------------------------------------
Pool.map | no yes yes yes
Pool.map_async | no yes no yes
Pool.apply | yes no yes no
Pool.apply_async | yes yes no no
Pool.starmap | yes yes yes yes
Pool.starmap_async| yes yes no no
Pool.imap
and Pool.imap_async
– lazier version of map and map_async.
Pool.starmap
method, very much similar to map method besides it acceptance of multiple arguments.
Async
methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.
Pool.map
(or Pool.apply
)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.
Is called for a list of jobs in one time
results = pool.map(func, [1, 2, 3])
Can only be called for one job
for x, y in [[1, 1], [2, 2]]:
results.append(pool.apply(func, (x, y)))
def collect_result(result):
results.append(result)
Is called for a list of jobs in one time
pool.map_async(func, jobs, callback=collect_result)
Can only be called for one job and executes a job in the background in parallel
for x, y in [[1, 1], [2, 2]]:
pool.apply_async(worker, (x, y), callback=collect_result)
Is a variant of pool.map
which support multiple arguments
pool.starmap(func, [(1, 1), (2, 1), (3, 1)])
A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.
pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)
Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html
Had the same problem, solved it by getting the appropriate webdriver from: https://chromedriver.chromium.org/downloads
You can know the exact version of your chrome browser by entering the link:
chrome://settings/help
You can also use this;
string employeeName = chldNode.Attributes().ElementAt(0).Name
The setting you are looking for is allow_url_fopen
.
You have two ways of getting around it without changing php.ini, one of them is to use fsockopen()
, and the other is to use cURL.
I recommend using cURL over file_get_contents()
anyways, since it was built for this.
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
Documentation: Deserialize JSON from a file stream
If you would like to insert multiple values lets say from multiple inputs that have different post values but the same table to insert into then simply use:
mysql_query("INSERT INTO `table` (a,b,c,d,e,f,g) VALUES
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g')")
or die (mysql_error()); // Inserts 3 times in 3 different rows
From verify
documentation:
If a certificate is found which is its own issuer it is assumed to be the root CA.
In other words, root CA needs to self signed for verify to work. This is why your second command didn't work. Try this instead:
openssl verify -CAfile RootCert.pem -untrusted Intermediate.pem UserCert.pem
It will verify your entire chain in a single command.
While it's true that floating point type can represent only approximatively decimal data, it's also true that if one rounds numbers to the necessary precision before presenting them, one obtains the correct result. Usually.
Usually because the double type has a precision less than 16 figures. If you require better precision it's not a suitable type. Also approximations can accumulate.
It must be said that even if you use fixed point arithmetic you still have to round numbers, were it not for the fact that BigInteger and BigDecimal give errors if you obtain periodic decimal numbers. So there is an approximation also here.
For example COBOL, historically used for financial calculations, has a maximum precision of 18 figures. So there is often an implicit rounding.
Concluding, in my opinion the double is unsuitable mostly for its 16 digit precision, which can be insufficient, not because it is approximate.
Consider the following output of the subsequent program. It shows that after rounding double give the same result as BigDecimal up to precision 16.
Precision 14
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.000051110111115611
Double : 56789.012345 / 1111111111 = 0.000051110111115611
Precision 15
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.0000511101111156110
Double : 56789.012345 / 1111111111 = 0.0000511101111156110
Precision 16
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.00005111011111561101
Double : 56789.012345 / 1111111111 = 0.00005111011111561101
Precision 17
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.000051110111115611011
Double : 56789.012345 / 1111111111 = 0.000051110111115611013
Precision 18
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.0000511101111156110111
Double : 56789.012345 / 1111111111 = 0.0000511101111156110125
Precision 19
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.00005111011111561101111
Double : 56789.012345 / 1111111111 = 0.00005111011111561101252
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.MathContext;
public class Exercise {
public static void main(String[] args) throws IllegalArgumentException,
SecurityException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
String amount = "56789.012345";
String quantity = "1111111111";
int [] precisions = new int [] {14, 15, 16, 17, 18, 19};
for (int i = 0; i < precisions.length; i++) {
int precision = precisions[i];
System.out.println(String.format("Precision %d", precision));
System.out.println("------------------------------------------------------");
execute("BigDecimalNoRound", amount, quantity, precision);
execute("DoubleNoRound", amount, quantity, precision);
execute("BigDecimal", amount, quantity, precision);
execute("Double", amount, quantity, precision);
System.out.println();
}
}
private static void execute(String test, String amount, String quantity,
int precision) throws IllegalArgumentException, SecurityException,
IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
Method impl = Exercise.class.getMethod("divideUsing" + test, String.class,
String.class, int.class);
String price;
try {
price = (String) impl.invoke(null, amount, quantity, precision);
} catch (InvocationTargetException e) {
price = e.getTargetException().getMessage();
}
System.out.println(String.format("%-30s: %s / %s = %s", test, amount,
quantity, price));
}
public static String divideUsingDoubleNoRound(String amount,
String quantity, int precision) {
// acceptance
double amount0 = Double.parseDouble(amount);
double quantity0 = Double.parseDouble(quantity);
//calculation
double price0 = amount0 / quantity0;
// presentation
String price = Double.toString(price0);
return price;
}
public static String divideUsingDouble(String amount, String quantity,
int precision) {
// acceptance
double amount0 = Double.parseDouble(amount);
double quantity0 = Double.parseDouble(quantity);
//calculation
double price0 = amount0 / quantity0;
// presentation
MathContext precision0 = new MathContext(precision);
String price = new BigDecimal(price0, precision0)
.toString();
return price;
}
public static String divideUsingBigDecimal(String amount, String quantity,
int precision) {
// acceptance
BigDecimal amount0 = new BigDecimal(amount);
BigDecimal quantity0 = new BigDecimal(quantity);
MathContext precision0 = new MathContext(precision);
//calculation
BigDecimal price0 = amount0.divide(quantity0, precision0);
// presentation
String price = price0.toString();
return price;
}
public static String divideUsingBigDecimalNoRound(String amount, String quantity,
int precision) {
// acceptance
BigDecimal amount0 = new BigDecimal(amount);
BigDecimal quantity0 = new BigDecimal(quantity);
//calculation
BigDecimal price0 = amount0.divide(quantity0);
// presentation
String price = price0.toString();
return price;
}
}
System.Reflection.Assembly.GetExecutingAssembly()
.Location
1
Combine that with System.IO.Path.GetDirectoryName
if all you want is the directory.
1As per Mr.Mindor's comment:
System.Reflection.Assembly.GetExecutingAssembly().Location
returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory.System.Reflection.Assembly.GetExecutingAssembly().CodeBase
will return the 'permanent' path of the assembly.
It is highly unlikely that adding NameVirtualHost *:443
is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).
If you're running a relatively stock Apache configuration, you probably have this somewhere:
<VirtualHost _default_:443>
Your best bet is to either:
VirtualHost
container, or VirtualHost
block and create a new one. Don't forget to include all the relevant SSL options. private void addContact(String name, String number){
Uri addContactsUri = ContactsContract.Data.CONTENT_URI;
long rowContactId = getRawContactId();
String displayName = name;
insertContactDisplayName(addContactsUri, rowContactId, displayName);
String phoneNumber = number;
String phoneTypeStr = "Mobile";//work,home etc
insertContactPhoneNumber(addContactsUri, rowContactId, phoneNumber, phoneTypeStr);
}
private void insertContactDisplayName(Uri addContactsUri, long rawContactId, String displayName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
// Put contact display name value.
contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName);
activity.getContentResolver().insert(addContactsUri, contentValues);
}
private long getRawContactId()
{
// Inser an empty contact.
ContentValues contentValues = new ContentValues();
Uri rawContactUri = activity.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
// Get the newly created contact raw id.
long ret = ContentUris.parseId(rawContactUri);
return ret;
}
private void insertContactPhoneNumber(Uri addContactsUri, long rawContactId, String phoneNumber, String phoneTypeStr) {
// Create a ContentValues object.
ContentValues contentValues = new ContentValues();
// Each contact must has an id to avoid java.lang.IllegalArgumentException: raw_contact_id is required error.
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
// Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
// Put phone number value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
// Calculate phone type by user selection.
int phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
if ("home".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
} else if ("mobile".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
} else if ("work".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
}
// Put phone type value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, phoneContactType);
// Insert new contact data into phone contact list.
activity.getContentResolver().insert(addContactsUri, contentValues);
}
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
See my other Answer using the industry-leading java.time classes.
Normally we consider it bad form on StackOverflow.com to answer a specific question by suggesting an alternate technology. But in the case of the date, time, and calendar classes bundled with Java 7 and earlier, those classes are so notoriously bad in both design and execution that I am compelled to suggest using a 3rd-party library instead: Joda-Time.
Joda-Time works by creating immutable objects. So rather than alter the time zone of a DateTime object, we simply instantiate a new DateTime with a different time zone assigned.
Your central concern of using both local and UTC time is so very simple in Joda-Time, taking just 3 lines of code.
org.joda.time.DateTime now = new org.joda.time.DateTime();
System.out.println( "Local time in ISO 8601 format: " + now + " in zone: " + now.getZone() );
System.out.println( "UTC (Zulu) time zone: " + now.toDateTime( org.joda.time.DateTimeZone.UTC ) );
Output when run on the west coast of North America might be:
Local time in ISO 8601 format: 2013-10-15T02:45:30.801-07:00
UTC (Zulu) time zone: 2013-10-15T09:45:30.801Z
Here is a class with several examples and further comments. Using Joda-Time 2.5.
/**
* Created by Basil Bourque on 2013-10-15.
* © Basil Bourque 2013
* This source code may be used freely forever by anyone taking full responsibility for doing so.
*/
public class TimeExample {
public static void main(String[] args) {
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 8 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// You may output to strings in other formats.
// Capture one moment in time, to be used in all the examples to follow.
org.joda.time.DateTime now = new org.joda.time.DateTime();
System.out.println( "Local time in ISO 8601 format: " + now + " in zone: " + now.getZone() );
System.out.println( "UTC (Zulu) time zone: " + now.toDateTime( org.joda.time.DateTimeZone.UTC ) );
// You may specify a time zone in either of two ways:
// • Using identifiers bundled with Joda-Time
// • Using identifiers bundled with Java via its TimeZone class
// ----| Joda-Time Zones |---------------------------------
// Time zone identifiers defined by Joda-Time…
System.out.println( "Time zones defined in Joda-Time : " + java.util.Arrays.toString( org.joda.time.DateTimeZone.getAvailableIDs().toArray() ) );
// Specify a time zone using DateTimeZone objects from Joda-Time.
// http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeZone.html
org.joda.time.DateTimeZone parisDateTimeZone = org.joda.time.DateTimeZone.forID( "Europe/Paris" );
System.out.println( "Paris France (Joda-Time zone): " + now.toDateTime( parisDateTimeZone ) );
// ----| Java Zones |---------------------------------
// Time zone identifiers defined by Java…
System.out.println( "Time zones defined within Java : " + java.util.Arrays.toString( java.util.TimeZone.getAvailableIDs() ) );
// Specify a time zone using TimeZone objects built into Java.
// http://docs.oracle.com/javase/8/docs/api/java/util/TimeZone.html
java.util.TimeZone parisTimeZone = java.util.TimeZone.getTimeZone( "Europe/Paris" );
System.out.println( "Paris France (Java zone): " + now.toDateTime(org.joda.time.DateTimeZone.forTimeZone( parisTimeZone ) ) );
}
}
You need a SMPT Server in order for
... mail($to,$subject,$message,$headers);
to work.
You could try light weight SMTP servers like xmailer
Try https://checkstyle.sourceforge.io/config_filters.html#SuppressionXpathFilter
You can configure it as:
<module name="SuppressionXpathFilter">
<property name="file" value="suppressions-xpath.xml"/>
<property name="optional" value="false"/>
</module>
Generate Xpath suppressions using the CLI with the -g option and specify the output using the -o switch.
https://checkstyle.sourceforge.io/cmdline.html#Command_line_usage
Here's an ant snippet that will help you set up your Checkstyle suppressions auto generation; you can integrate it into Maven using the Antrun plugin.
<target name="checkstyleg">
<move file="suppressions-xpath.xml"
tofile="suppressions-xpath.xml.bak"
preservelastmodified="true"
force="true"
failonerror="false"
verbose="true"/>
<fileset dir="${basedir}"
id="javasrcs">
<include name="**/*.java" />
</fileset>
<pathconvert property="sources"
refid="javasrcs"
pathsep=" " />
<loadfile property="cs.cp"
srcFile="../${cs.classpath.file}" />
<java classname="${cs.main.class}"
logError="true">
<arg line="-c ../${cs.config} -p ${cs.properties} -o ${ant.project.name}-xpath.xml -g ${sources}" />
<classpath>
<pathelement path="${cs.cp}" />
<pathelement path="${java.class.path}" />
</classpath>
</java>
<condition property="file.is.empty" else="false">
<length file="${ant.project.name}-xpath.xml" when="equal" length="0" />
</condition>
<if>
<equals arg1="${file.is.empty}" arg2="false"/>
<then>
<move file="${ant.project.name}-xpath.xml"
tofile="suppressions-xpath.xml"
preservelastmodified="true"
force="true"
failonerror="true"
verbose="true"/>
</then>
</if>
</target>
The suppressions-xpath.xml is specified as the Xpath suppressions source in the Checkstyle rules configuration. In the snippet above, I'm loading the Checkstyle classpath from a file cs.cp into a property. You can choose to specify the classpath directly.
Or you could use groovy within Maven (or Ant) to do the same:
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.nio.file.Paths
def backupSuppressions() {
def supprFileName =
project.properties["checkstyle.suppressionsFile"]
def suppr = Paths.get(supprFileName)
def target = null
if (Files.exists(suppr)) {
def supprBak = Paths.get(supprFileName + ".bak")
target = Files.move(suppr, supprBak,
StandardCopyOption.REPLACE_EXISTING)
println "Backed up " + supprFileName
}
return target
}
def renameSuppressions() {
def supprFileName =
project.properties["checkstyle.suppressionsFile"]
def suppr = Paths.get(project.name + "-xpath.xml")
def target = null
if (Files.exists(suppr)) {
def supprNew = Paths.get(supprFileName)
target = Files.move(suppr, supprNew)
println "Renamed " + suppr + " to " + supprFileName
}
return target
}
def getClassPath(classLoader, sb) {
classLoader.getURLs().each {url->
sb.append("${url.getFile().toString()}:")
}
if (classLoader.parent) {
getClassPath(classLoader.parent, sb)
}
return sb.toString()
}
backupSuppressions()
def cp = getClassPath(this.class.classLoader,
new StringBuilder())
def csMainClass =
project.properties["cs.main.class"]
def csRules =
project.properties["checkstyle.rules"]
def csProps =
project.properties["checkstyle.properties"]
String[] args = ["java", "-cp", cp,
csMainClass,
"-c", csRules,
"-p", csProps,
"-o", project.name + "-xpath.xml",
"-g", "src"]
ProcessBuilder pb = new ProcessBuilder(args)
pb = pb.inheritIO()
Process proc = pb.start()
proc.waitFor()
renameSuppressions()
The only drawback with using Xpath suppressions---besides the checks it doesn't support---is if you have code like the following:
package cstests;
public interface TestMagicNumber {
static byte[] getAsciiRotator() {
byte[] rotation = new byte[95 * 2];
for (byte i = ' '; i <= '~'; i++) {
rotation[i - ' '] = i;
rotation[i + 95 - ' '] = i;
}
return rotation;
}
}
The Xpath suppression generated in this case is not ingested by Checkstyle and the checker fails with an exception on the generated suppression:
<suppress-xpath
files="TestMagicNumber.java"
checks="MagicNumberCheck"
query="/INTERFACE_DEF[./IDENT[@text='TestMagicNumber']]/OBJBLOCK/METHOD_DEF[./IDENT[@text='getAsciiRotator']]/SLIST/LITERAL_FOR/SLIST/EXPR/ASSIGN[./IDENT[@text='i']]/INDEX_OP[./IDENT[@text='rotation']]/EXPR/MINUS[./CHAR_LITERAL[@text='' '']]/PLUS[./IDENT[@text='i']]/NUM_INT[@text='95']"/>
Generating Xpath suppressions is recommended when you have fixed all other violations and wish to suppress the rest. It will not allow you to select specific instances in the code to suppress. You can , however, pick and choose suppressions from the generated file to do just that.
SuppressionXpathSingleFilter is better suited to identify and suppress a specific rule, file or error message. You can configure multiple filters identifying each one by the id attribute.
https://checkstyle.sourceforge.io/config_filters.html#SuppressionXpathSingleFilter
df = pd.DataFrame({
'client_scripting_ms' : client_scripting_ms,
'apimlayer' : apimlayer, 'server' : server
}, index = index)
ax = df.plot(kind = 'barh',
stacked = True,
title = "Chart",
width = 0.20,
align='center',
figsize=(7,5))
plt.legend(loc='upper right', frameon=True)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('right')
No. Looking at the syntax from the man page for GNU make
make [ -f makefile ] [ options ] ... [ targets ] ...
you can specify multiple targets, hence 'no' (at least no in the exact way you specified).
rising_edge is defined as:
FUNCTION rising_edge (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
RETURN (s'EVENT AND (To_X01(s) = '1') AND
(To_X01(s'LAST_VALUE) = '0'));
END;
FUNCTION To_X01 ( s : std_ulogic ) RETURN X01 IS
BEGIN
RETURN (cvt_to_x01(s));
END;
CONSTANT cvt_to_x01 : logic_x01_table := (
'X', -- 'U'
'X', -- 'X'
'0', -- '0'
'1', -- '1'
'X', -- 'Z'
'X', -- 'W'
'0', -- 'L'
'1', -- 'H'
'X' -- '-'
);
If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.
Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk)
to be more descriptive than the (clk'event and clk = '1')
variant.
I ended up using Brads technique to create a scaleToFitWidth
method in UIImage+Extensions
if that's useful to anyone...
-(UIImage *)scaleToFitWidth:(CGFloat)width
{
CGFloat ratio = width / self.size.width;
CGFloat height = self.size.height * ratio;
NSLog(@"W:%f H:%f",width,height);
UIGraphicsBeginImageContext(CGSizeMake(width, height));
[self drawInRect:CGRectMake(0.0f,0.0f,width,height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
then wherever you like
#import "UIImage+Extensions.h"
UIImage *newImage = [image scaleToFitWidth:100.0f];
Also worth noting you could move this further down into a UIView+Extensions
class if you want to render images from a UIView
My guess is that $_.Name does not exist.
If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_
Increase the font-size of glyphicon
to increase all icons size.
.glyphicon {
font-size: 50px;
}
To target only one icon,
.glyphicon.glyphicon-globe {
font-size: 75px;
}
AngularStrap doesn't work in IE8 with angularjs version 1.2.9 so not use this if your application needs to support IE8
The call to time(NULL)
returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t
variable, that pointer variable will point to the current time.
Follow the below simple steps you will able to get the result
Step 1- Create one internal function getDetailFromExternal in your back end. step 2- In that function call the external url by using cUrl like below function
function getDetailFromExternal($p1,$p2) {
$url = "http://request url with parameters";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
exit;
}
Step 3- Call that internal function from your front end by using javascript/jquery Ajax.
Unix
The commands env, set, and printenv display all environment variables and their values. env and set are also used to set environment variables and are often incorporated directly into the shell. printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.
In Unix, the following commands can also be used, but are often dependent on a certain shell.
export VARIABLE=value # for Bourne, bash, and related shells
setenv VARIABLE value # for csh and related shells
You can have a look at this at
You could use the "Shown" event: MSDN - Form.Shown
"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."
I guess you want to do this:
$total_rating_count = count($total_rating_count);
if ($total_rating_count > 0) // because you can't divide through zero
$avg = round($total_rating_points / $total_rating_count, 1);
For a SOAP 1.2 Webservice, I normally use
curl --header "content-type: application/soap+xml" --data @filetopost.xml http://domain/path
These days, if you really need this sort of thing to be accessible in interface builder on a case-by-case basis, you can do it with a simple extension like this:
extension UIButton {
@IBInspectable var numberOfLines: Int {
get { return titleLabel?.numberOfLines ?? 1 }
set { titleLabel?.numberOfLines = newValue }
}
}
Then you can simply set numberOfLines as an attribute on any UIButton or UIButton subclass as if it were a label. The same goes for a whole host of other usually-inaccessible values, such as the corner radius of a view's layer, or the attributes of the shadow that it casts.
I was working on the bounding box problem as a side issue to finding all the points within SrcRad radius of a static LAT, LONG point. There have been quite a few calculations that use
maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
minLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));
to calculate the longitude bounds, but I found this to not give all the answers that were needed. Because what you really want to do is
(SrcRad/RadEarth)/cos(deg2rad(lat))
I know, I know the answer should be the same, but I found that it wasn't. It appeared that by not making sure I was doing the (SRCrad/RadEarth) First and then dividing by the Cos part I was leaving out some location points.
After you get all your bounding box points, if you have a function that calculates the Point to Point Distance given lat, long it is easy to only get those points that are a certain distance radius from the fixed point. Here is what I did. I know it took a few extra steps but it helped me
-- GLOBAL Constants
gc_pi CONSTANT REAL := 3.14159265359; -- Pi
-- Conversion Factor Constants
gc_rad_to_degs CONSTANT NUMBER := 180/gc_pi; -- Conversion for Radians to Degrees 180/pi
gc_deg_to_rads CONSTANT NUMBER := gc_pi/180; --Conversion of Degrees to Radians
lv_stat_lat -- The static latitude point that I am searching from
lv_stat_long -- The static longitude point that I am searching from
-- Angular radius ratio in radians
lv_ang_radius := lv_search_radius / lv_earth_radius;
lv_bb_maxlat := lv_stat_lat + (gc_rad_to_deg * lv_ang_radius);
lv_bb_minlat := lv_stat_lat - (gc_rad_to_deg * lv_ang_radius);
--Here's the tricky part, accounting for the Longitude getting smaller as we move up the latitiude scale
-- I seperated the parts of the equation to make it easier to debug and understand
-- I may not be a smart man but I know what the right answer is... :-)
lv_int_calc := gc_deg_to_rads * lv_stat_lat;
lv_int_calc := COS(lv_int_calc);
lv_int_calc := lv_ang_radius/lv_int_calc;
lv_int_calc := gc_rad_to_degs*lv_int_calc;
lv_bb_maxlong := lv_stat_long + lv_int_calc;
lv_bb_minlong := lv_stat_long - lv_int_calc;
-- Now select the values from your location datatable
SELECT * FROM (
SELECT cityaliasname, city, state, zipcode, latitude, longitude,
-- The actual distance in miles
spherecos_pnttopntdist(lv_stat_lat, lv_stat_long, latitude, longitude, 'M') as miles_dist
FROM Location_Table
WHERE latitude between lv_bb_minlat AND lv_bb_maxlat
AND longitude between lv_bb_minlong and lv_bb_maxlong)
WHERE miles_dist <= lv_limit_distance_miles
order by miles_dist
;
I realize this is answered, but there is another option when you're dealing with objects.
If you have an object that might be:
{
name: {
first: "John",
last: "Doe"
}
}
You can use:
obj.get(property_name, value_if_null)
Like:
obj.get("name", {}).get("first", "Name is missing")
By adding {}
as the default value, if "name" is missing, an empty object is returned and passed through to the next get. This is similar to null-safe-navigation in C#, which would be like obj?.name?.first
.
You should encode only the user name or other part of the URL that could be invalid. URL encoding a URL can lead to problems since something like this:
string url = HttpUtility.UrlEncode("http://www.google.com/search?q=Example");
Will yield
http%3a%2f%2fwww.google.com%2fsearch%3fq%3dExample
This is obviously not going to work well. Instead, you should encode ONLY the value of the key/value pair in the query string, like this:
string url = "http://www.google.com/search?q=" + HttpUtility.UrlEncode("Example");
Hopefully that helps. Also, as teedyay mentioned, you'll still need to make sure illegal file-name characters are removed or else the file system won't like the path.
Update 2016/6
The problem throttling the frame rate is that the screen has a constant update rate, typically 60 FPS.
If we want 24 FPS we will never get the true 24 fps on the screen, we can time it as such but not show it as the monitor can only show synced frames at 15 fps, 30 fps or 60 fps (some monitors also 120 fps).
However, for timing purposes we can calculate and update when possible.
You can build all the logic for controlling the frame-rate by encapsulating calculations and callbacks into an object:
function FpsCtrl(fps, callback) {
var delay = 1000 / fps, // calc. time per frame
time = null, // start time
frame = -1, // frame count
tref; // rAF time reference
function loop(timestamp) {
if (time === null) time = timestamp; // init start time
var seg = Math.floor((timestamp - time) / delay); // calc frame no.
if (seg > frame) { // moved to next frame?
frame = seg; // update
callback({ // callback function
time: timestamp,
frame: frame
})
}
tref = requestAnimationFrame(loop)
}
}
Then add some controller and configuration code:
// play status
this.isPlaying = false;
// set frame-rate
this.frameRate = function(newfps) {
if (!arguments.length) return fps;
fps = newfps;
delay = 1000 / fps;
frame = -1;
time = null;
};
// enable starting/pausing of the object
this.start = function() {
if (!this.isPlaying) {
this.isPlaying = true;
tref = requestAnimationFrame(loop);
}
};
this.pause = function() {
if (this.isPlaying) {
cancelAnimationFrame(tref);
this.isPlaying = false;
time = null;
frame = -1;
}
};
It becomes very simple - now, all that we have to do is to create an instance by setting callback function and desired frame rate just like this:
var fc = new FpsCtrl(24, function(e) {
// render each frame here
});
Then start (which could be the default behavior if desired):
fc.start();
That's it, all the logic is handled internally.
var ctx = c.getContext("2d"), pTime = 0, mTime = 0, x = 0;_x000D_
ctx.font = "20px sans-serif";_x000D_
_x000D_
// update canvas with some information and animation_x000D_
var fps = new FpsCtrl(12, function(e) {_x000D_
ctx.clearRect(0, 0, c.width, c.height);_x000D_
ctx.fillText("FPS: " + fps.frameRate() + _x000D_
" Frame: " + e.frame + _x000D_
" Time: " + (e.time - pTime).toFixed(1), 4, 30);_x000D_
pTime = e.time;_x000D_
var x = (pTime - mTime) * 0.1;_x000D_
if (x > c.width) mTime = pTime;_x000D_
ctx.fillRect(x, 50, 10, 10)_x000D_
})_x000D_
_x000D_
// start the loop_x000D_
fps.start();_x000D_
_x000D_
// UI_x000D_
bState.onclick = function() {_x000D_
fps.isPlaying ? fps.pause() : fps.start();_x000D_
};_x000D_
_x000D_
sFPS.onchange = function() {_x000D_
fps.frameRate(+this.value)_x000D_
};_x000D_
_x000D_
function FpsCtrl(fps, callback) {_x000D_
_x000D_
var delay = 1000 / fps,_x000D_
time = null,_x000D_
frame = -1,_x000D_
tref;_x000D_
_x000D_
function loop(timestamp) {_x000D_
if (time === null) time = timestamp;_x000D_
var seg = Math.floor((timestamp - time) / delay);_x000D_
if (seg > frame) {_x000D_
frame = seg;_x000D_
callback({_x000D_
time: timestamp,_x000D_
frame: frame_x000D_
})_x000D_
}_x000D_
tref = requestAnimationFrame(loop)_x000D_
}_x000D_
_x000D_
this.isPlaying = false;_x000D_
_x000D_
this.frameRate = function(newfps) {_x000D_
if (!arguments.length) return fps;_x000D_
fps = newfps;_x000D_
delay = 1000 / fps;_x000D_
frame = -1;_x000D_
time = null;_x000D_
};_x000D_
_x000D_
this.start = function() {_x000D_
if (!this.isPlaying) {_x000D_
this.isPlaying = true;_x000D_
tref = requestAnimationFrame(loop);_x000D_
}_x000D_
};_x000D_
_x000D_
this.pause = function() {_x000D_
if (this.isPlaying) {_x000D_
cancelAnimationFrame(tref);_x000D_
this.isPlaying = false;_x000D_
time = null;_x000D_
frame = -1;_x000D_
}_x000D_
};_x000D_
}
_x000D_
body {font:16px sans-serif}
_x000D_
<label>Framerate: <select id=sFPS>_x000D_
<option>12</option>_x000D_
<option>15</option>_x000D_
<option>24</option>_x000D_
<option>25</option>_x000D_
<option>29.97</option>_x000D_
<option>30</option>_x000D_
<option>60</option>_x000D_
</select></label><br>_x000D_
<canvas id=c height=60></canvas><br>_x000D_
<button id=bState>Start/Stop</button>
_x000D_
Old answer
The main purpose of requestAnimationFrame
is to sync updates to the monitor's refresh rate. This will require you to animate at the FPS of the monitor or a factor of it (ie. 60, 30, 15 FPS for a typical refresh rate @ 60 Hz).
If you want a more arbitrary FPS then there is no point using rAF as the frame rate will never match the monitor's update frequency anyways (just a frame here and there) which simply cannot give you a smooth animation (as with all frame re-timings) and you can might as well use setTimeout
or setInterval
instead.
This is also a well known problem in the professional video industry when you want to playback a video at a different FPS then the device showing it refresh at. Many techniques has been used such as frame blending and complex re-timing re-building intermediate frames based on motion vectors, but with canvas these techniques are not available and the result will always be jerky video.
var FPS = 24; /// "silver screen"
var isPlaying = true;
function loop() {
if (isPlaying) setTimeout(loop, 1000 / FPS);
... code for frame here
}
The reason why we place setTimeout
first (and why some place rAF
first when a poly-fill is used) is that this will be more accurate as the setTimeout
will queue an event immediately when the loop starts so that no matter how much time the remaining code will use (provided it doesn't exceed the timeout interval) the next call will be at the interval it represents (for pure rAF this is not essential as rAF will try to jump onto the next frame in any case).
Also worth to note that placing it first will also risk calls stacking up as with setInterval
. setInterval
may be slightly more accurate for this use.
And you can use setInterval
instead outside the loop to do the same.
var FPS = 29.97; /// NTSC
var rememberMe = setInterval(loop, 1000 / FPS);
function loop() {
... code for frame here
}
And to stop the loop:
clearInterval(rememberMe);
In order to reduce frame rate when the tab gets blurred you can add a factor like this:
var isFocus = 1;
var FPS = 25;
function loop() {
setTimeout(loop, 1000 / (isFocus * FPS)); /// note the change here
... code for frame here
}
window.onblur = function() {
isFocus = 0.5; /// reduce FPS to half
}
window.onfocus = function() {
isFocus = 1; /// full FPS
}
This way you can reduce the FPS to 1/4 etc.
Open Terminal
cd to/the/program/location
ruby program.rb
or add #!/usr/bin/env ruby
in the first of your program (script tell that this is executed using Ruby Interpreter)
Open Terminal
cd to/the/program/location
chmod 777 program.rb
./program.rb
The problem is that the 'and' is being treated as an 'or'.
No, the problem is that you are using the XPath !=
operator and you aren't aware of its "weird" semantics.
Solution:
Just replace the any x != y
expressions with a not(x = y)
expression.
In your specific case:
Replace:
<xsl:when test="$AccountNumber != '12345' and $Balance != '0'">
with:
<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')">
Explanation:
By definition whenever one of the operands of the !=
operator is a nodeset, then the result of evaluating this operator is true if there is a node in the node-set, whose value isn't equal to the other operand.
So:
$someNodeSet != $someValue
generally doesn't produce the same result as:
not($someNodeSet = $someValue)
The latter (by definition) is true exactly when there isn't a node in $someNodeSet
whose string value is equal to $someValue
.
Lesson to learn:
Never use the !=
operator, unless you are absolutely sure you know what you are doing.
Change
try {
myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
to
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
To see the full code(query) written in stored procedure/ functions, Use below Command:
sp_helptext procedure/function_name
for function name and procedure name don't add prefix 'dbo.' or 'sys.'.
don't add brackets at the end of procedure or function name and also don't pass the parameters.
use sp_helptext keyword and then just pass the procedure/ function name.
use below command to see full code written for Procedure:
sp_helptext ProcedureName
use below command to see full code written for function:
sp_helptext FunctionName
I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.
import pandas as pd
import numpy as np
df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])
newdf = df.loc[df['a'].str.contains('foo') == True]
Works with or without .loc
.
I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either True
or False
. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.
Try:
tr -s ' ' <text.txt | cut -d ' ' -f4
From the tr
man page:
-s, --squeeze-repeats replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character
Another useful time to include @ is when you use FOR
in the command line. For example:
FOR %F IN (*.*) DO ECHO %F
Previous line show for every file: the command prompt, the ECHO
command, and the result of ECHO
command. This way:
FOR %F IN (*.*) DO @ECHO %F
Just the result of ECHO
command is shown.
user: USER
this.user = ({} as USER)
In C#, I had problem with checking RadioButton
,
and this worked for me:
driver.ExecuteJavaScript("arguments[0].checked=true", radio);
Short of using a local templating system like many hundreds now exist in every scripting language or even using your homebrewed one with sed
or m4
and sending the result over to your server, no, you'd need at least SSI.
I use an extension method for this. My extension method first checks to see if the enumeration is null and if so creates an empty list. This allows you to do a foreach on it without explicitly having to check for null.
Here is a very contrived example:
IEnumerable<string> stringEnumerable = null;
StringBuilder csv = new StringBuilder();
stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(","));
Here is the extension method:
public static List<T> ToNonNullList<T>(this IEnumerable<T> obj)
{
return obj == null ? new List<T>() : obj.ToList();
}
One of the approaches may be like this:
1) Create a CSS file with name "style.css" and define an id selector in it:
#pane{ -fx-background-image: url("background_image.jpg"); -fx-background-repeat: stretch; -fx-background-size: 900 506; -fx-background-position: center center; -fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0); }
2) Set the id of the most top control (or any control) in the scene with value defined in CSS and load this CSS file into the scene:
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.setId("pane");
Scene scene = new Scene(root, 300, 250);
scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
}
You can also give an id to the control in a FXML file:
<StackPane id="pane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="demo.Sample">
<children>
</children>
</StackPane>
For more info about JavaFX CSS Styling refer to this guide.
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
Short answer:
use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.
Long answer:
The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.
TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.
Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.
Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.
So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.
Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().
Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.
I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".
In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.
What you can do is:
For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.
I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:
The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)
Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.
It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal
.
json: unsupported type: map[int]main.Foo
JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.
You have two options:
1 Use map[string]Foo
and convert the index to string (using fmt.Sprint for example):
datas := make(map[string]Foo, N)
for i := 0; i < 10; i++ {
datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)
2 Simply just use a slice (javascript array):
datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)
Also had this issue out of the blue. Android studio was taking up 100% of CPU and in expo I had the following error:
Couldn't start project on Android: Error running adb: This computer is not authorized to debug the device. Please follow the instructions here to enable USB debugging: https://developer.android.com/studio/run/device.html#developer-device-options. If you are using Genymotion go to Settings -> ADB, select "Use custom Android SDK tools", and point it at your Android SDK directory.
Cold boot fixed it for me, like boltup_im_coding's answer. You can also cold boot this way if it's already running (with the black screen).
async function fetchDataAsync() {_x000D_
const response = await fetch('paste URL');_x000D_
console.log(await response.json())_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
fetchDataAsync();
_x000D_
I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.
Late Binding
This error can occur due to a missing reference. For example when changing from early binding to late binding, by eliminating the reference, some code may remain that references data types specific the the dropped reference.
Try including the reference to see if the problem disappears.
Maybe the error is not a compiler error but a linker error, so the specific line is unknown. Shame on Microsoft!
To prevent this, make sure every BEGIN TRANSACTION has COMMIT
The following will say successful but will leave uncommitted transactions:
BEGIN TRANSACTION
BEGIN TRANSACTION
<SQL_CODE?
COMMIT
Closing query windows with uncommitted transactions will prompt you to commit your transactions. This will generally resolve the Error 1222 message.
First you need to install cors
by using below command :
npm install cors --save
Now add the following code to your app starting file like ( app.js or server.js
)
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
//enables cors
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
require('./router/index')(app);
'raw string' means it is stored as it appears. For example, '\'
is just a backslash instead of an escaping.
> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
a b
"numeric" "numeric"
Monolithic kernel design is much older than the microkernel idea, which appeared at the end of the 1980's.
Unix and Linux kernels are monolithic, while QNX, L4 and Hurd are microkernels. Mach was initially a microkernel (not Mac OS X), but later converted into a hybrid kernel. Minix (before version 3) wasn't a pure microkernel because device drivers were compiled as part of the kernel.
Monolithic kernels are usually faster than microkernels. The first microkernel Mach was 50% slower than most monolithic kernels, while later ones like L4 were only 2% or 4% slower than the monolithic designs.
Monolithic kernels are big in size, while microkernels are small in size - they usually fit into the processor's L1 cache (first generation microkernels).
In monolithic kernels, the device drivers reside in the kernel space while in the microkernels the device drivers are user-space.
Since monolithic kernels' device drivers reside in the kernel space, monolithic kernels are less secure than microkernels, and failures (exceptions) in the drivers may lead to crashes (displayed as BSODs in Windows). Microkernels are more secure than monolithic kernels, hence more often used in military devices.
Monolithic kernels use signals and sockets to implement inter-process communication (IPC), microkernels use message queues. 1st gen microkernels didn't implement IPC well and were slow on context switches - that's what caused their poor performance.
Adding a new feature to a monolithic system means recompiling the whole kernel or the corresponding kernel module (for modular monolithic kernels), whereas with microkernels you can add new features or patches without recompiling.
To add to the end of the list:
list.append('foo')
To insert at the beginning:
list.insert(0, 'foo')
As a reference:
def toBinary(n):
return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])
This function can convert a positive integer as large as 18446744073709551615
, represented as string '1111111111111111111111111111111111111111111111111111111111111111'
.
It can be modified to serve a much larger integer, though it may not be as handy as "{0:b}".format()
or bin()
.
Use isinstance
, nothing else:
if isinstance(x, pd.DataFrame):
... # do something
PEP8 says explicitly that isinstance
is the preferred way to check types
No: type(x) is pd.DataFrame
No: type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)
And don't even think about
if obj.__class__.__name__ = 'DataFrame':
expect_problems_some_day()
isinstance
handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str
or unicode
), because they derive from basestring
)
if isinstance(obj, basestring):
i_am_string(obj)
Specifically for pandas
DataFrame
objects:
import pandas as pd
isinstance(var, pd.DataFrame)
This is for future readers. I found that the simplest method for me was to use Visual Studio -> Tools -> External Tools. More details in this answer.
Easier to use and good debugging tools.
I have copied the relevant code below from This page. Hope this might help you.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
console.log(percentComplete);
}
}, false);
//Download progress
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
console.log(percentComplete);
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data) {
//Do something success-ish
}
});
This one would delete empty hashes too:
swoop = Proc.new { |k, v| v.delete_if(&swoop) if v.kind_of?(Hash); v.empty? }
hsh.delete_if &swoop
I use such alias in my .bashrc config
alias gpb='git push origin `git rev-parse --abbrev-ref HEAD`'
On the command $gpb
it takes the current branch name and pushes it to the origin.
Here are my other aliases:
alias gst='git status'
alias gbr='git branch'
alias gca='git commit -am'
alias gco='git checkout'
What I did to remove marker was this create a button who allow me do it
Hope i can help someone :)
//Button who active deleteBool
const button = document.getElementById('btn')
//Boolean who let me delete marker
let deleteBool = false
//Button function to enable boolean
button.addEventListener('click',()=>{
deleteBool = true
})
// Function to delete marker
const deleteMarker = (e) => {
if (deleteBool) {
e.target.removeFrom(map)
deleteBooly = false
}
}
//Initiate map
var map = L.map('map').setView([51.505, -0.09], 13);
//Create one marker
let marker = L.marker([51.5, -0.09]).addTo(map)
//Add Marker Function
marker.on('click', deleteMarker)
_x000D_
body {
display: flex;
flex-direction: column;
}
#map{
width: 500px;
height: 500px;
margin: auto;
}
#btn{
width: 50px;
height: 50px;
margin: 2em auto;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<title>MovieCenter</title>
</head>
<body>
<div id="map"></div>
<button id="btn">Click me!</button>
<script script="script" src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<script src="script.js"></script>
</body>
</html>
_x000D_
This is fairly easy to answer from the internet. Set system properties http.proxyHost
and http.proxyPort
. You can do this with System.setProperty()
, or from the command line with the -D
syntax.
The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.
As an aside, apart from the answer by mipadi (which should work by the way), you should know that doing:
git branch -D master
git checkout master
also does exactly what you want without having to redownload everything
(your quote paraphrased). That is because your local repo contains a copy of the remote repo (and that copy is not the same as your local directory, it is not even the same as your checked out branch).
Wiping out a branch is perfectly safe and reconstructing that branch is very fast and involves no network traffic. Remember, git is primarily a local repo by design. Even remote branches have a copy on the local. There's only a bit of metadata that tells git that a specific local copy is actually a remote branch. In git, all files are on your hard disk all the time.
If you don't have any branches other than master, you should:
git checkout -b 'temp'
git branch -D master
git checkout master
git branch -D temp
Marco's answer above is correct, but just to expand on the question of "under what context"...
frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.
center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.
bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds]
on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.
Why is there an frame rectangle and an bounds rectangle in an UIView?
Hopefully this helps clarify the circumstances where each property might get used.
This error happens to me because there is an invalid input in my activity_main.xml file.
When you try to build or clean your project you will see error messages.
I resolved mine by reading those error messages, correct what is wrong in my xml file. then rebuild project.
If you don't know the locale and you want to parse any kind of number, use this parseNumber(text)
function. It is not perfect but take into account most cases :
>>> parseNumber("a 125,00 €")
125
>>> parseNumber("100.000,000")
100000
>>> parseNumber("100 000,000")
100000
>>> parseNumber("100,000,000")
100000000
>>> parseNumber("100 000 000")
100000000
>>> parseNumber("100.001 001")
100.001
>>> parseNumber("$.3")
0.3
>>> parseNumber(".003")
0.003
>>> parseNumber(".003 55")
0.003
>>> parseNumber("3 005")
3005
>>> parseNumber("1.190,00 €")
1190
>>> parseNumber("1190,00 €")
1190
>>> parseNumber("1,190.00 €")
1190
>>> parseNumber("$1190.00")
1190
>>> parseNumber("$1 190.99")
1190.99
>>> parseNumber("1 000 000.3")
1000000.3
>>> parseNumber("1 0002,1.2")
10002.1
>>> parseNumber("")
>>> parseNumber(None)
>>> parseNumber(1)
1
>>> parseNumber(1.1)
1.1
>>> parseNumber("rrr1,.2o")
1
>>> parseNumber("rrr ,.o")
>>> parseNumber("rrr1rrr")
1
I found that running the npm install
command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.
Specifically, I was trying to use ng2-completer
$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.
I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.
cd foo/foo_app
$ npm install ng2-completer --save
If the time is in milliseconds and one need to preserve them:
DECLARE @value VARCHAR(32) = '1561487667713';
SELECT DATEADD(MILLISECOND, CAST(RIGHT(@value, 3) AS INT) - DATEDIFF(MILLISECOND,GETDATE(),GETUTCDATE()), DATEADD(SECOND, CAST(LEFT(@value, 10) AS INT), '1970-01-01T00:00:00'))
This is a way of doing the trick.
f = open("path_to_file", "r")
contents = f.readlines()
f.close()
contents.insert(index, value)
f = open("path_to_file", "w")
contents = "".join(contents)
f.write(contents)
f.close()
"index" and "value" are the line and value of your choice, lines starting from 0.
I know its too late to post answer, but i found completely differently scenario. I tried all possible solution given above but that not works for me. I found very silly mistake / ignorance in my case I checked IIS manager window carefully and found asp.net section was missing there. I have made Turn Windows features on for ASP.net, below is the steps
- Open Control Panel
- Programs\Turn Windows Features on or off Internet
- Information Services World Wide Web Services Application development
- Check for - >Features ASP.Net
I have closed IIS manager window and reopened it, now ASP.NET section is visible. just browse hosted website and it's up on browser.
Eloquent::insert
is the proper solution but it wont update the timestamps, so you can do something like below
$json_array=array_map(function ($a) {
return array_merge($a,['created_at'=>
Carbon::now(),'updated_at'=> Carbon::now()]
);
}, $json_array);
Model::insert($json_array);
The idea is to add created_at and updated_at on whole array before doing insert
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session
(cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
@app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
Your question is a little unclear. If you're generating hostDict
in a loop:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('\n')
If you mean you want each variable within hostDict
to be on a new line:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
When the indent
keyword argument is set it automatically adds newlines.
Another version, with some benefits below.
$sum = ArrayHelper::copyKeys($arr[0]);
foreach ($arr as $item) {
ArrayHelper::addArrays($sum, $item);
}
class ArrayHelper {
public function addArrays(Array &$to, Array $from) {
foreach ($from as $key=>$value) {
$to[$key] += $value;
}
}
public function copyKeys(Array $from, $init=0) {
return array_fill_keys(array_keys($from), $init);
}
}
I wanted to combine the best of Gumbo's, Graviton's, and Chris J's answer with the following goals so I could use this in my app:
a) Initialize the 'sum' array keys outside of the loop (Gumbo). Should help with performance on very large arrays (not tested yet!). Eliminates notices.
b) Main logic is easy to understand without hitting the manuals. (Graviton, Chris J).
c) Solve the more general problem of adding the values of any two arrays with the same keys and make it less dependent on the sub-array structure.
Unlike Gumbo's solution, you could reuse this in cases where the values are not in sub arrays. Imagine in the example below that $arr1
and $arr2
are not hard-coded, but are being returned as the result of calling a function inside a loop.
$arr1 = array(
'gozhi' => 2,
'uzorong' => 1,
'ngangla' => 4,
'langthel' => 5
);
$arr2 = array(
'gozhi' => 5,
'uzorong' => 0,
'ngangla' => 3,
'langthel' => 2
);
$sum = ArrayHelper::copyKeys($arr1);
ArrayHelper::addArrays($sum, $arr1);
ArrayHelper::addArrays($sum, $arr2);
Give this a try:
PS> $nl = [Environment]::NewLine
PS> gci hklm:\software\microsoft\windows\currentversion\uninstall |
ForEach { $_.GetValue("DisplayName") } | Where {$_} | Sort |
Foreach {"$_$nl"} | Out-File addrem.txt -Enc ascii
It yields the following text in my addrem.txt file:
Adobe AIR
Adobe Flash Player 10 ActiveX
...
Note: on my system, GetValue("DisplayName") returns null for some entries, so I filter those out. BTW, you were close with this:
ForEach-Object -Process { "$_.GetValue("DisplayName") `n" }
Except that within a string, if you need to access a property of a variable, that is, "evaluate an expression", then you need to use subexpression syntax like so:
Foreach-Object -Process { "$($_.GetValue('DisplayName'))`r`n" }
Essentially within a double quoted string PowerShell will expand variables like $_
, but it won't evaluate expressions unless you put the expression within a subexpression using this syntax:
$(`<Multiple statements can go in here`>).
You can also receive a 406 response when invalid cookies are stored or referenced in the browser - for example, when running a Rails server in Dev mode locally.
If you happened to run two different projects on the same port, the browser might reference a cookie from a different localhost session.
This has happened to me...tripped me up for a minute. Looking in browser > Developer Mode > Network showed it.
You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.
For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.
While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:
You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.
That means, you are really only establishing about 10-20 concurrent requests.
As others mentioned, you have nothing to worry about in that department.
If yoou use Contains, you could get false positives. Suppose you have a string that contains such text: "My text data Mdd LH" Using Contains method, this method will return true for call. The approach is use equals operator:
bool exists = myStringList.Any(c=>c == "Mdd LH")
You can call bringToFront() on the view you want to get in the front
This is an example:
yourView.bringToFront();
If you have the Apache common utilities in your project rather use the first one. Because its shorter and does exactly the same as the latter one. There won't be any difference between both methods but how it looks inside the source code.
Also a empty check using
listName.size() != 0
Is discouraged because all collection implementations have the
listName.isEmpty()
function that does exactly the same.
So all in all, if you have the Apache common utils in your classpath anyway, use
if (CollectionUtils.isNotEmpty(listName))
in any other case use
if(listName != null && listName.isEmpty())
You will not notice any performance difference. Both lines do exactly the same.
I think it's better to use the Microsoft.VisualBasic.FileIO.TextFieldParser Class if you're working with comma separated values text files.
Works in Ubuntu 20.04
Add this line inside <policymap>
<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />
Comment these lines:
<!--
<policy domain="coder" rights="none" pattern="PS" />
<policy domain="coder" rights="none" pattern="PS2" />
<policy domain="coder" rights="none" pattern="PS3" />
<policy domain="coder" rights="none" pattern="EPS" />
<policy domain="coder" rights="none" pattern="PDF" />
<policy domain="coder" rights="none" pattern="XPS" />
-->
I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.
You can use res.render() or res.redirect() method to redirect to another page using node.js express
Eg:
var bodyParser = require('body-parser');
var express = require('express');
var navigator = require('web-midi-api');
var app = express();
app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render("index");
});
//This reponds a post request for the login page
app.post('/login', function (req, res) {
console.log("Got a POST request for the login");
var data = {
"email": req.body.email,
"password": req.body.password
};
console.log(data);
//Data insertion code
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("college");
var query = { email: data.email };
dbo.collection("user").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
if(result[0].password == data.password)
res.redirect('dashboard.html');
else
res.redirect('login-error.html');
db.close();
});
});
});
// This responds a POST request for the add user
app.post('/insert', function (req, res) {
console.log("Got a POST request for the add user");
var data = {
"first_name" : req.body.firstName,
"second_name" : req.body.secondName,
"organization" : req.body.organization,
"email": req.body.email,
"mobile" : req.body.mobile,
};
console.log(data);
**res.render('success.html',{email:data.email,password:data.password});**
});
//make sure that Service Workers are supported.
if (navigator.serviceWorker) {
navigator.serviceWorker.register('service-worker.js', {scope: '/'})
.then(function (registration) {
console.log(registration);
})
.catch(function (e) {
console.error(e);
})
} else {
console.log('Service Worker is not supported in this browser.');
}
// TODO add service worker code here
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('service-worker.js')
.then(function() { console.log('Service Worker Registered'); });
}
var server = app.listen(63342, function () {
var host = server.address().host;
var port = server.address().port;
console.log("Example app listening at http://localhost:%s", port)
});
Here in the login section, If the email and password matches in the database then the site is directed to dashbaord.html otherwise we will show page-error.html using res.redirect() method. Also you can use res.render() to render a page in node.js
final has three good reasons:
Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.
How about that?
<?php
while($items = array_pop($lists)){
echo "<ul>";
foreach($items as $item){
echo "<li>$item</li>";
}
echo "</ul>";
}
?>
A slight tweak to the function returns the next word from a start point in the entry CREATE FUNCTION [dbo].[GetWord] ( @value varchar(max) , @startLocation int ) RETURNS varchar(max) AS BEGIN SET @value = LTRIM(RTRIM(@Value)) SELECT @startLocation = CASE WHEN @startLocation > Len(@value) THEN LEN(@value) ELSE @startLocation END SELECT @value = CASE WHEN @startLocation > 1 THEN LTRIM(RTRIM(RIGHT(@value, LEN(@value) - @startLocation))) ELSE @value END RETURN CASE CHARINDEX(' ', @value, 1) WHEN 0 THEN @value ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) END END GO SELECT dbo.GetWord(NULL, 1) SELECT dbo.GetWord('', 1) SELECT dbo.GetWord('abc', 1) SELECT dbo.GetWord('abc def', 4) SELECT dbo.GetWord('abc def ghi', 20)
there is also another way to resolve this issue. lets say you have two tables Table1 and Table2. and it is required to fetch all entries of Table1 not referred/present in Table2 using Criteria query. So go ahead like this...
List list=new ArrayList();
Criteria cr=session.createCriteria(Table1.class);
cr.add(Restrictions.sqlRestriction("this_.id not in (select t2.t1_id from Table2 t2 )"));
.
.
. . . It will perform all the subquery function directly in SQL without including 1000 or more parameters in SQL converted by Hibernate framework. It worked for me. Note: You may need to change SQL portion as per your requirement.
Spring Data
is a convenience library on top of JPA
that abstracts away many things and brings Spring magic (like it or not) to the persistence store access. It is primarily used for working with relational databases. In short, it allows you to declare interfaces that have methods like findByNameOrderByAge(String name);
that will be parsed in runtime and converted into appropriate JPA
queries.
Its placement atop of JPA
makes its use tempting for:
Rookie developers who don't know SQL
or know it badly. This is a
recipe for disaster but they can get away with it if the project is trivial.
Experienced engineers who know what they do and want to spindle up things fast. This might be a viable strategy (but read further).
From my experience with Spring Data
, its magic is too much (this is applicable to Spring
in general). I started to use it heavily in one project and eventually hit several corner cases where I couldn't get the library out of my way and ended up with ugly workarounds. Later I read other users' complaints and realized that these issues are typical for Spring Data
. For example, check this issue that led to hours of investigation/swearing:
public TourAccommodationRate createTourAccommodationRate(
@RequestBody TourAccommodationRate tourAccommodationRate
) {
if (tourAccommodationRate.getId() != null) {
throw new BadRequestException("id MUST NOT be specified in a body during entry creation");
}
// This is an ugly hack required for the Room slim model to work. The problem stems from the fact that
// when we send a child entity having the many-to-many (M:N) relation to the containing entity, its
// information is not fetched. As a result, we get NPEs when trying to access all but its Id in the
// code creating the corresponding slim model. By detaching the entity from the persistence context we
// force the ORM to re-fetch it from the database instead of taking it from the cache
tourAccommodationRateRepository.save(tourAccommodationRate);
entityManager.detach(tourAccommodationRate);
return tourAccommodationRateRepository.findOne(tourAccommodationRate.getId());
}
I ended up going lower level and started using JDBI
- a nice library with just enough "magic" to save you from the boilerplate. With it, you have complete control over SQL queries and almost never have to fight the library.
We can define the so-called foreign key
in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,
student
{
_id: ObjectId(...),
name: 'Jane',
courses: ['bio101', 'bio102'] // <= ids of the courses
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
The courses
field contains _id
s of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane
, we need to perform another operation to retrieve the course
document via _id
.
If the course bio101
is removed, we need to perform another operation to update the courses
field in the student
document.
The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:
Example:
student
{
name: 'Kate Monster',
addresses : [
{ street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
{ street: '123 Avenue Q', city: 'New York', cc: 'USA' }
]
}
Like the student
/course
example above.
Suitable for one-to-squillions, such as log messages.
host
{
_id : ObjectID('AAAB'),
name : 'goofy.example.com',
ipaddr : '127.66.66.66'
}
logmsg
{
time : ISODate("2014-03-28T09:42:41.382Z"),
message : 'cpu is on fire!',
host: ObjectID('AAAB') // Reference to the Host document
}
Virtually, a host
is the parent of a logmsg
. Referencing to the host
id saves much space given that the log messages are squillions.
References:
How to do through Source Tree
1: Open SourceTree, click on Repository -> Checkout
2: Click on Create New Branch
3: Select the branch where you want to get code for new branch
4: Give your branch name
5: Push the branch (by click on Push-button)
$.fn.extend({
id : function() {
return this.attr('id');
}
});
alert( $('#element').id() );
Some checking code required of course, but easily implemented!
@scottf
An enum is like a Singleton. The JVM creates the instance.
If you would create it by yourself with classes it could be look like that
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
@Override
public String toString(){
return enumValue;
}
}
And could be used like that:
public class HelloWorld{
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
@Override
public String toString(){
return enumValue;
}
}
public static void main(String []args){
System.out.println(MyEnum.ONE);
System.out.println(MyEnum.TWO);
System.out.println(MyEnum.ONE == MyEnum.ONE);
System.out.println("Hello World");
}
}
You can use java.awt.Robot
to achieve this task.
below is the code of server, which saves the captured screenshot as image in your Directory.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
public class ServerApp extends Thread
{
private ServerSocket serverSocket=null;
private static Socket server = null;
private Date date = null;
private static final String DIR_NAME = "screenshots";
public ServerApp() throws IOException, ClassNotFoundException, Exception{
serverSocket = new ServerSocket(61000);
serverSocket.setSoTimeout(180000);
}
public void run()
{
while(true)
{
try
{
server = serverSocket.accept();
date = new Date();
DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");
String fileName = server.getInetAddress().getHostName().replace(".", "-");
System.out.println(fileName);
BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
ImageIO.write(img, "png", new File("D:\\screenshots\\"+fileName+dateFormat.format(date)+".png"));
System.out.println("Image received!!!!");
//lblimg.setIcon(img);
}
catch(SocketTimeoutException st)
{
System.out.println("Socket timed out!"+st.toString());
//createLogFile("[stocktimeoutexception]"+stExp.getMessage());
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{
ServerApp serverApp = new ServerApp();
serverApp.createDirectory(DIR_NAME);
Thread thread = new Thread(serverApp);
thread.start();
}
private void createDirectory(String dirName) {
File newDir = new File("D:\\"+dirName);
if(!newDir.exists()){
boolean isCreated = newDir.mkdir();
}
}
}
And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.
package com.viremp.client;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import java.util.Random;
import javax.imageio.ImageIO;
public class ClientApp implements Runnable {
private static long nextTime = 0;
private static ClientApp clientApp = null;
private String serverName = "192.168.100.18"; //loop back ip
private int portNo = 61000;
//private Socket serverSocket = null;
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
clientApp = new ClientApp();
clientApp.getNextFreq();
Thread thread = new Thread(clientApp);
thread.start();
}
private void getNextFreq() {
long currentTime = System.currentTimeMillis();
Random random = new Random();
long value = random.nextInt(180000); //1800000
nextTime = currentTime + value;
//return currentTime+value;
}
@Override
public void run() {
while(true){
if(nextTime < System.currentTimeMillis()){
System.out.println(" get screen shot ");
try {
clientApp.sendScreen();
clientApp.getNextFreq();
} catch (AWTException e) {
// TODO Auto-generated catch block
System.out.println(" err"+e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
//System.out.println(" statrted ....");
}
}
private void sendScreen()throws AWTException, IOException {
Socket serverSocket = new Socket(serverName, portNo);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimensions = toolkit.getScreenSize();
Robot robot = new Robot(); // Robot class
BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
serverSocket.close();
}
}
Here is an alternative to the methods mentioned earlier that rely on changing something via CSS and reading it via Javascript. This method does not need window.matchMedia
or Modernizr. It also needs no extra HTML element. It works by using a HTML pseudo-element to 'store' breakpoint information:
body:after {
visibility: hidden;
height: 0;
font-size: 0;
}
@media (min-width: 20em) {
body:after {
content: "mobile";
}
}
@media (min-width: 48em) {
body:after {
content: "tablet";
}
}
@media (min-width: 64em) {
body:after {
content: "desktop";
}
}
I used body
as an example, you can use any HTML element for this. You can add any string or number you want into the content
of the pseudo-element. Doesn't have to be 'mobile' and so on.
Now we can read this information from Javascript in the following way:
var breakpoint = window.getComputedStyle(document.querySelector('body'), ':after').getPropertyValue('content').replace(/"/g,'');
if (breakpoint === 'mobile') {
doSomething();
}
This way we are always sure that the breakpoint information is correct, since it is coming directly from CSS and we don't have to hassle with getting the right screen-width via Javascript.
%~dp0 expands to current directory path of the running batch file.
To get clear understanding, let's create a batch file in a directory.
C:\script\test.bat
with contents:
@echo off
echo %~dp0
When you run it from command prompt, you will see this result:
C:\script\
There are a bunch of similar questions about this, so I'll post what I wrote before:
The only way I got this to work on my machine was to do it this way:
# Ignore all directories, and all sub-directories, and it's contents:
*/*
#Now ignore all files in the current directory
#(This fails to ignore files without a ".", for example
#'file.txt' works, but
#'file' doesn't):
*.*
#Only Include these specific directories and subdirectories and files if you wish:
!wordpress/somefile.jpg
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
!wordpress/*/wp-content/themes/*
!wordpress/*/wp-content/themes/*/*
!wordpress/*/wp-content/themes/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*/*
Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.
This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153
These were useful topics:
I also tried
*
*/*
**/**
and **/wp-content/themes/**
or /wp-content/themes/**/*
None of that worked for me, either. Lots of trail and error!
var data = [
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
];
for(var i = 0, len = data.length; i < length; i++) {
var temp = '<tr><td>' + data[i].id + '</td>';
temp+= '<td>' + data[i].name+ '</td>';
temp+= '<td>' + data[i].category + '</td>';
temp+= '<td>' + data[i].color + '</td></tr>';
$('table tbody').append(temp));
}
When I ran into this problem, it was a result of trying to use an inner class to serve as the DO. Construction of the inner class (silently) required an instance of the enclosing class -- which wasn't available to Jackson.
In this case, moving the inner class to its own .java file fixed the problem.
I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.
static final int COMPARE_EARLIEST = 0;
static final int COMPARE_MOST_RECENT = 1;
public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) {
LocalDate refDate = null;
switch(comparatorType)
{
case COMPARE_EARLIEST:
//returns the most earliest of the date entries
refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item ->
item.toDateTimeAtCurrentTime())).get();
break;
case COMPARE_MOST_RECENT:
//returns the most recent of the date entries
refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item ->
item.toDateTimeAtCurrentTime())).get();
break;
}
return refDate;
}
Python functionsorted
returns ASCII based result for string.
INCORRECT: In the example below, e
and d
is behind H
and W
due it's to ASCII value.
>>>a = "Hello World!"
>>>"".join(sorted(a))
' !!HWdellloor'
CORRECT: In order to write the sorted string without changing the case of letter. Use the code:
>>> a = "Hello World!"
>>> "".join(sorted(a,key=lambda x:x.lower()))
' !deHllloorW'
If you want to remove all punctuation and numbers. Use the code:
>>> a = "Hello World!"
>>> "".join(filter(lambda x:x.isalpha(), sorted(a,key=lambda x:x.lower())))
'deHllloorW'
Can't figure out how to add to the code or reply to the message but here's support for jython that you can tack in before you give up:
# jython
try:
from java.lang import Runtime
runtime = Runtime.getRuntime()
res = runtime.availableProcessors()
if res > 0:
return res
except ImportError:
pass
If you have a file called scaffolds.css.scss, then there's a chance that's overriding all the custom things you're doing in the other files. I commented out that file and suddenly everything worked. If there isn't anything important in that file, you might as well just delete it!
You could use cut
df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf),
labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))
set.seed(24)
df <- data.frame(value= sample(0:2500, 100, replace=TRUE))
uint16_t
is unsigned 16-bit integer.
unsigned short int
is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX
is 65535
). In practice, it usually is 16-bit, but you can't take that as guaranteed.
Note:
uint16_t
.inttypes.h
and stdint.h
are both introduced in C99. If you are using C89, define your own type.uint16_t
may not be provided in certain implementation(See reference below), but unsigned short int
is always available.Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types
For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
It will be $_COOKIE['CaptchaResponseValue']
, not $_COOKIE('CaptchaResponseValue')
Just turn the LINQ to Entity query into a LINQ to Objects query (e.g. call ToArray) anytime you need to use a method call in your LINQ query.
The first option is better performance wise (As ArrayList implement RandomAccess interface). As per the java doc, a List implementation should implement RandomAccess interface if, for typical instances of the class, this loop:
for (int i=0, n=list.size(); i < n; i++)
list.get(i);
runs faster than this loop:
for (Iterator i=list.iterator(); i.hasNext(); )
i.next();
I hope it helps. First option would be slow for sequential access lists.
Post json data (e.g. with curl)
curl -X POST -H 'Content-Type: application/json' \
'http://<host>:<port>/solr/<core>/update?commit=true' \
-d '{ "delete": {"query":"*:*"} }'
BalusC is right. Version 1.0.13 is current, but 1.0.9 appears to have the required bundles:
$ jar tf lib/jfreechart-1.0.9.jar | grep LocalizationBundle.properties org/jfree/chart/LocalizationBundle.properties org/jfree/chart/editor/LocalizationBundle.properties org/jfree/chart/plot/LocalizationBundle.properties
(If you are in MacOS 10.10, try the accumulative -c option of top:
top -c a -pid PID
(This option is not available in other linux, tried with Scientific Linux el6 and RHEL6)
You cannot achieve the desired solution with CSS z-index either, as z-index is only relative to the parent element. So if you have parents A and B with respective children a and b, b's z-index is only relative to other children of B and a's z-index is only relative to other children of A.
The z-index of A and B are relative to each other if they share the same parent element, but all of the children of one will share the same relative z-index at this level.
Contrary to the accepted answer you do not need a custom trust manager, you need to fix your server configuration!
I hit the same problem while connecting to an Apache server with an incorrectly installed dynadot/alphassl certificate. I'm connecting using HttpsUrlConnection (Java/Android), which was throwing -
javax.net.ssl.SSLHandshakeException:
java.security.cert.CertPathValidatorException:
Trust anchor for certification path not found.
The actual problem is a server misconfiguration - test it with http://www.digicert.com/help/ or similar, and it will even tell you the solution:
"The certificate is not signed by a trusted authority (checking against Mozilla's root store). If you bought the certificate from a trusted authority, you probably just need to install one or more Intermediate certificates. Contact your certificate provider for assistance doing this for your server platform."
You can also check the certificate with openssl:
openssl s_client -debug -connect www.thedomaintocheck.com:443
You'll probably see:
Verify return code: 21 (unable to verify the first certificate)
and, earlier in the output:
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=27:certificate not trusted
verify return:1
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=21:unable to verify the first certificate`
The certificate chain will only contain 1 element (your certificate):
Certificate chain
0 s:/OU=Domain Control Validated/CN=www.thedomaintocheck.com
i:/O=AlphaSSL/CN=AlphaSSL CA - G2
... but should reference the signing authorities in a chain back to one which is trusted by Android (Verisign, GlobalSign, etc):
Certificate chain
0 s:/OU=Domain Control Validated/CN=www.thedomaintocheck.com
i:/O=AlphaSSL/CN=AlphaSSL CA - G2
1 s:/O=AlphaSSL/CN=AlphaSSL CA - G2
i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
2 s:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
Instructions (and the intermediate certificates) for configuring your server are usually provided by the authority that issued your certificate, for example: http://www.alphassl.com/support/install-root-certificate.html
After installing the intermediate certificates provided by my certificate issuer I now have no errors when connecting using HttpsUrlConnection.
I recently had the same issue on OS X Sierra with bash shell, and thanks to answers above I only had to edit the file
~/.bash_profile
and append those lines
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
var lowerCaseName = "Your Name".toLowerCase();
Simply restarting Visual Studio worked for me.
**This can be achived easily using two different ways:**
1)We can also do this by using addClass and removeClass of Jquery
2)Toggle class of jQuery
**1)First Way**
$(documnet.ready(function(){
$('#dvId').click(function(){
$('#dvId').removeClass('active class or your class name which you want to remove').addClass('active class or your class name which you want to add');
});
});
**2) Second Way**
i) Here we need to add the class which we want to show while page get loads.
ii)after clicking on div we we will toggle class i.e. the class is added while loading page gets removed and class which we provide in toggleClss gets added :)
<div id="dvId" class="ActiveClassname ">
</div
$(documnet.ready(function(){
$('#dvId').click(function(){
$('#dvId').toggleClass('ActiveClassname InActiveClassName');
});
});
Enjoy.....:)
If you any doubt free to ask any time...
I know it is an old question but still wanted to share how i achieved this. Assuming state in constructor looks like this:
constructor(props) {
super(props);
this.state = {
loading: false,
user: {
email: ""
},
organization: {
name: ""
}
};
this.handleChange = this.handleChange.bind(this);
}
My handleChange
function is like this:
handleChange(e) {
const names = e.target.name.split(".");
const value = e.target.type === "checkbox" ? e.target.checked : e.target.value;
this.setState((state) => {
state[names[0]][names[1]] = value;
return {[names[0]]: state[names[0]]};
});
}
And make sure you name inputs accordingly:
<input
type="text"
name="user.email"
onChange={this.handleChange}
value={this.state.user.firstName}
placeholder="Email Address"
/>
<input
type="text"
name="organization.name"
onChange={this.handleChange}
value={this.state.organization.name}
placeholder="Organization Name"
/>
Here is the syntax:
set terminal pdf {monochrome|color|colour}
{{no}enhanced}
{fname "<font>"} {fsize <fontsize>}
{font "<fontname>{,<fontsize>}"}
{linewidth <lw>} {rounded|butt}
{solid|dashed} {dl <dashlength>}}
{size <XX>{unit},<YY>{unit}}
and an example:
set terminal pdfcairo monochrome enhanced font "Times-New-Roman,12" dashed
This will Helpfull.Easy to implement,100% tested.
for(int i=1;i<linecount;i++)
{
progressBar1.Value = i * progressBar1.Maximum / linecount; //show process bar counts
LabelTotal.Text = i.ToString() + " of " + linecount; //show number of count in lable
int presentage = (i * 100) / linecount;
LabelPresentage.Text = presentage.ToString() + " %"; //show precentage in lable
Application.DoEvents(); keep form active in every loop
}
Command to remove Cordova and ionic
For Window system
For Mac system
For install cordova and ionic
eg.
sudo npm install -g [email protected]
sudo npm install -g [email protected]
You can create a Date
object, and call getTime
on it:
new Date(2010, 6, 26).getTime() / 1000
Typescript
public blobToFile = (theBlob: Blob, fileName:string): File => {
return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}
Javascript
function blobToFile(theBlob, fileName){
return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}
Output
File {name: "fileName", lastModified: 1597081051454, lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 601887, …}
lastModified: 1597081051454
lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time) {}
name: "fileName"
size: 601887
type: "image/png"
webkitRelativePath: ""
__proto__: File
Write one table per join, like this:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
Note that while my query contains actual left join, your query apparently doesn't.
Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).
The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.
In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.
So look what happens when you move conditions to the where clause:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx
left join table4 tab4 on tab4.xya = tab3.xya
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
tab3.desc = "XYZ" and
tab4.ss = tab3.ss
Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss
is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.
PS: left join
and left outer join
are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join
to make not the left, but the right table the leading table. And there is and even full [outer] join
to return a row if there is data in either table.
I finally ended using the following :
bower install --save http://twitter.github.com/bootstrap/assets/bootstrap.zip
Seems cleaner to me since it doesn't clone the whole repo, it only unzip the required assests.
The downside of that is that it breaks the bower philosophy since a bower update
will not update bootstrap.
But I think it's still cleaner than using bower install bootstrap
and then building bootstrap in your workflow.
It's a matter of choice I guess.
Update : seems they now version a dist folder (see: https://github.com/twbs/bootstrap/pull/6342), so just use bower install bootstrap
and point to the assets in the dist
folder
You can simply write:
val mutableList = mutableListOf<Kolory>()
This is the most idiomatic way.
Alternative ways are
val mutableList : MutableList<Kolory> = arrayListOf()
or
val mutableList : MutableList<Kolory> = ArrayList()
This is exploiting the fact that java types like ArrayList
are implicitly implementing the type MutableList
via a compiler trick.
To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent
and background-image: none
) without explicitly specifying any value such as transparent
or none
, you can do so by writing:
background: initial;
You can find your Firebase Web API Key in the follwing way .
Go To project overview -> general -> web API key
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
If you're using multiple slides, and you can use jQuery, you can do the follow to deal with multiple sliders easily:
function updateRangeInput(elem) {_x000D_
$(elem).next().val($(elem).val());_x000D_
}
_x000D_
input { padding: 8px; border: 1px solid #ddd; color: #555; display: block; }_x000D_
input[type=text] { width: 100px; }_x000D_
input[type=range] { width: 400px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="range" min="0" max="100" oninput="updateRangeInput(this)" value="0">_x000D_
<input type="text" value="0">_x000D_
_x000D_
<input type="range" min="0" max="100" oninput="updateRangeInput(this)" value="50">_x000D_
<input type="text" value="50">
_x000D_
Also, by using oninput
on the <input type='range'>
you'll receive events while dragging the range.
The correct way to use max in the having clause is by performing a self join first:
select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)
The following is how you would join with a subquery:
select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
from table1 t1_max
where t1.id = t1_max.id)
Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
join #dataset d_max
on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c
Sub query version:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
from #dataset d_max
where d.id = d_max.id)
The first step you create Filter using @Pipe
in your component.ts file:
your.component.ts
import { Component, Pipe, PipeTransform, Injectable } from '@angular/core';
import { Person} from "yourPath";
@Pipe({
name: 'searchfilter'
})
@Injectable()
export class SearchFilterPipe implements PipeTransform {
transform(items: Person[], value: string): any[] {
if (!items || !value) {
return items;
}
console.log("your search token = "+value);
return items.filter(e => e.firstName.toLowerCase().includes(value.toLocaleLowerCase()));
}
}
@Component({
....
persons;
ngOnInit() {
//inicial persons arrays
}
})
And data structure of Person object:
person.ts
export class Person{
constructor(
public firstName: string,
public lastName: string
) { }
}
In your view in html file:
your.component.html
<input class="form-control" placeholder="Search" id="search" type="text" [(ngModel)]="searchText"/>
<table class="table table-striped table-hover">
<colgroup>
<col span="1" style="width: 50%;">
<col span="1" style="width: 50%;">
</colgroup>
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of persons | searchfilter:searchText">
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</tbody>
</table>
Add the "extern" keyword to the function definitions in point.h
You have to select and send the form data as well:
$("#post-btn").click(function(){
$.post("process.php", $("#reg-form").serialize(), function(data) {
alert(data);
});
});
Take a look at the documentation for the jQuery serialize
method, which encodes the data from the form fields into a data-string to be sent to the server.
The easiest might be:
Array(1, 2, 3) :+ 4
Actually, Array can be implcitly transformed in a WrappedArray
I was getting the error with "Add source roots to PYTHONPATH" as well. My problem was that I had two folders with the same name, like project/subproject1/thing/src
and project/subproject2/thing/src
and I had both of them marked as source root. When I renamed one of the "thing"
folders to "thing1"
(any unique name), it worked.
Maybe if PyCharm automatically adds selected source roots, it doesn't use the full path and hence mixes up folders with the same name.