In Xcode 4.2.1, open Organizer, then go to Library/Device Logs and drag your .crash file into the list of crash logs. It will be symbolicated for you after a few seconds.
Note that you must use the same instance of Xcode that the original build was archived on (i.e. the archive for your build must exist in Organizer).
Please note that String.format(format, args...)
is locale-dependent because it formats using the user's default locale, that is, probably with commas and even spaces inside like 123 456,789 or 123,456.789, which may be not exactly what you expect.
You may prefer to use String.format((Locale)null, format, args...)
.
For example,
double f = 123456.789d;
System.out.println(String.format(Locale.FRANCE,"%f",f));
System.out.println(String.format(Locale.GERMANY,"%f",f));
System.out.println(String.format(Locale.US,"%f",f));
prints
123456,789000
123456,789000
123456.789000
and this is what will String.format(format, args...)
do in different countries.
EDIT Ok, since there has been a discussion about formalities:
res += stripFpZeroes(String.format((Locale) null, (nDigits!=0 ? "%."+nDigits+"f" : "%f"), value));
...
protected static String stripFpZeroes(String fpnumber) {
int n = fpnumber.indexOf('.');
if (n == -1) {
return fpnumber;
}
if (n < 2) {
n = 2;
}
String s = fpnumber;
while (s.length() > n && s.endsWith("0")) {
s = s.substring(0, s.length()-1);
}
return s;
}
With ES6 the most performant way would be to use a Map.
var myMap = new Map();
myMap.set(1, 'myVal');
myMap.set(2, { catName: 'Meow', age: 3 });
myMap.get(1);
myMap.get(2);
You can use ES6 features today using a shim (https://github.com/es-shims/es6-shim).
Performance will vary depending on the browser and scenario. But here is one example where Map
is most performant: https://jsperf.com/es6-map-vs-object-properties/2
REFERENCE https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
Depending on the situation, it is often helpful to make the image a background image of a div
with CSS.
<div id='my-image'></div>
Then in CSS:
#my-image {
background-image: url('/img/foo.png');
width: ???px;
height: ???px;
}
See this JSFiddle for a live example with a button and a different sizing option.
The javascript has
var canvasW = 640;
var canvasH = 480;
in it. Try changing those as well as the css for the canvas.
Or better yet, have the initialize function determine the size of the canvas from the css!
in response to your edits, change your init function:
function init()
{
canvas = document.getElementById("mainCanvas");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
canvasW = canvas.width;
canvasH = canvas.height;
if( canvas.getContext )
{
setup();
setInterval( run , 33 );
}
}
Also remove all the css from the wrappers, that just junks stuff up. You have to edit the js to get rid of them completely though... I was able to get it full screen though.
html, body {
overflow: hidden;
}
Edit: document.width
and document.height
are obsolete. Replace with document.body.clientWidth
and document.body.clientHeight
Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event()
and data pointers to a framework function watch_events()
(for example). When an event happens, your function is called with your data and some event-specific data.
Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.
Click Run
Click Debug ...
New Java Application
Click Arguments tab
in the 2nd box (VM Arguments) add the -D entry
-Xdebug -verbose:gc -Xbootclasspath/p:jar/vbjorb.jar;jar/oracle9.jar;classes;jar/mq.jar;jar/xml4j.jar -classpath -DORBInitRef=NameService=iioploc://10.101.2.94:8092/NameService
etc...
"MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format." This is from mysql site. You can store only this type, but you can use one of the many time format functions to change it, when you need to display it.
For example, one of those functions is the DATE_FORMAT, which can be used like so:
SELECT DATE_FORMAT(column_name, '%m/%d/%Y %H:%i') FROM tablename
I've been frustrated for long by Windows code page issues, and the C programs portability and localisation issues they cause. The previous posts have detailed the issues at length, so I'm not going to add anything in this respect.
To make a long story short, eventually I ended up writing my own UTF-8 compatibility library layer over the Visual C++ standard C library. Basically this library ensures that a standard C program works right, in any code page, using UTF-8 internally.
This library, called MsvcLibX, is available as open source at https://github.com/JFLarvoire/SysToolsLib. Main features:
More details in the MsvcLibX README on GitHub, including how to build the library and use it in your own programs.
The release section in the above GitHub repository provides several programs using this MsvcLibX library, that will show its capabilities. Ex: Try my which.exe tool with directories with non-ASCII names in the PATH, searching for programs with non-ASCII names, and changing code pages.
Another useful tool there is the conv.exe program. This program can easily convert a data stream from any code page to any other. Its default is input in the Windows code page, and output in the current console code page. This allows to correctly view data generated by Windows GUI apps (ex: Notepad) in a command console, with a simple command like: type WINFILE.txt | conv
This MsvcLibX library is by no means complete, and contributions for improving it are welcome!
Following on from answer's by bstoney and Snark I did some tests on the various methods:
// Test 1 (array_merge)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
$array1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);
// Test2 (foreach)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
foreach ($array2 as $v) {
$array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);
// Test 3 (... token)
// PHP 5.6+ and produces error if $array2 is empty
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
array_push($array1, ...$array2);
echo sprintf("Test 3: %.06f\n", microtime(true) - $start);
Which produces:
Test 1: 0.002717
Test 2: 0.006922
Test 3: 0.004744
ORIGINAL: I believe as of PHP 7, method 3 is a significantly better alternative due to the way foreach loops now act, which is to make a copy of the array being iterated over.
Whilst method 3 isn't strictly an answer to the criteria of 'not array_push' in the question, it is one line and the most high performance in all respects, I think the question was asked before the ... syntax was an option.
UPDATE 25/03/2020: I've updated the test which was flawed as the variables weren't reset. Interestingly (or confusingly) the results now show as test 1 being the fastest, where it was the slowest, having gone from 0.008392 to 0.002717! This can only be down to PHP updates, as this wouldn't have been affected by the testing flaw.
So, the saga continues, I will start using array_merge from now on!
Why not just using
<div [ngClass]="classes"> </div>
https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
First you need to download JQuery library from http://jquery.com/ then load the jquery library the following way within your html head tags
then you can test whether the jquery is working by coding your jquery code after the jquery loading script
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--LINK JQUERY-->
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<!--PERSONAL SCRIPT JavaScript-->
<script type="text/javascript">
$(function(){
alert("My First Jquery Test");
});
</script>
</head>
<body><!-- Your web--></body>
</html>
If you want to use your jquery scripts file seperately you must define the external .js file this way after the jquery library loading.
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script src="js/YourExternalJQueryScripts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
_x000D_
<!--LINK JQUERY-->_x000D_
<script type="text/javascript" src="jquery-3.3.1.js"></script>_x000D_
<!--PERSONAL SCRIPT JavaScript-->_x000D_
<script type="text/javascript">_x000D_
$(function(){_x000D_
alert("My First Jquery Test");_x000D_
});_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body><!-- Your web--></body>_x000D_
</html>
_x000D_
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
You can use XMLGrid's Online viewer which provides a great XSD support and many other features:
Screenshot:
You don't "commit the folder" - you add the folder, as you have done, and then simply commit all changes. The command should be:
git add foldername
git commit -m "commit operation"
polygenelubricants answer is almost perfect. It has one important bug though. It will not handle map entries where the values are the same.
This code:...
Map<String, Integer> nonSortedMap = new HashMap<String, Integer>();
nonSortedMap.put("ape", 1);
nonSortedMap.put("pig", 3);
nonSortedMap.put("cow", 1);
nonSortedMap.put("frog", 2);
for (Entry<String, Integer> entry : entriesSortedByValues(nonSortedMap)) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
Would output:
ape:1
frog:2
pig:3
Note how our cow dissapeared as it shared the value "1" with our ape :O!
This modification of the code solves that issue:
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1; // Special fix to preserve items with equal values
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
Well I am bit late to answer,but my code is tested
check scheme from uri:
byte[] videoBytes;
if (uri.getScheme().equals("content")){
InputStream iStream = context.getContentResolver().openInputStream(uri);
videoBytes = getBytes(iStream);
}else{
File file = new File(uri.getPath());
FileInputStream fileInputStream = new FileInputStream(file);
videoBytes = getBytes(fileInputStream);
}
In the above answer I converted the video uri to bytes array , but that's not related to question,
I just copied my full code to show the usage of FileInputStream
and InputStream
as both are working same in my code.
I used the variable context which is getActivity() in my Fragment and in Activity it simply be ActivityName.this
context=getActivity();
//in Fragment
context=ActivityName.this;
// in activity
May be this can help you- Add the system variable _JAVA_OPTIONS and in the "new variable value" add "-Xmx1024M" Xmx sets the maximum heap memory size
^CTR.*$
matches a line starting with CTR
.
Adding to Andy's answer, there is additional utility to git rm
:
Safety: When doing git rm
instead of rm
, Git will block the removal if there is a discrepancy between the HEAD
version of a file and the staging index or working tree version. This block is a safety mechanism to prevent removal of in-progress changes.
Safeguarding: git rm --dry-run
. This option is a safeguard that will execute the git rm
command but not actually delete the files. Instead it will output which files it would have removed.
Alternatively to Link Library Dependencies
in project properties there is another way to link libraries in Visual Studio.
Add Existing Item...
).Item Type
is Library
This will include the other libraries in X as if you ran
lib /out:X.lib X.lib other1.lib other2.lib
using a switch case
switch ($num){
case ($num>= $value1 && $num<= $value2):
echo "within range 1";
break;
case ($num>= $value3 && $num<= $value4):
echo "within range 2";
break;
.
.
.
.
.
default: //default
echo "within no range";
break;
}
You can use:
sdiff file1 file2
or
diff -y file1 file2
or
vimdiff file1 file2
for side by side display.
$('html').keyup(function(e){
if(e.keyCode == 46) {
alert('Delete key released');
}
});
Source: javascript char codes key codes from www.cambiaresearch.com
Remember, when you return more than one item, you're really returning a tuple. So you can do things like this:
def func():
return 1, 2
print func()[0] # prints 1
print func()[1] # prints 2
uuid-ossp
is a contrib module, so it isn't loaded into the server by default. You must load it into your database to use it.
For modern PostgreSQL versions (9.1 and newer) that's easy:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
but for 9.0 and below you must instead run the SQL script to load the extension. See the documentation for contrib modules in 8.4.
For Pg 9.1 and newer instead read the current contrib docs and CREATE EXTENSION
. These features do not exist in 9.0 or older versions, like your 8.4.
If you're using a packaged version of PostgreSQL you might need to install a separate package containing the contrib modules and extensions. Search your package manager database for 'postgres' and 'contrib'.
Suppose you have a timedelta series:
import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})
td_series = (z['a'] - z['b'])
One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:
td_series.astype(pd.Timedelta).apply(lambda l: l.days)
Another way is to cast the series as a timedelta64 in days, and then cast it as an int:
td_series.astype('timedelta64[D]').astype(int)
An alternative is to use the CountDownLatch class.
public class DatabaseTest {
/**
* Data limit
*/
private static final int DATA_LIMIT = 5;
/**
* Countdown latch
*/
private CountDownLatch lock = new CountDownLatch(1);
/**
* Received data
*/
private List<Data> receiveddata;
@Test
public void testDataRetrieval() throws Exception {
Database db = new MockDatabaseImpl();
db.getData(DATA_LIMIT, new DataCallback() {
@Override
public void onSuccess(List<Data> data) {
receiveddata = data;
lock.countDown();
}
});
lock.await(2000, TimeUnit.MILLISECONDS);
assertNotNull(receiveddata);
assertEquals(DATA_LIMIT, receiveddata.size());
}
}
NOTE you can't just used syncronized with a regular object as a lock, as fast callbacks can release the lock before the lock's wait method is called. See this blog post by Joe Walnes.
EDIT Removed syncronized blocks around CountDownLatch thanks to comments from @jtahlborn and @Ring
If your using ASP.Net 5 (now known as ASP.Net Core v1) ensure in your project.json "commands" section for each site you are hosting that the Kestrel proxy listening port differs between sites, otherwise one site will work but the other will return a 504 gateway timeout.
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5090"
},
You can try/catch PDOException
s (your configs could differ but the important part is the try/catch):
try {
$dbh = new PDO(
DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
DB_USER,
DB_PASS,
[
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE
]
);
} catch ( PDOException $e ) {
echo 'ERROR!';
print_r( $e );
}
The print_r( $e );
line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'
.
You import the function from outside the main instance, and don't add it to the methods block. so the context of this
is not the vm.
Either do this:
ready() {
checkAuth.call(this)
}
or add the method to your methods first (which will make Vue bind this
correctly for you) and call this method:
methods: {
checkAuth: checkAuth
},
ready() {
this.checkAuth()
}
Put all the 6 classes to 6 different projects. Then create jar files of all the 6 projects. In this manner you will get 6 executable jar files.
After hours of analysis reading tons of logs and sourcecode, finally found problem. And it is quite easy to solve it.
in sinle line: you need to pass --whitelisted-ips= into chrome driver (not chrome!) executables
You can do it in few ways:
If you use ChromeDriver locally/directly from code, just insert lines below before ChromeDriver init
System.setProperty("webdriver.chrome.whitelistedIps", "");
If you use it remotely (eg. selenium hub/grid) you need to set system property when node starts, like in command:
java -Dwebdriver.chrome.whitelistedIps= testClass etc...
or docker by passing JAVA_OPTS
env
chrome:
image: selenium/node-chrome:3.141.59
container_name: chrome
depends_on:
- selenium-hub
environment:
- HUB_HOST=selenium-hub
- HUB_PORT=4444
- JAVA_OPTS=-Dwebdriver.chrome.whitelistedIps=
I figured it out from the PostgreSQL docs, the exact syntax is:
ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
Thanks Fred.
I use the following to determine if the string is ascii or unicode:
>> print 'test string'.__class__.__name__
str
>>> print u'test string'.__class__.__name__
unicode
>>>
Then just use a conditional block to define the function:
def is_ascii(input):
if input.__class__.__name__ == "str":
return True
return False
This is another option
$ read test < <(echo hello world)
$ echo $test
hello world
I was struggling a lot with different solutions including \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:
You can change the margins of just one or more pages and then restore it to its default:
\usepackage{geometry}
...
...
...
\newgeometry{top=5mm, bottom=10mm} % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...
\restoregeometry %so it does not affect the rest of the pages.
...
...
...
PS:
1- This can also fix the following warning:
LaTeX Warning: Float too large for page by ...pt on input line ...
2- For more detailed answer look at this.
3- I just found that this is more elaboration on Kevin Chen's answer.
After digging a lot of stuff, finally, I came up with a good solution that doesn't hang the CI :) Suit it to your needs!
public static Task WaitUntil<T>(T elem, Func<T, bool> predicate, int seconds = 10)
{
var tcs = new TaskCompletionSource<int>();
using(var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(seconds)))
{
cancellationTokenSource.Token.Register(() =>
{
tcs.SetException(
new TimeoutException($"Waiting predicate {predicate} for {elem.GetType()} timed out!"));
tcs.TrySetCanceled();
});
while(!cancellationTokenSource.IsCancellationRequested)
{
try
{
if (!predicate(elem))
{
continue;
}
}
catch(Exception e)
{
tcs.TrySetException(e);
}
tcs.SetResult(0);
break;
}
return tcs.Task;
}
}
Simply call:
btnTest_Click(null, null);
Just make sure you aren't trying to use either of those params in the function.
Edit 18 Nov 2016
This code also work (for those who prefer another solution , without using ActiveX)
var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
// true on IE11
// false on Edge and other IEs/browsers.
Original Answer
In order to check Ie11 , you can use this : ( tested)
(or run this)
!(window.ActiveXObject) && "ActiveXObject" in window
I have all VMS of IE :
Notice : this wont work for IE11 :
as you can see here , it returns true :
So what can we do :
Apparently , they added the machine bit space :
ie11 :
"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"
ie12 :
"Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"
so we can do:
/x64|x32/ig.test(window.navigator.userAgent)
this will return true only for ie11.
For existing project end existing repository with files:
git init
git remote add origin <.git>
git checkout -b master
git branch --set-upstream-to=origin/master master
git pull --allow-unrelated-histories
The following is a complete solution, including how to deal with some pitfalls.
### ********************
## init python (version 2.7.2 )
import urllib
### ********************
## first setup a dictionary of name-value pairs
dict_name_value_pairs = {
"bravo" : "True != False",
"alpha" : "http://www.example.com",
"charlie" : "hello world",
"delta" : "1234567 !@#$%^&*",
"echo" : "[email protected]",
}
### ********************
## setup an exact ordering for the name-value pairs
ary_ordered_names = []
ary_ordered_names.append('alpha')
ary_ordered_names.append('bravo')
ary_ordered_names.append('charlie')
ary_ordered_names.append('delta')
ary_ordered_names.append('echo')
### ********************
## show the output results
if('NO we DO NOT care about the ordering of name-value pairs'):
queryString = urllib.urlencode(dict_name_value_pairs)
print queryString
"""
echo=user%40example.com&bravo=True+%21%3D+False&delta=1234567+%21%40%23%24%25%5E%26%2A&charlie=hello+world&alpha=http%3A%2F%2Fwww.example.com
"""
if('YES we DO care about the ordering of name-value pairs'):
queryString = "&".join( [ item+'='+urllib.quote_plus(dict_name_value_pairs[item]) for item in ary_ordered_names ] )
print queryString
"""
alpha=http%3A%2F%2Fwww.example.com&bravo=True+%21%3D+False&charlie=hello+world&delta=1234567+%21%40%23%24%25%5E%26%2A&echo=user%40example.com
"""
Your placeholder is replaced by a string and you're not handling it right.
Replace
"name LIKE '%?%' OR postal_code LIKE '%?%'", search, search
with
"name LIKE ? OR postal_code LIKE ?", "%#{search}%", "%#{search}%"
As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.
The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.
s = requests.session()
s.config['keep_alive'] = False
Actually, the solution provided before is not working. It doesn't work if you want to enter 100.00.
Replace:
double parsed = Double.parseDouble(cleanString);
String formato = NumberFormat.getCurrencyInstance().format((parsed/100));
With:
BigDecimal parsed = new BigDecimal(cleanString).setScale(2,BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100),BigDecimal.ROUND_FLOOR);
String formato = NumberFormat.getCurrencyInstance().format(parsed);
I must say that I made some modifications for my code. The thing is that you should be using BigDecimal's
from jquery api
Added to jQuery in version 1.4, the .delay()
method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show()
or .hide()
which do not use the effects queue.
There are few more classess in Bootstrap 4 (added in recent versions) not mentioned in other answers.
.text-black-50
and .text-white-50
are 50% transparent.
.text-body {_x000D_
color: #212529 !important;_x000D_
}_x000D_
_x000D_
.text-black-50 {_x000D_
color: rgba(0, 0, 0, 0.5) !important;_x000D_
}_x000D_
_x000D_
.text-white-50 {_x000D_
color: rgba(255, 255, 255, 0.5) !important;_x000D_
}_x000D_
_x000D_
/*DEMO*/_x000D_
p{padding:.5rem}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
_x000D_
<p class="text-body">.text-body</p>_x000D_
<p class="text-black-50">.text-black-50</p>_x000D_
<p class="text-white-50 bg-dark">.text-white-50</p>
_x000D_
The solution is quite simple, it is all a matter of how you define things on the server / workstation in relation to your visual studio project.
First check the version of the Oracle library that you are using, in your case 2.111.7.20. Next go to the Windows GAC located in your windows home->assembly folder.
Scroll down to the Oracle dll, it is normally called Oracle.DataAccess or Oracle.Web. Find the right version of it and note down if it says x86 or AMD64.
In visual studio ensure that your target platform is the same as the dll in the GAC, so if it says x86 in the GAC folder ensure that the target platform is x64 and other x64. You can set this in Visual Studio project properties, under build/platform target.
Also ensure that your reference, under references in your project points to this exact same version on your development computer.
With this everything should work fine.
What I normally do is to check the server first as it is often easier in an enterprise environment to change the version of your local dependencies, then to ask a server administrator to do an installation of a different dll.
This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.
On the other hand, SQL Server would let you do what you are trying to achieve.
There are 2 workarounds here:
Both are, of course, stupid workarounds :)
In response to Mike B, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:
template <class IntegerType>
class smart_integer {
public:
typedef integer_traits<Integer> traits;
IntegerType operator+=(IntegerType value){
typedef typename traits::larger_integer_t larger_t;
larger_t interm = larger_t(myValue) + larger_t(value);
if(interm > traits::max() || interm < traits::min())
throw overflow();
myValue = IntegerType(interm);
}
}
larger_integer_t
is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that larger_integer_t
is a type. class, on the otherhand, has no such overloaded meaning.
That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.
I also suggest using contourf(Z)
. For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.
So in my case, I prefer to use jucestain's answer. The default shading faceted
of pcolor()
is more suitable.
However, pcolor()
does not use the last row and column of the plotted matrix. For this, I used the padarray()
function:
pcolor(padarray(Z,[1 1],0,'post'))
Sorry if that is not really related to the original post
To solve the problem of not being able to start mongodb on ubuntu 16.04 1) look at mongodb log file
2) we find that the error is due to "Failed to unlink socket file /tmp/mongodb-27017"
3) Look at the permission of file /tmp/mongdb-27017.lock and find that the owner is root instead of mongodb
4) Delete the /tmp/mongodb-27017.sock file manually and use the command "sudo chown mongodb:mongodb /tmp/mongodb*"
5) Start the service with systemcl and use netstat to check whther mongdob has been started on port 27017
Credit: https://www.mkyong.com/mongodb/mongodb-failed-to-unlink-socket-file-tmpmongodb-27017/ https://hevodata.com/blog/install-mongodb-on-ubuntu/
require
loads a file from the $LOAD_PATH
. If you want to require a file relative to the currently executing file instead of from the $LOAD_PATH
, use require_relative
.
I've been searching for a way to save notebooks as html, since whenever I try to download as html with my new Jupyter installation, I always get a 500 : Internal Server Error The error was: nbconvert failed: validate() got an unexpected keyword argument 'relax_add_props'
error. Oddly enough, I've found that downloading as html is as simple as:
No print preview, no print, no nbconvert. Using Jupyter Version: 1.0.0
. Just a suggestion to try (obviously not all setups are the same).
The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.
I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.
Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin
appears).
const {Builder, By, Key, util} = require('selenium-webdriver')
// FUNÇÃO PARA PAUSA
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function example() {
// chrome
let driver = await new Builder().forBrowser("firefox").build()
await driver.get('https://www.google.com.br')
// await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)
await sleep(2000)
await driver.findElement(By.name('q')).sendKeys('Selenium')
await sleep(2000)
// CLICAR
driver.findElement(By.name('btnK')).click()
}
example()
Com essas últimas linhas, você pode clicar !
Javascript is duck typed, so you can create a small structure.
function myFunction(value1,value2,value3)
{
var myObject = new Object();
myObject.value2 = somevalue2;
myObject.value3 = somevalue3;
return myObject;
}
var value = myFunction("1",value2,value3);
if(value.value2 && value.value3)
{
//Do some stuff
}
.outerdiv {
margin-left: auto;
margin-right: auto;
display: table;
}
Doesn't work in internet explorer 7... but who cares ?
Using FA 4.4.0 adding
.text-danger
color: #d9534f
to the document css and then using
<i class="fa fa-ban text-danger"></i>
changes the color to red. You can set your own for any color.
You can also dump elasticsearch data in JSON format by http request:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html
CURL -XPOST 'https://ES/INDEX/_search?scroll=10m'
CURL -XPOST 'https://ES/_search/scroll' -d '{"scroll": "10m", "scroll_id": "ID"}'
you can use
parent.style.setProperty("--padding-top", (height*100/width).toFixed(2)+"%");
in css
el:after{
....
padding-top:var(--padding-top, 0px);
}
With an example of the not-working code, it will be easy to answer this question, but with this information the best that I can think is that you are calling the $location.path outside of the AngularJS digest.
Try doing this on the directive scope.$apply(function() { $location.path("/route"); });
HTML
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
You could use the XPATH as :
//div[@id='a']//a[@class='click']
output
<a class="click">abc</a>
That said your Python code should be as :
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
There is a conflict between Visual Studio 2015 and Visual Studio Code for the git credentials. When i changed my credentials on VS 2015 VS Code let me push with the correct git ID.
Per batch, 65536 * Network Packet Size which is 4k so 256 MB
However, IN will stop way before that but it's not precise.
You end up with memory errors but I can't recall the exact error. A huge IN will be inefficient anyway.
Edit: Remus reminded me: the error is about "stack size"
Your constructor's access modifier would be package-private(default). As you have declared the class public, it will be visible everywhere, but the constructor will not. Your constructor will be visible only in its package.
package flight.booking;
public class FlightLog // Public access modifier
{
private SpecificFlight flight;
FlightLog(SpecificFlight flight) // Default access modifier
{
this.flight = flight;
}
}
When you do not write any constructor in your class then the compiler generates a default constructor with the same access modifier of the class. For the following example, the compiler will generate a default constructor with the public access modifier (same as class).
package flight.booking;
public class FlightLog // Public access modifier
{
private SpecificFlight flight;
}
As opposed to the time per unit of work (speed/latency).
This question in network engineering stack exchange contains good responses: https://networkengineering.stackexchange.com/questions/10504/what-is-the-difference-between-data-rate-and-latency
Here is the best method that I've found: First, set your projects output type to "Windows Application", then P/Invoke AllocConsole to create a console window.
internal static class NativeMethods
{
[DllImport("kernel32.dll")]
internal static extern Boolean AllocConsole();
}
static class Program
{
static void Main(string[] args) {
if (args.Length == 0) {
// run as windows app
Application.EnableVisualStyles();
Application.Run(new Form1());
} else {
// run as console app
NativeMethods.AllocConsole();
Console.WriteLine("Hello World");
Console.ReadLine();
}
}
}
First, using a page-file when you have 4 GB of RAM is useless. Windows can't access more than 4GB (actually, less because of memory holes) so the page file is not used.
Second, the address space is split in 2, half for kernel, half for user mode. If you need more RAM for your applications use the /3GB option in boot.ini (make sure java.exe is marked as "large address aware" (google for more info).
Third, I think you can't allocate the full 2 GB of address space because java wastes some memory internally (for threads, JIT compiler, VM initialization, etc). Use the /3GB switch for more.
For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.
Based on some answers I found here, I made myself a small helper file to source for my projects:
#!/bin/bash
function try()
{
[[ $- = *e* ]]; SAVED_OPT_E=$?
set +e
}
function throw()
{
exit $1
}
function catch()
{
export ex_code=$?
(( $SAVED_OPT_E )) && set +e
return $ex_code
}
function throwErrors()
{
set -e
}
function ignoreErrors()
{
set +e
}
here is an example how it looks like in use:
#!/bin/bash
export AnException=100
export AnotherException=101
# start with a try
try
( # open a subshell !!!
echo "do something"
[ someErrorCondition ] && throw $AnException
echo "do something more"
executeCommandThatMightFail || throw $AnotherException
throwErrors # automaticatly end the try block, if command-result is non-null
echo "now on to something completely different"
executeCommandThatMightFail
echo "it's a wonder we came so far"
executeCommandThatFailsForSure || true # ignore a single failing command
ignoreErrors # ignore failures of commands until further notice
executeCommand1ThatFailsForSure
local result = $(executeCommand2ThatFailsForSure)
[ result != "expected error" ] && throw $AnException # ok, if it's not an expected error, we want to bail out!
executeCommand3ThatFailsForSure
echo "finished"
)
# directly after closing the subshell you need to connect a group to the catch using ||
catch || {
# now you can handle
case $ex_code in
$AnException)
echo "AnException was thrown"
;;
$AnotherException)
echo "AnotherException was thrown"
;;
*)
echo "An unexpected exception was thrown"
throw $ex_code # you can rethrow the "exception" causing the script to exit if not caught
;;
esac
}
I've never done it, but it looks like Reflection provides this. Field
is an AnnotatedElement
and so it has getAnnotation
. This page has an example (copied below); quite straightforward if you know the class of the annotation and if the annotation policy retains the annotation at runtime. Naturally if the retention policy doesn't keep the annotation at runtime, you won't be able to query it at runtime.
An answer that's since been deleted (?) provided a useful link to an annotations tutorial that you may find helpful; I've copied the link here so people can use it.
Example from this page:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
class Meta {
@MyAnno(str = "Two Parameters", val = 19)
public static void myMeth(String str, int i) {
Meta ob = new Meta();
try {
Class c = ob.getClass();
Method m = c.getMethod("myMeth", String.class, int.class);
MyAnno anno = m.getAnnotation(MyAnno.class);
System.out.println(anno.str() + " " + anno.val());
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth("test", 10);
}
}
Though the earlier answers are correct, there's a small complication it would help to remark on.
In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:
if __name__ == '__main__':
import my_module
There is at least one situation where using single quotes will not work and that is if you are creating the markup "on the fly" from JavaScript. You use single quotes to contain the string and then any property in the markup can have double quotes for its value.
Inline content leaves space at the bottom for characters that descend (j, y, q):
https://developer.mozilla.org/en-US/docs/Images,_Tables,_and_Mysterious_Gaps
There are a couple fixes:
Use display: block;
<img style="display:block;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
or use vertical-align: bottom;
<img style="vertical-align: bottom;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
FYI, from November 2018 anyone who wants access Twitter’s APIs must apply for a Twitter Development Account by visiting https://developer.twitter.com/. Once your application has been approved then only you'll be able to create Twitter apps.
Once the Twitter Developer Account is ready:
1) Go to https://developer.twitter.com/.
2) Click on Apps and then click on Create an app.
3) Provide an App Name & Description.
4) Enter a website name in the Website URL field.
5) Click on Create.
6) Navigate to your app, then click on Details and then go to Keys and Tokens.
Reference: http://www.technocratsid.com/getting-twitter-consumer-api-access-token-keys/
This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.
anaconda
. Latest version can be found hereanaconda-navigator
in terminalcreate
and then choose your python version in that. install
in that. Hope it helps!!
Now there is already no need to use JSON.stringify
explicitly. Just execute this line of code
$.cookie.json = true;
After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.
var user = { name: "name", age: 25 }
$.cookie('user', user);
...
var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);
But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js
I'd like to add complementary information: In postman app you may use the "request" object to see your subsituted input data. (refer to https://www.getpostman.com/docs/postman/scripts/postman_sandbox in paragraph "Request/response related properties", ie.
console.log("header : " + request.headers["Content-Type"]);
console.log("body : " + request.data);
console.log("url : " + request.url);
I didn't test for header substitution but it works for url and body.
Alex
System.Diagnostics.Stopwatch is designed for this task.
You can do:
if not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do sth. # condition is satisfied
Using a loop:
while not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied
Get COLUMN INDEX on click:
$(this).closest("td").index();
Get ROW INDEX on click:
$(this).closest("tr").index();
Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.
When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)
Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.
Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.
AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)
To include native libraries you need:
To create jar file, use the following snippet:
task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
destinationDir file("$buildDir/native-libs")
baseName 'native-libs'
extension 'jar'
from fileTree(dir: 'libs', include: '**/*.so')
into 'lib/'
}
tasks.withType(Compile) {
compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:
compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
Correct attribute value for Asp.Net MVC Core to prevent browser caching (including Internet Explorer 11) is:
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
as described in Microsoft documentation:
Response caching in ASP.NET Core - NoStore and Location.None
I just wanted to post a demo using calc() for setting rows/height, since no one did.
body {_x000D_
/* page default */_x000D_
font-size: 15px;_x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
/* demo related */_x000D_
width: 300px;_x000D_
margin-bottom: 1em;_x000D_
display: block;_x000D_
_x000D_
/* rows related */_x000D_
font-size: inherit;_x000D_
line-height: inherit;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows); */_x000D_
height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.
The solution (http://expressjs.com/en/starter/static-files.html).
once done this the image folder no longer shalt put it. only be
background-image: url ( "/ image.png");
carpera that the image is already in the static files
var arr = new Array();
$('li').each(function() {
arr.push(this.innerHTML);
})
You can use str.isalpha()
.
For example:
s = 'a123b'
for char in s:
print(char, char.isalpha())
Output:
a True
1 False
2 False
3 False
b True
CSS3 flexbox can also be used to align button at the bottom of parent element.
Required HTML:
<div class="container">
<div class="btn-holder">
<button type="button">Click</button>
</div>
</div>
Necessary CSS:
.container {
justify-content: space-between;
flex-direction: column;
height: 100vh;
display: flex;
}
.container .btn-holder {
justify-content: flex-end;
display: flex;
}
Screenshot:
Useful Resources:
* {box-sizing: border-box;}_x000D_
body {_x000D_
background: linear-gradient(orange, yellow);_x000D_
font: 14px/18px Arial, sans-serif;_x000D_
margin: 0;_x000D_
}_x000D_
.container {_x000D_
justify-content: space-between;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
display: flex;_x000D_
padding: 10px;_x000D_
}_x000D_
.container .btn-holder {_x000D_
justify-content: flex-end;_x000D_
display: flex;_x000D_
}_x000D_
.container .btn-holder button {_x000D_
padding: 10px 25px;_x000D_
background: blue;_x000D_
font-size: 16px;_x000D_
border: none;_x000D_
color: #fff;_x000D_
}
_x000D_
<div class="container">_x000D_
<p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>_x000D_
<div class="btn-holder">_x000D_
<button type="button">Click</button>_x000D_
</div>_x000D_
</div>
_x000D_
I had to specify individual commands first and then use the *
to bring all in command.
from tkinter import filedialog
from tkinter import *
If you want to do this in PHP:
// replace time() with the time stamp you want to add one day to
$startDate = time();
date('Y-m-d H:i:s', strtotime('+1 day', $startDate));
If you want to add the date in MySQL:
-- replace CURRENT_DATE with the date you want to add one day to
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY);
With an OR
(||) operation, if any one of the conditions are true, the result is true.
I think you want an AND
(&&) operation here.
Check for spaces in your formula before the "=". example' =A1' instean '=A1'
A = zeros(20, 10, 3); %# Creates a 20x10x3 matrix
B = zeros(4,4);
C = zeros(size(B,1), size(B,2), 4); %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B; %# Copy the content of B into C's first set of values
zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0
for a 3D matrix. To confirm the size of your matrices you can run: size(A)
which gives 20 10 3
.
There is no explicit bound on the number of dimensions a matrix may have.
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
What you need is:
if (!File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
}
or
if (File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Delete(@"c:\test\Test\SomeFile.txt");
}
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
This will either:
Edit: I should clarify my answer, even though it's the most upvoted!
The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires.
So, your second parameter should be c:\test\Test\SomeFile.txt
.
to set session you can try this:
$request->session()->put('key','value');
also to get session data you can try this:
$request->session()->get('key');
If you want to get all session data:
$request->session()->all();
Alternative could be
to make your response look like
myCustom_JSONResponse
{"master":[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
}
instead of
server_JSONResponse
[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
CODE
String server_JSONResponse =.... // the string in which you are getting your JSON Response after hitting URL
String myCustom_JSONResponse="";// in which we will keep our response after adding object element to it
MyClass apiResponse = new MyClass();
myCustom_JSONResponse="{\"master\":"+server_JSONResponse+"}";
apiResponse = gson.fromJson(myCustom_JSONResponse, MyClass .class);
After this it will be just any other GSON Parsing
@Test
public void testSearchManagementStaff() throws SQLException
{
boolean res=true;
ManagementDaoImp mdi=new ManagementDaoImp();
boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
assertEquals(res,b);
}
I also faced this same issue, I got a solution with this.
I did the following steps :
close your current cmd, and restart it run flutter doctor
this should work on windows
You can do that in some methods:
One is the type
command: type filename
Another is the more
command: more filename
With more
you can also do that: type filename | more
The last option is using a for
for /f "usebackq delims=" %%A in (filename) do (echo.%%A)
This will go for each line and display it's content. This is an equivalent of the type
command, but it's another method of reading the content.
If you are asking what to use, use the more
command as it will make a pause.
Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.
In contrast, JSTL works entirely with scoped attributes, either at page
, request
or session
scope. You need to rework your scriptlet to fish test
out as an attribute:
<c:set var="test" value="test1"/>
<%
String resp = "abc";
String test = pageContext.getAttribute("test");
resp = resp + test;
pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>
If you look at the docs for <c:set>
, you'll see you can specify scope
as page
, request
or session
, and it defaults to page
.
Better yet, don't use scriptlets at all: they make the baby jesus cry.
Your regular expression [^a-zA-Z0-9]\s/g
says match any character that is not a number or letter followed by a space.
Remove the \s and you should get what you are after if you want a _ for every special character.
var newString = str.replace(/[^A-Z0-9]/ig, "_");
That will result in hello_world___hello_universe
If you want it to be single underscores use a + to match multiple
var newString = str.replace(/[^A-Z0-9]+/ig, "_");
That will result in hello_world_hello_universe
Define a converter:
public class RowIndexConverter : IValueConverter
{
public object Convert( object value, Type targetType,
object parameter, CultureInfo culture )
{
var row = (IDictionary<string, object>) value;
var key = (string) parameter;
return row.Keys.Contains( key ) ? row[ key ] : null;
}
public object ConvertBack( object value, Type targetType,
object parameter, CultureInfo culture )
{
throw new NotImplementedException( );
}
}
Bind to a custom definition of a Dictionary. There's lot of overrides that I've omitted, but the indexer is the important one, because it emits the property changed event when the value is changed. This is required for source to target binding.
public class BindableRow : INotifyPropertyChanged, IDictionary<string, object>
{
private Dictionary<string, object> _data = new Dictionary<string, object>( );
public object Dummy // Provides a dummy property for the column to bind to
{
get
{
return this;
}
set
{
var o = value;
}
}
public object this[ string index ]
{
get
{
return _data[ index ];
}
set
{
_data[ index ] = value;
InvokePropertyChanged( new PropertyChangedEventArgs( "Dummy" ) ); // Trigger update
}
}
}
In your .xaml file use this converter. First reference it:
<UserControl.Resources>
<ViewModelHelpers:RowIndexConverter x:Key="RowIndexConverter"/>
</UserControl.Resources>
Then, for instance, if your dictionary has an entry where the key is "Name", then to bind to it: use
<TextBlock Text="{Binding Dummy, Converter={StaticResource RowIndexConverter}, ConverterParameter=Name}">
Just use simple code
<%
if(condition)
{%>
html code
<% }
else
{
%>
html code
<% } %>
hive> show partitions table_name;
If you have issues with JAR files not being found I would also ensure your CLASSPATH is set to include the location of those files. I do find however that the CLASSPATH often needs to be set differently for different programs and often ends up being something to set uniquely for individual programs.
Had the same issue and I 'Compiled VBA Project' which identified an error. After correction and compiling, the macros worked.
Adding this to your WebSecurityConfiguration class should do the trick.
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
}
With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.
import { Router } from 'react-router';
export default class Foo extends Component {
static get contextTypes() {
return {
router: React.PropTypes.object.isRequired,
};
}
handleClick() {
this.context.router.push('/some-path');
}
}
On Debian, using openjdk version "1.8.0_212", I found cacerts here:
/etc/ssl/certs/java/cacerts
Sure would be handy if there was a standard command that would print out this path.
If you are using python 3+ then try adding below lines
import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)
Bare bones, but confirmed working, example:
<script type="text/javascript">
var clicked;
function mysubmit() {
alert(clicked);
}
</script>
<form action="" onsubmit="mysubmit();return false">
<input type="submit" onclick="clicked='Save'" value="Save" />
<input type="submit" onclick="clicked='Add'" value="Add" />
</form>
Use substring
String strOut = "abcdefghijklmnopqrtuvwxyz"
String result = strOut.substring(0, 8) + "...";// count start in 0 and 8 is excluded
System.out.pritnln(result);
Note: substring(int first, int second) takes two parameters. The first is inclusive and the second is exclusive.
You should add an optional hyphen at the beginning by adding -?
(?
is a quantifier meaning one or zero occurrences):
^-?[0-9]\d*(\.\d+)?$
I verified it in Rubular with these values:
10.00
-10.00
and both matched as expected.
Java8 +
import java.time.Instant;
Instant.now().getEpochSecond(); //timestamp in seconds format (int)
Instant.now().toEpochMilli(); // timestamp in milliseconds format (long)
AFAIK, there is nothing built in for searching all columns. You can use Find
only against the primary key. Select
needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.
You can create file .gitignore and then Idea will suggest you install plugin
Assuming you have a JSON hash hanging around somewhere, to automatically convert it into something like WarHog's version, wrap your JSON hash contents in %q{hsh}
tags.
This seems to automatically add all the necessary escaped text like in WarHog's answer.
Check, you might have written this statement wrong.
public static void main(String Args[])
I have also just started java and was facing the same error and it was occuring as i didn't put []
after args.
so check ur statment.
if it is VBScript, it should be
WScript.Sleep 100
If it is JavaScript
WScript.Sleep(100);
Time in milliseconds. WScript.Sleep 1000 results in a 1 second sleep.
Just to take a subset of your questions:
This article on indexing addresses the question of the difference between []
and [[]]
.
In short [[]] selects a single item from a list and []
returns a list of the selected items. In your example, x = list(1, 2, 3, 4)'
item 1 is a single integer but x[[1]]
returns a single 1 and x[1]
returns a list with only one value.
> x = list(1, 2, 3, 4)
> x[1]
[[1]]
[1] 1
> x[[1]]
[1] 1
In your view:
{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}
In you controller functions add decorator:
from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):
To Achieve ellipses for the text use the Text property numberofLines={1} which will automatically truncate the text with an ellipsis you can specify the ellipsizeMode as "head", "middle", "tail" or "clip" By default it is tail
I tried to push to my own hosted bonobo-git server, and did not realise, that the http.postbuffer meant the project directory ...
so just for other confused ones:
why? In my case, I had large zip files with assets and some PSDs pushed as well - to big for the buffer I guess.
How to do this http.postbuffer: execute that command within your project src directory, next to the .git folder, not on the server.
be aware, large temp (chunk) files will be created of that buffer size.
Note: Just check your largest files, then set the buffer.
$('element').html('<h1>TEXT TO INSERT</h1>');
or
$('element').text('TEXT TO INSERT');
As @Daniel Kutik mentioned, presetdef
is a good option. Especially if one is working on a project with many build.xml
files which one cannot, or prefers not to, edit (e.g., those from third-parties.)
To use presetdef
, add these lines in your top-level build.xml
file:
<presetdef name="javac">
<javac includeantruntime="false" />
</presetdef>
Now all subsequent javac
tasks will essentially inherit includeantruntime="false"
. If your projects do actually need ant runtime libraries, you can either add them explicitly to your build files OR set includeantruntime="true"
. The latter will also get rid of warnings.
Subsequent javac
tasks can still explicitly change this if desired, for example:
<javac destdir="out" includeantruntime="true">
<src path="foo.java" />
<src path="bar.java" />
</javac>
I'd recommend against using ANT_OPTS
. It works, but it defeats the purpose of the warning. The warning tells one that one's build might behave differently on another system. Using ANT_OPTS
makes this even more likely because now every system needs to use ANT_OPTS
in the same way. Also, ANT_OPTS
will apply globally, suppressing warnings willy-nilly in all your projects
Here a more complete snippet that crops out the center of an [bitmap] of arbitrary dimensions and scales the result to your desired [IMAGE_SIZE]. So you will always get a [croppedBitmap] scaled square of the image center with a fixed size. ideal for thumbnailing and such.
Its a more complete combination of the other solutions.
final int IMAGE_SIZE = 255;
boolean landscape = bitmap.getWidth() > bitmap.getHeight();
float scale_factor;
if (landscape) scale_factor = (float)IMAGE_SIZE / bitmap.getHeight();
else scale_factor = (float)IMAGE_SIZE / bitmap.getWidth();
Matrix matrix = new Matrix();
matrix.postScale(scale_factor, scale_factor);
Bitmap croppedBitmap;
if (landscape){
int start = (tempBitmap.getWidth() - tempBitmap.getHeight()) / 2;
croppedBitmap = Bitmap.createBitmap(tempBitmap, start, 0, tempBitmap.getHeight(), tempBitmap.getHeight(), matrix, true);
} else {
int start = (tempBitmap.getHeight() - tempBitmap.getWidth()) / 2;
croppedBitmap = Bitmap.createBitmap(tempBitmap, 0, start, tempBitmap.getWidth(), tempBitmap.getWidth(), matrix, true);
}
sub selectVar ()
dim x,y as integer
let srange = "A" & x & ":" & "m" & y
range(srange).select
end sub
I think this is the simplest way.
This is working for me in Angular 7. It is based on the --main option of the ng command. I am not sure if this option is undocumented and possibly subject to change, but it works for me. I put a line in my package.json file in scripts section. There using the --main option of with the ng test command, I specify the path to the .spec.ts file I want to execute. For example
"test 1": "ng test --main E:/WebRxAngularClient/src/app/test/shared/my-date-utils.spec.ts",
You can run the script as you run any such script. I run it in Webstorm by clicking on "test 1" in the npm section.
A simple Stream extension method would do the job:
public static class StreamExtensions
{
public static string ConvertToBase64(this Stream stream)
{
var bytes = new Byte[(int)stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(bytes, 0, (int)stream.Length);
return Convert.ToBase64String(bytes);
}
}
The methods for Read (and also Write) and optimized for the respective class (whether is file stream, memory stream, etc.) and will do the work for you. For simple task like this, there is no need of readers, and etc.
The only drawback is that the stream is copied into byte array, but that is how the conversion to base64 via Convert.ToBase64String works unfortunately.
I used underscore
javascript library to tweak this issue.
function containsObject(obj, list) {
var res = _.find(list, function(val){ return _.isEqual(obj, val)});
return (_.isObject(res))? true:false;
}
please refer to underscore.js documentation for the underscore functions used in the above example.
note: This is not a pure javascript solution. Shared for educational purposes.
Is old post but can be done like this:
if(!function_exists('strim')) :
function strim($str,$charlist=" ",$option=0){
$return='';
if(is_string($str))
{
// Translate HTML entities
$return = str_replace(" "," ",$str);
$return = strtr($return, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
// Choose trim option
switch($option)
{
// Strip whitespace (and other characters) from the begin and end of string
default:
case 0:
$return = trim($return,$charlist);
break;
// Strip whitespace (and other characters) from the begin of string
case 1:
$return = ltrim($return,$charlist);
break;
// Strip whitespace (and other characters) from the end of string
case 2:
$return = rtrim($return,$charlist);
break;
}
}
return $return;
}
endif;
Standard trim() functions can be a problematic when come HTML entities. That's why i wrote "Super Trim" function what is used to handle with this problem and also you can choose is trimming from the begin, end or booth side of string.
I'm using this solution and works in IE8 or greater.
if (typeof Element.prototype.addEventListener === 'undefined') {
Element.prototype.addEventListener = function (e, callback) {
e = 'on' + e;
return this.attachEvent(e, callback);
};
}
And then:
<button class="click-me">Say Hello</button>
<script>
document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
console.log('Hello');
});
</script>
This will work both IE8 and Chrome, Firefox, etc.
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Where referenceNode
is the node you want to put newNode
after. If referenceNode
is the last child within its parent element, that's fine, because referenceNode.nextSibling
will be null
and insertBefore
handles that case by adding to the end of the list.
So:
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
You can test it using the following snippet:
function insertAfter(referenceNode, newNode) {_x000D_
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);_x000D_
}_x000D_
_x000D_
var el = document.createElement("span");_x000D_
el.innerHTML = "test";_x000D_
var div = document.getElementById("foo");_x000D_
insertAfter(div, el);
_x000D_
<div id="foo">Hello</div>
_x000D_
You can make a simple hashMap yourself. What a hashMap does is storing items in a array using the hash as index/key. Hash-functions give collisions once in a while (not often, but they may do), so you have to store multiple items for an entry in the hashMap. That simple is a hashMap:
class IEqualityComparer {
public function equals($x, $y) {
throw new Exception("Not implemented!");
}
public function getHashCode($obj) {
throw new Exception("Not implemented!");
}
}
class HashMap {
private $map = array();
private $comparer;
public function __construct(IEqualityComparer $keyComparer) {
$this->comparer = $keyComparer;
}
public function has($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $item) {
if ($this->comparer->equals($item['key'], $key)) {
return true;
}
}
return false;
}
public function get($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $item) {
if ($this->comparer->equals($item['key'], $key)) {
return $item['value'];
}
}
return false;
}
public function del($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $index => $item) {
if ($this->comparer->equals($item['key'], $key)) {
unset($this->map[$hash][$index]);
if (count($this->map[$hash]) == 0)
unset($this->map[$hash]);
return true;
}
}
return false;
}
public function put($key, $value) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
$this->map[$hash] = array();
}
$newItem = array('key' => $key, 'value' => $value);
foreach ($this->map[$hash] as $index => $item) {
if ($this->comparer->equals($item['key'], $key)) {
$this->map[$hash][$index] = $newItem;
return;
}
}
$this->map[$hash][] = $newItem;
}
}
For it to function you also need a hash-function for your key and a comparer for equality (if you only have a few items or for another reason don't need speed you can let the hash-function return 0; all items will be put in same bucket and you will get O(N) complexity)
Here is an example:
class IntArrayComparer extends IEqualityComparer {
public function equals($x, $y) {
if (count($x) !== count($y))
return false;
foreach ($x as $key => $value) {
if (!isset($y[$key]) || $y[$key] !== $value)
return false;
}
return true;
}
public function getHashCode($obj) {
$hash = 0;
foreach ($obj as $key => $value)
$hash ^= $key ^ $value;
return $hash;
}
}
$hashmap = new HashMap(new IntArrayComparer());
for ($i = 0; $i < 10; $i++) {
for ($j = 0; $j < 10; $j++) {
$hashmap->put(array($i, $j), $i * 10 + $j);
}
}
echo $hashmap->get(array(3, 7)) . "<br/>";
echo $hashmap->get(array(5, 1)) . "<br/>";
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(-1, 9))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(6))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(1, 2, 3))? 'true': 'false') . "<br/>";
$hashmap->del(array(8, 4));
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
Which gives as output:
37
51
true
false
false
false
false
I have implemented a tiny benchmark (please find the code on Gist) to evaluate the pandas' concat
and append
. I updated the code snippet and the results after the comment by ssk08
- thanks alot!
The benchmark ran on a Mac OS X 10.13 system with Python 3.6.2 and pandas 0.20.3.
+--------+---------------------------------+---------------------------------+ | | ignore_index=False | ignore_index=True | +--------+---------------------------------+---------------------------------+ | size | append | concat | append/concat | append | concat | append/concat | +--------+--------+--------+---------------+--------+--------+---------------+ | small | 0.4635 | 0.4891 | 94.77 % | 0.4056 | 0.3314 | 122.39 % | +--------+--------+--------+---------------+--------+--------+---------------+ | medium | 0.5532 | 0.6617 | 83.60 % | 0.3605 | 0.3521 | 102.37 % | +--------+--------+--------+---------------+--------+--------+---------------+ | large | 0.9558 | 0.9442 | 101.22 % | 0.6670 | 0.6749 | 98.84 % | +--------+--------+--------+---------------+--------+--------+---------------+
Using ignore_index=False
append
is slightly faster, with ignore_index=True
concat
is slightly faster.
tl;dr
No significant difference between concat
and append
.
In most recent version of Rails (can't tell which one exactly though), you could use the as_json
method :
@post = Post.first
hash = @post.as_json
puts hash.pretty_inspect
Will output :
{
:name => "test",
:post_number => 20,
:active => true
}
To go a bit further, you could override that method in order to customize the way your attributes appear, by doing something like this :
class Post < ActiveRecord::Base
def as_json(*args)
{
:name => "My name is '#{self.name}'",
:post_number => "Post ##{self.post_number}",
}
end
end
Then, with the same instance as above, will output :
{
:name => "My name is 'test'",
:post_number => "Post #20"
}
This of course means you have to explicitly specify which attributes must appear.
Hope this helps.
EDIT :
Also you can check the Hashifiable gem.
For Guzzle 5, 6 and 7 you do it like this:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);
You can pass multiple arrays as arguments using something like this:
takes_ary_as_arg()
{
declare -a argAry1=("${!1}")
echo "${argAry1[@]}"
declare -a argAry2=("${!2}")
echo "${argAry2[@]}"
}
try_with_local_arys()
{
# array variables could have local scope
local descTable=(
"sli4-iread"
"sli4-iwrite"
"sli3-iread"
"sli3-iwrite"
)
local optsTable=(
"--msix --iread"
"--msix --iwrite"
"--msi --iread"
"--msi --iwrite"
)
takes_ary_as_arg descTable[@] optsTable[@]
}
try_with_local_arys
sli4-iread sli4-iwrite sli3-iread sli3-iwrite
--msix --iread --msix --iwrite --msi --iread --msi --iwrite
Edit/notes: (from comments below)
descTable
and optsTable
are passed as names and are expanded in the function. Thus no $
is needed when given as parameters.descTable
etc being defined with local
, because locals are visible to the functions they call.!
in ${!1}
expands the arg 1 variable.declare -a
just makes the indexed array explicit, it is not strictly necessary.The modern way to do this is with flexbox, adding align-items: flex-end;
on the container.
With this content:
<div class="Container">
<div>one</div>
<div>two</div>
</div>
Use this style:
.Container {
display: flex;
align-items: flex-end;
}
If you want to manipulate the actual CSS class instead of modifying the DOM elements or using modifier CSS classes, see https://stackoverflow.com/a/50036923/482916.
You can try with ParseExact
method
Sample
Dim format As String
format = "d"
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
_x000D_
# COLUMN is integer column number
# INPUT_FILE is input file name
cut -f ${COLUMN} < ${INPUT_FILE} | sort -u | wc -l
After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.
# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]
# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]
# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...
Requirements:
Xcode -> Preferences -> Locations
change Command Line Tools to Xcode 11.2.1
Make it static (shared in VB).
Public Class Form1
Public Shared SomeValue As Integer = 5
End Class
No, there is no simpler way. You only can lose the type=array
.
<numbers>
<value>3</value>
<value>2</value>
<value>1</value>
</numbers>
You can use the exit
built-in to set the exit code of a process. It can be obtained from the exitcode
attribute of the process:
import multiprocessing
def worker(procnum):
print str(procnum) + ' represent!'
exit(procnum)
if __name__ == '__main__':
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p)
p.start()
result = []
for proc in jobs:
proc.join()
result.append(proc.exitcode)
print result
Output:
0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
[0, 1, 2, 3, 4]
You have to get back out of the Iframe with the following code:
driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();
hope that helps
Here are a few simple, order-preserving ways of diffing two lists of strings.
Code
An unusual approach using pathlib
:
import pathlib
temp1 = ["One", "Two", "Three", "Four"]
temp2 = ["One", "Two"]
p = pathlib.Path(*temp1)
r = p.relative_to(*temp2)
list(r.parts)
# ['Three', 'Four']
This assumes both lists contain strings with equivalent beginnings. See the docs for more details. Note, it is not particularly fast compared to set operations.
A straight-forward implementation using itertools.zip_longest
:
import itertools as it
[x for x, y in it.zip_longest(temp1, temp2) if x != y]
# ['Three', 'Four']
Uh.. Try this:
def int_check(a):
if int(a) == a:
return True
else:
return False
This works if you don't put a string that's not a number.
And also (I forgot to put the number check part. ), there is a function checking if the string is a number or not. It is str.isdigit(). Here's an example:
a = 2
a.isdigit()
If you call a.isdigit(), it will return True.
First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript
You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".
It's probably not working due to one of:
To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.
For example:
$(document).ready(function() {
// This WILL work because we are listening on the 'document',
// for a click on an element with an ID of #test-element
$(document).on("click","#test-element",function() {
alert("click bound to document listening for #test-element");
});
// This will NOT work because there is no '#test-element' ... yet
$("#test-element").on("click",function() {
alert("click bound directly to #test-element");
});
// Create the dynamic element '#test-element'
$('body').append('<div id="test-element">Click mee</div>');
});
In this example, only the "bound to document" alert will fire.
This is what I got from oracle documentation, but it is for oracle 10g release 2:
When you define a NUMBER variable, you can specify its precision (p) and scale (s) so that it is sufficiently, but not unnecessarily, large. Precision is the number of significant digits. Scale can be positive or negative. Positive scale identifies the number of digits to the right of the decimal point; negative scale identifies the number of digits to the left of the decimal point that can be rounded up or down.
The NUMBER data type is supported by Oracle Database standard libraries and operates the same way as it does in SQL. It is used for dimensions and surrogates when a text or INTEGER data type is not appropriate. It is typically assigned to variables that are not used for calculations (like forecasts and aggregations), and it is used for variables that must match the rounding behavior of the database or require a high degree of precision. When deciding whether to assign the NUMBER data type to a variable, keep the following facts in mind in order to maximize performance:
(For who ever got here due to wrong table style) Change Table style from plain to grouped, via the attributes inspector, or via code:
let tableView = UITableView(frame: .zero, style: .grouped)
In java 8
String lastItem = Stream.of(str.split("-")).reduce((first,last)->last).get();
if anyone else has this situation: i am creating an email verification to log in to my app so my users arent signed in yet, however i used the below to check for an email entered on the login which is a variation of @firecape solution
ApplicationUser user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindByEmail(Email.Text);
you will also need the following:
using Microsoft.AspNet.Identity;
and
using Microsoft.AspNet.Identity.Owin;
You can set the value in the HTML and then init datepicker to start/highlight the actual date
<input name="datefrom" type="text" class="datepicker" value="20-1-2011">
<input name="dateto" type="text" class="datepicker" value="01-01-2012">
<input name="dateto2" type="text" class="datepicker" >
$(".datepicker").each(function() {
$(this).datepicker('setDate', $(this).val());
});
The above even works with danish date formats
If you just want to check if the file uploaded is an image you can just try to load it into <img>
tag an check for any error callback.
Example:
var input = document.getElementsByTagName('input')[0];
var reader = new FileReader();
reader.onload = function (e) {
imageExists(e.target.result, function(exists){
if (exists) {
// Do something with the image file..
} else {
// different file format
}
});
};
reader.readAsDataURL(input.files[0]);
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
I wrote this function for higher numbers and all test cases
function numberToOrdinal(num) {
if (num === 0) {
return '0'
};
let i = num.toString(), j = i.slice(i.length - 2), k = i.slice(i.length - 1);
if (j >= 10 && j <= 20) {
return (i + 'th')
} else if (j > 20 && j < 100) {
if (k == 1) {
return (i + 'st')
} else if (k == 2) {
return (i + 'nd')
} else if (k == 3) {
return (i + 'rd')
} else {
return (i + 'th')
}
} else if (j == 1) {
return (i + 'st')
} else if (j == 2) {
return (i + 'nd')
} else if (j == 3) {
return (i + 'rd')
} else {
return (i + 'th')
}
}
Have you heard about the jQuery Waypoint plugin.
Below is the simple way of calling a waypoints plugin and having the page load more Content once you reaches the bottom on scroll :
$(document).ready(function() {
var $loading = $("<div class='loading'><p>Loading more items…</p></div>"),
$footer = $('footer'),
opts = {
offset: '100%'
};
$footer.waypoint(function(event, direction) {
$footer.waypoint('remove');
$('body').append($loading);
$.get($('.more a').attr('href'), function(data) {
var $data = $(data);
$('#container').append($data.find('.article'));
$loading.detach();
$('.more').replaceWith($data.find('.more'));
$footer.waypoint(opts);
});
}, opts);
});
add this below script in ~/.bashrc and do please replace project name(projectname) with whatever the name you needed
function s() {
array=($(gcloud projects list | awk /projectname/'{print $1}'))
for i in "${!array[@]}";do printf "%s=%s\n" "$i" "${array[$i]}";done
echo -e "\nenter the number to switch project:\c"
read project
[ ${array[${project}]} ] || { echo "project not exists"; exit 2; }
printf "\n**** Running: gcloud config set project ${array[${project}]} *****\n\n"
eval "gcloud config set project ${array[${project}]}"
}
I was also having the same issue with Spring Boot and embedded Tomcat.
From what I understand these properties only set the Tomcat configuration parameters. According to the Tomcat documentation this is only used for Client authentication (i.e. for two-way SSL) and not for verifying remote certificates:
truststoreFile - The trust store file to use to validate client certificates.
https://tomcat.apache.org/tomcat-8.0-doc/config/http.html
In order to configure the trust store for HttpClient it largely depends on the HttpClient implementation you use. For instance for RestTemplate by default Spring Boot uses a SimpleClientHttpRequestFactory based on standard J2SE classes like java.net.HttpURLConnection.
I've come up with a solution based on the Apache HttpClient docs and these posts: http://vincentdevillers.blogspot.pt/2013/02/configure-best-spring-resttemplate.html http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
Basically this allows for a RestTemplate bean that only trusts certificates signed by the root CA in the configured truststore.
@Configuration
public class RestClientConfig {
// e.g. Add http.client.ssl.trust-store=classpath:ssl/truststore.jks to application.properties
@Value("${http.client.ssl.trust-store}")
private Resource trustStore;
@Value("${http.client.ssl.trust-store-password}")
private char[] trustStorePassword;
@Value("${http.client.maxPoolSize}")
private Integer maxPoolSize;
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
@Bean
public HttpClient httpClient() {
// Trust own CA and all child certs
Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
try {
SSLContext sslContext = SSLContexts
.custom()
.loadTrustMaterial(trustStore.getFile(),
trustStorePassword)
.build();
// Since only our own certs are trusted, hostname verification is probably safe to bypass
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
new HostnameVerifier() {
@Override
public boolean verify(final String hostname,
final SSLSession session) {
return true;
}
});
socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
} catch (Exception e) {
//TODO: handle exceptions
e.printStackTrace();
}
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(maxPoolSize);
// This client is for internal connections so only one route is expected
connectionManager.setDefaultMaxPerRoute(maxPoolSize);
return HttpClientBuilder.create()
.setConnectionManager(connectionManager)
.disableCookieManagement()
.disableAuthCaching()
.build();
}
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(httpRequestFactory());
return restTemplate;
}
}
And then you can use this custom Rest client whenever you need to, e.g.:
@Autowired
private RestTemplate restTemplate;
restTemplate.getForEntity(...)
This assumes your trying to connect to a Rest endpoint, but you can also use the above HttpClient bean for whatever you want.
I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:
import numpy as np
from sklearn import linear_model
from sklearn import svm
classifiers = [
svm.SVR(),
linear_model.SGDRegressor(),
linear_model.BayesianRidge(),
linear_model.LassoLars(),
linear_model.ARDRegression(),
linear_model.PassiveAggressiveRegressor(),
linear_model.TheilSenRegressor(),
linear_model.LinearRegression()]
trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ])
trainingScores = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData = np.array([ [2.5, 2.4, 2.7], [2.7, 3.2, 1.2] ])
for item in classifiers:
print(item)
clf = item
clf.fit(trainingData, trainingScores)
print(clf.predict(predictionData),'\n')
It is nor php nor html it sounds like specific xml tag.
From personal experience, the System.Diagnostics.Stopwatch
class can be used to measure the execution time of a method, however, BEWARE: It is not entirely accurate!
Consider the following example:
Stopwatch sw;
for(int index = 0; index < 10; index++)
{
sw = Stopwatch.StartNew();
DoSomething();
Console.WriteLine(sw.ElapsedMilliseconds);
}
sw.Stop();
Example results
132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms
Now you're wondering; "well why did it take 132ms the first time, and significantly less the rest of the time?"
The answer is that Stopwatch
does not compensate for "background noise" activity in .NET, such as JITing. Therefore the first time you run your method, .NET JIT's it first. The time it takes to do this is added to the time of the execution. Equally, other factors will also cause the execution time to vary.
What you should really be looking for absolute accuracy is Performance Profiling!
Take a look at the following:
RedGate ANTS Performance Profiler is a commercial product, but produces very accurate results. - Boost the performance of your applications with .NET profiling
Here is a StackOverflow article on profiling: - What Are Some Good .NET Profilers?
I have also written an article on Performance Profiling using Stopwatch that you may want to look at - Performance profiling in .NET
I was not using any third party firewalls when running into this error. I was convinced it was a Windows Firewall issue, though disabling Windows Firewall did not work for me. I finally found this blog post after much research: Docker on windows 10 error: A firewall is blocking file Sharing ...
It ended up NOT having to do with the built in Windows Firewall.
The Fix
- Uncheck File and Printer Sharing for Microsoft Networks from the vEthernet (DockerNAT) network adapter (you can find the connection in the Windows Network and Sharing Center).
- Recheck it and make sure it is enabled.
Use Array.extend
instead of Array.push
for > 150,000 records.
if (!Array.prototype.extend) {
Array.prototype.extend = function(arr) {
if (!Array.isArray(arr)) {
return this;
}
for (let record of arr) {
this.push(record);
}
return this;
};
}
Also you can do join:
var qwe = new List<int> {5, 2, 3, 8};
Console.WriteLine(string.Join("\t", qwe));
fmod
is the standard C function for handling floating-point modulus; I imagine your source was saying that Java handles floating-point modulus the same as C's fmod
function. In Java you can use the %
operator on doubles the same as on integers:
int x = 5 % 3; // x = 2
double y = .5 % .3; // y = .2
The way you have it is fine but you could create a set of extension methods to make "a more elegant way to check for the 'NOT' instance."
public static bool Is<T>(this object myObject)
{
return (myObject is T);
}
public static bool IsNot<T>(this object myObject)
{
return !(myObject is T);
}
Then you could write:
if (child.IsNot<IContainer>())
{
// child is not an IContainer
}
You must run git fetch
before you can compare your local repository against the files on your remote server.
This command only updates your remote tracking branches and will not affect your worktree until you call git merge
or git pull
.
To see the difference between your local branch and your remote tracking branch once you've fetched you can use git diff or git cherry as explained here.
If you don't want to send the full modal structure you can replicate the old behaviour doing something like this:
// this is just an example, remember to adapt the selectors to your code!
$('.modal-link').click(function(e) {
var modal = $('#modal'), modalBody = $('#modal .modal-body');
modal
.on('show.bs.modal', function () {
modalBody.load(e.currentTarget.href)
})
.modal();
e.preventDefault();
});
mysql_query
function is used for executing mysql query in php. mysql_query
returns false if query execution fails.Alternatively you can try using mysql_error()
function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
In addition you can add live template that will do the work.
To do it press Ctrl+Alt+S -> "Live Templates"
section -> other
(or w/e you wish)
And then create a new one with a definition like this:
private static final long serialVersionUID = 1L;
$END$
Then select definition
scope and save it as 'serial'
Now you can type serial
TAB in class body.
Maybe the condition you are using is incorrect:
$str1 == "taste" && $str2 == "waste"
The program will enter into THEN
part only when both of the stated conditions are true.
You can try with $str1 == "taste" || $str2 == "waste"
. This will execute the THEN
part if anyone of the above conditions are true.
in function
def handleUpload():
if 'photo' in request.files:
photo = request.files['photo']
if photo.filename != '':
image = request.files['photo']
image_string = base64.b64encode(image.read())
image_string = image_string.decode('utf-8')
#use this to remove b'...' to get raw string
return render_template('handleUpload.html',filestring = image_string)
return render_template('upload.html')
in html file
<html>
<head>
<title>Simple file upload using Python Flask</title>
</head>
<body>
{% if filestring %}
<h1>Raw image:</h1>
<h1>{{filestring}}</h1>
<img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
{% else %}
<h1></h1>
{% endif %}
</body>
echo "You are running $0"
one line solution: basic idea:
$('sth').click(function () {
let COND = $(this).propery == 'cond1' ? 'cond2' : 'cond1';
doSomeThing(COND);
})
example 1, changing innerHTML of an element in a toggle-mode:
$('#clickTest1').click(function () {
$(this).html($(this).html() == 'click Me' ? 'clicked' : 'click Me');
});
example 2, toggling displays between "none" and "inline-block":
$('#clickTest2, #clickTest2 > span').click(function () {
$(this).children().css('display', $(this).children().css('display') == 'inline-block' ? 'none' : 'inline-block');
});
You'll need to compile it using:
g++ inputfile.cpp -o outputbinary
The file you are referring has a missing #include <cstdlib>
directive, if you also include that in your file, everything shall compile fine.
This is how I used this is as an example:
CAST(vAvgMaterialUnitCost.`avgUnitCost` AS DECIMAL(11,2)) * woMaterials.`qtyUsed` AS materialCost
Just to elaborate on the etymology of the command name rev-parse
, Git consistently uses the term rev
in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list
for example prints a list of 40-char commit hashes for a branch or whatever.
In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash
. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.
I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)
Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.
Jonathan's answer didn't seem to work for me. I'm using React v0.14.0 and React Router v1.0.0-rc3. This did:
<IndexRoute component={Home}/>
.
So in Matthew's Case, I believe he'd want:
<IndexRoute component={SearchDashboard}/>
.
Source: https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ComponentLifecycle.md
@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):
Option Explicit
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Sheet1") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
For editing use
vi galfit.feedme //if user has file editing permissions
or
sudo vi galfit.feedme //if user doesn't have file editing permissions
For inserting
Press i //Do required editing
For exiting
Press Esc
:wq //for exiting and saving
:q! //for exiting without saving
Don't press Esc ever. See this answer to learn why. As mentioned above, Ctrl + C is a better alternative. I strongly suggest mapping your Caps Lock key to escape.
If you're editing a Ctags compatible language, using a tags file and :ta
, Ctrl + ], etc. is a great way to navigate the code, even across multiple files. Also, Ctrl + N and Ctrl + P completion using the tags file is a great way to cut down on keystrokes.
If you're editing a line that is wrapped because it's wider than your buffer, you can move up/down using gk and gj.
Try to focus on effective use of the motion commands before you learn bad habits. Things like using 'dt' or 'd3w' instead of pressing x a bunch of times. Basically, any time that you find yourself pressing the same key repeatedly, there's probably a better/faster/more concise way of accomplishing the same thing.
If you have pandas
installed you can turn it into a series with the keys as the index. So something like
import pandas as pd
s = pd.Series(my_dict)
s[['key1', 'key3', 'key2']]
You need
str.CopyTo(data);
data.Position = 0; // reset to beginning
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
And since your Test()
method is imitating the client it ought to Close()
or Dispose()
the str
Stream. And the memoryStream too, just out of principal.
You are inside vim. To save changes and quit, type:
<esc> :wq <enter>
That means:
:wq
An alternative that stdcall in the comments mentions is:
Z
twice).I've used both approaches, and they both worked fine for me. Whichever one I use, I always try to apply this principle:
If the only possible errors are programmer errors, don't return an error code, use asserts inside the function.
An assertion that validates the inputs clearly communicates what the function expects, while too much error checking can obscure the program logic. Deciding what to do for all the various error cases can really complicate the design. Why figure out how functionX should handle a null pointer if you can instead insist that the programmer never pass one?
Use this: htmlentities($_POST['field']);
Enough only. This for special character:
Use for CI htmlentities($this->input->post('control_name'));
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
It seems they offer a js
option for the format parameter, which will return JSONP. You can retrieve JSONP like so:
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
console.log(data);
});
Interesting, I didn't know make would default to using the C compiler given rules regarding source files.
Anyway, a simple solution that demonstrates simple Makefile concepts would be:
HEADERS = program.h headers.h
default: program
program.o: program.c $(HEADERS)
gcc -c program.c -o program.o
program: program.o
gcc program.o -o program
clean:
-rm -f program.o
-rm -f program
(bear in mind that make requires tab instead of space indentation, so be sure to fix that when copying)
However, to support more C files, you'd have to make new rules for each of them. Thus, to improve:
HEADERS = program.h headers.h
OBJECTS = program.o
default: program
%.o: %.c $(HEADERS)
gcc -c $< -o $@
program: $(OBJECTS)
gcc $(OBJECTS) -o $@
clean:
-rm -f $(OBJECTS)
-rm -f program
I tried to make this as simple as possible by omitting variables like $(CC) and $(CFLAGS) that are usually seen in makefiles. If you're interested in figuring that out, I hope I've given you a good start on that.
Here's the Makefile I like to use for C source. Feel free to use it:
TARGET = prog
LIBS = -lm
CC = gcc
CFLAGS = -g -Wall
.PHONY: default all clean
default: $(TARGET)
all: default
OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c $< -o $@
.PRECIOUS: $(TARGET) $(OBJECTS)
$(TARGET): $(OBJECTS)
$(CC) $(OBJECTS) -Wall $(LIBS) -o $@
clean:
-rm -f *.o
-rm -f $(TARGET)
It uses the wildcard and patsubst features of the make utility to automatically include .c and .h files in the current directory, meaning when you add new code files to your directory, you won't have to update the Makefile. However, if you want to change the name of the generated executable, libraries, or compiler flags, you can just modify the variables.
In either case, don't use autoconf, please. I'm begging you! :)
You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use
ping -n 11 127.0.0.1 > nul
This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)
By these days (ending 2019) I prefer to use a tool like http://www.convertcsv.com/csv-to-sql.htm I you got a lot of rows you can run partitioned blocks saving user mistakes when csv come from a final user spreadsheet.