Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.
Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
Here's the best way I found:
For Each row As DataRow In your_table.Rows
For Each cell As String In row.ItemArray
'do what you want!
Next
Next
You can install any application/packages with brew on mac. If you want to know the exact command just search your package on https://brewinstall.org and you will get the set of commands needed to install that package.
First open terminal and install brew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null
Now Install jq
brew install jq
Maybe an example would help.
Your app wants to download a file from some remote computer and then write to to a local disk. The remote computer is the other side of a dial-up modem and a satellite link. The latency and transfer time will be huge and you have other things to do. So, you have a function/method that will write a buffer to disk. You pass a pointer to this method to your network API, together with the remote URI and other stuff. This network call returns 'immediately' and you can do your other stuff. 30 seconds later, the first buffer from the remote computer arrives at the network layer. The network layer then calls the function that you passed during the setup and so the buffer gets written to disk - the network layer has 'called back'. Note that, in this example, the callback would happen on a network layer thread than the originating thread, but that does not matter - the buffer still gets written to the disk.
Nobody mentioned it so far... with utf8mb4 which is 4-byte and can also store emoticons (we should never more use 3-byte utf8) and we can avoid errors like Incorrect string value: \xF0\x9F\x98\...
we should not use typical VARCHAR(255) but rather VARCHAR(191) because in case utf8mb4 and VARCHAR(255) same part of data are stored off-page and you can not create index for column VARCHAR(255) but for VARCHAR(191) you can. It is because the maximum indexed column size is 767 bytes for ROW_FORMAT=COMPACT or ROW_FORMAT=REDUNDANT.
For newer row formats ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED (which requires newer file format innodb_file_format=Barracuda not older Antelope) maximum indexed column size is 3072. It is available since MySQL >= 5.6.3 when innodb_large_prefix=1 (disabled by default for MySQL <= 5.7.6 and enabled by default for MySQL >= 5.7.7). So in this case we can use VARCHAR(768) for utf8mb4 (or VARCHAR(1024) for old utf8) for indexed column. Option innodb_large_prefix is deprecated since 5.7.7 because its behavior is built-in MySQL 8 (in this version is option removed).
Any() returns true if any of the elements in a collection meet your predicate's criteria.
Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.
Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.
You can use @Qualifier
along with @Autowired
. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier
For Example in following case it is necessary provide a qualifier
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
EDIT:
In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
@RequiredArgsConstructor
public Payroll {
@Qualifier("employee") private final Person person;
}
provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):
# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
This was recently introduced in latest lombok 1.18.4.
NOTE
If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)
public Payroll {
@Autowired @Qualifier("employee") private final Person person;
}
or
public Payroll {
private final Person person;
@Autowired
@Qualifier("employee")
public void setPerson(Person person) {
this.person = person;
}
}
If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
I upgraded to my Git for Windows to latest (2.30.0) 64-bit and it works fine now. get the latest from the url https://git-scm.com/download/win and run the commands below to verify. $ git --version $ git version 2.30.0.windows.1
Several of the answers mention that you can use JNI or JNA to access cpython but I would not recommend starting from scratch because there are already open source libraries for accessing cpython from java. For example:
It should also be noted that one key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the top level package. It shares a format with npm-shrinkwrap.json(5), which is essentially the same file, but allows publication. This is not recommended unless deploying a CLI tool or otherwise using the publication process for producing production packages.
If both package-lock.json and npm-shrinkwrap.json are present in the root of a package, package-lock.json will be completely ignored.
Try restarting the mysql or starting it if it wasn't started already. Type this within terminal.
mysql.server restart
To auto start go to the following link below:
How to auto-load MySQL on startup on OS X Yosemite / El Capitan
If anyone came here trying to do this with a decimal like me:
myFloat = parseFloat(myString);
If you just need an Int, that's well covered in the other answers.
it is working in google chrome when you add !important attribute to background image make sure you add attribute first and try again, you can do it like that
.inputbg {
background: url('inputbg.png') !important;
}
No. JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the GC decides to run and the object is eligible for collection.
Seeing as that will happen automatically as required, what would be the purpose of reclaiming the memory explicitly?
pure javascript:
var ctrlKeyCode = 17;
var cntrlIsPressed = false;
document.addEventListener('keydown', function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
document.addEventListener('keyup', function(){
if(event.which=="17")
cntrlIsPressed = true;
});
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
Most of the posted solutions using array functions such as filter are incomplete because they aren't parameterized.
Here goes a solution with which the element to count can be set at run time.
function elementsCount(elementToFind, total, number){
return total += number==elementToFind;
}
var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(elementsCount.bind(this, elementToFind), 0);
The advantage of this approach is that could easily change the function to count for instance the number of elements greater than X.
You may also declare the reduce function inline
var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(function (elementToFind, total, number){
return total += number==elementToFind;
}.bind(this, elementToFind), 0);
An easy way of doing this is to use JavaScript like so:
element.addEventListener('click', (e => {
e.preventDefault();
element.style = '<insert CSS here as you would in a style attribute>';
}));
Try this, but I don't think it will work because you're not supposed to be able to change this
Put this line in an htaccess file in the directory you want the setting to be enabled:
php_value allow_url_fopen On
Note that this setting will only apply to PHP file's in the same directory as the htaccess file.
As an alternative to using url_fopen, try using curl.
You can also replace complicated condition with single method call to make it less evil in maintain.
Try this:
def monthdelta(date, delta):
m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
if not m: m = 12
d = min(date.day, [31,
29 if y%4==0 and (not y%100==0 or y%400 == 0) else 28,
31,30,31,30,31,31,30,31,30,31][m-1])
return date.replace(day=d,month=m, year=y)
>>> for m in range(-12, 12):
print(monthdelta(datetime.now(), m))
2009-08-06 16:12:27.823000
2009-09-06 16:12:27.855000
2009-10-06 16:12:27.870000
2009-11-06 16:12:27.870000
2009-12-06 16:12:27.870000
2010-01-06 16:12:27.870000
2010-02-06 16:12:27.870000
2010-03-06 16:12:27.886000
2010-04-06 16:12:27.886000
2010-05-06 16:12:27.886000
2010-06-06 16:12:27.886000
2010-07-06 16:12:27.886000
2010-08-06 16:12:27.901000
2010-09-06 16:12:27.901000
2010-10-06 16:12:27.901000
2010-11-06 16:12:27.901000
2010-12-06 16:12:27.901000
2011-01-06 16:12:27.917000
2011-02-06 16:12:27.917000
2011-03-06 16:12:27.917000
2011-04-06 16:12:27.917000
2011-05-06 16:12:27.917000
2011-06-06 16:12:27.933000
2011-07-06 16:12:27.933000
>>> monthdelta(datetime(2010,3,30), -1)
datetime.datetime(2010, 2, 28, 0, 0)
>>> monthdelta(datetime(2008,3,30), -1)
datetime.datetime(2008, 2, 29, 0, 0)
Edit Corrected to handle the day as well.
Edit See also the answer from puzzlement which points out a simpler calculation for d
:
d = min(date.day, calendar.monthrange(y, m)[1])
It's seems flaw's in your database structure. Keep default value None to your title and body column.
Try this:
$user_login_id = auth()->id();
Post::create(request([
'body' => request('body'),
'title' => request('title'),
'user_id' => $user_login_id
]));
You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).
But, try this:
a = [0 for x in range(N)] # N = size of list you want
a[i] = 5 # as long as i < N, you're okay
For lists of other types, use something besides 0. None
is often a good choice as well.
Using slice() method:
function returnChunksArray(str, chunkSize) {
var arr = [];
while(str !== '') {
arr.push(str.slice(0, chunkSize));
str = str.slice(chunkSize);
}
return arr;
}
The same can be done using substring() method.
function returnChunksArray(str, chunkSize) {
var arr = [];
while(str !== '') {
arr.push(str.substring(0, chunkSize));
str = str.substring(chunkSize);
}
return arr;
}
With VS 2013 Express this key does not exist. What I see is HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0 and there is no mention of Text Editor under that.
DateTime d1 = ...;
DateTime d2 = ...;
Period period = new Period(d1, d2, PeriodType.minutes());
int differenceMinutes = period.getMinutes();
In practice I think this will always give the same result as the answer based on Duration
. For a different time unit than minutes, though, it might be more correct. For example there are 365 days from 2016/2/2 to 2017/2/1, but actually it's less than 1 year and should truncate to 0 years if you use PeriodType.years()
.
In theory the same could happen for minutes because of leap seconds, but Joda doesn't support leap seconds.
You can read it by chunks (byte buffer[] = new byte[2048]
) and write the chunks to a ByteArrayOutputStream. From the ByteArrayOutputStream you can retrieve the contents as a byte[], without needing to determine its size beforehand.
It may be relevant to see if it's running in PHP via command line as well-
<path-to-php-binary>php -i | grep memcache
select pe_name,count( distinct b.ord_id),count(c.item_id)
from people a, order1 as b ,item as c
where a.pe_id=b.pe_id and
b.ord_id=c.order_id group by a.pe_id,pe_name
Mike's suggestion sounds like the "right way". I came across this thread wanting to specify the user to run vncserver
under on reboot and wanted to keep all my cron jobs in one place.
I was getting the following error for the VNC cron:
vncserver: The USER environment variable is not set. E.g.:
In my case, I was able to use sudo
to specify who to run the task as.
@reboot sudo -u [someone] vncserver ...
Is 'clean' not good enough? Note that you can call msbuild with /t:clean from the command-line.
Thre are 2 ways to run Action Query in MS Access VBA:
DoCmd.OpenQuery
statement. This allows you to control these warnings:BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs
Function RunActionQuery(QueryName As String)
On Error GoTo Hell 'Set Error Hanlder
DoCmd.SetWarnings True 'Turn On Warnings
DoCmd.OpenQuery QueryName 'Execute Action Query
DoCmd.SetWarnings False 'Turn On Warnings
Exit Function
Hell:
If Err.Number = 2501 Then 'If Query Was Canceled
MsgBox Err.Description, vbInformation
Else 'Everything else
MsgBox Err.Description, vbCritical
End If
End Function
CurrentDb.Execute
method. This alows you to keep Action Query failures
under control. The SetWarnings flag does not affect it. Query is executed always without warnings.Function RunActionQuery()
'To Catch the Query Error use dbFailOnError option
On Error GoTo Hell
CurrentDb.Execute "Query1", dbFailOnError
Exit Function
Hell:
Debug.Print Err.Description
End Function
It is worth noting that the dbFailOnError
option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified
In addition, you can use DoCmd.Hourglass True
and DoCmd.Hourglass False
to control the mouse pointer if your Query takes longer
Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt")
. The only drawback is that this call requires root privileges on OSX.
You can change the labels' text by adorning the property with the DisplayName
attribute.
[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }
Or, you could write the raw HTML explicitly:
<label for="SomekingStatus" class="control-label">Someking Status</label>
window.onload
and onunload
are shortcuts to document.body.onload
and document.body.onunload
document.onload
and onload
handler on all html tag seems to be reserved however never triggered
'onload
' in document -> true
i'd just do a simple check to see if d[a] exists and if not initialize it...
var a = "1",
b = "hello",
c = { "100" : "some important data" },
d = {};
if (d[a] === undefined) {
d[a] = {}
};
d[a]["greeting"] = b;
d[a]["data"] = c;
console.debug (d);
I believe it's better to use
$('#form-id').find('input').val('');
instead of
$('#form-id').children('input').val('');
incase you have checkboxes in your form use this to rest it:
$('#form-id').find('input:checkbox').removeAttr('checked');
Looks like python requests does not handle extremely large multi-part files.
The documentation recommends you look into requests-toolbelt
.
Here's the pertinent page from their documentation.
If you don't mind adding a dependency, you can use JsonPath.
import com.jayway.jsonpath.JsonPath;
String firstName = JsonPath.read(rawJsonString, "$.detail.first_name");
"$" specifies the root of the raw json string and then you just specify the path to the field you want. This will always return a string. You'll have to do any casting yourself.
Be aware that it'll throw a PathNotFoundException at runtime if the path you specify doesn't exist.
You should be able to use forward slashes in Java to refer to file locations.
The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the Java APIs.
Toolkit's use of BufferedReader is probably what you need.
for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.
if( (A) && (B) ){
//if A and B both are true
}else{
}
if( (A) ||(B) ){
//if A or B is true
}else{
}
You can load a Java class from source at runtime. (Using JCI, BeanShell or JavaCompiler)
This would allow you to change the Enum values as you wish.
Note: this wouldn't change any classes which referred to these enums so this might not be very useful in reality.
This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.
You don't. Your array doesn't have a key [1]
. You could:
Make a new array, which contains the keys:
$newArray = array_keys($array);
echo $newArray[0];
But the value "one" is at $newArray[0]
, not [1]
.
A shortcut would be:
echo current(array_keys($array));
Get the first key of the array:
reset($array);
echo key($array);
Get the key corresponding to the value "value":
echo array_search('value', $array);
This all depends on what it is exactly you want to do. The fact is, [1]
doesn't correspond to "one" any which way you turn it.
The package is not fully compatible with dotnetcore 2.0 for now.
eg, for 'Microsoft.AspNet.WebApi.Client'
it maybe supported in version (5.2.4).
See Consume new Microsoft.AspNet.WebApi.Client.5.2.4 package for details.
You could try the standard Client package as Federico mentioned.
If that still not work, then as a workaround you can only create a Console App (.Net Framework)
instead of the .net core 2.0 console app.
Reference this thread: Microsoft.AspNet.WebApi.Client supported in .NET Core or not?
One technique I think is a little easier and that hasn't been mentioned before here:
var asdf = new [] {
(Age: 1, Name: "cow"),
(Age: 2, Name: "bird")
}.ToList();
I think that's a little cleaner than:
var asdf = new List<Tuple<int, string>> {
(Age: 1, Name: "cow"),
(Age: 2, Name: "bird")
};
You just need to divide each element by the sum of the values in its column.
Doing this should suffice:
data.perc <- apply(data, 2, function(x){x/sum(x)})
Note that the second parameter tells apply
to apply the provided function to columns (using 1 you would apply it to rows). The anonymous function, then, gets passed each data column, one at a time.
You need
@ManagedBean(name="userBean")
Make sure you have getUser()
method.
Type of setUser()
method should be void
.
Make sure that User
class has proper setters
and getters
as well.
Steps to get this error ;
Solution : rm -rf "name of repo folder which in out case is xyz" . So
rm -rf xyz
Here's what I put together. It works on the select mobile device I needed it for, but I'm not sure how universal the solution is
<a href="mailto:[email protected]?subject=Me&body=%3Chtml%20xmlns%3D%22http:%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%3C%2Fhead%3E%3Cbody%3EPlease%20%3Ca%20href%3D%22http:%2F%2Fwww.w3.org%22%3Eclick%3C%2Fa%3E%20me%3C%2Fbody%3E%3C%2Fhtml%3E">
This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
To use code like this, you can do something like:
print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)
Or, with Python 3.6+:
print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")
This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.
If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.
If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".
Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).
The Text Mode Demo Contest has more resources for doing graphics in text mode.
Now, you can
#wrapper { display: flow-root; }
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
Just click on form and go to JFrame properties, then Code tab and check Generate Center
.
Since this question is from 4 years ago new things have been implemented and among them there is a new function plt.subplots
which is very convenient:
fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
where axes
is a numpy.ndarray
of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices [i,j]
.
You can set the output to a temporary file and the read the data from the file after that you can delete the temporary file.
echo %date%>temp.txt
set /p myVarDate= < temp.txt
echo Date is %myVarDate%
del temp.txt
In this variable myVarDate
contains the output of command.
Text2Conv="Aa"
for letter in $(echo "$Text2Conv" | sed "s/\(.\)/'\1 /g");do printf '%x' "$letter";done
4161
The trick is using sed to parse the Text2Conv to format we can then seperate anf loop using for.
The simplest way in laravel 5 is:
$listings=Listing::take(10)->get();
return view('view.name',compact('listings'));
You can also use binding
<TextBlock Text="{Binding MyText}"/>
And set MyText like this:
Public string MyText
{
get{return string.Format("My Text \n Your Text");}
}
Now google chrome has introduce new feature. By Using this feature You can edit you code in chrome browse. (Permanent change on code location)
For that Press F12 --> Source Tab -- (right side) --> File System - in that please select your location of code. and then chrome browser will ask you permission and after that code will be sink with green color. and you can modify your code and it will also reflect on you code location (It means it will Permanent change)
Thanks
None of these answers seem to be quite right. I tried them all. Here are my results.
Sending query: SELECT count(*) FROM daximation
91
Sending query: SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'
96
Sending query: SHOW TABLE STATUS LIKE 'daximation'
98
Sending query: SELECT id FROM daximation ORDER BY id DESC LIMIT 1
97
here's the screenshot: https://www.screencast.com/t/s8c3trYU
Here is my PHP code:
$query = "SELECT count(*) FROM daximation";
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);
$query = "SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'";
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);
$query = "SHOW TABLE STATUS LIKE 'daximation'";
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[10]);
$query = "SELECT id FROM daximation ORDER BY id DESC LIMIT 1";
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);
A free app named SqlTableZip will get the job done. Basically, you write any query (which, of course can also be [select * from table]) and the app creates a compressed file with all the data, which can be restored later.
In addition to the answers above.
I wrote following test.exe as console application
static void Main(string[] args) {
Console.WriteLine(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
Console.WriteLine(
System.Reflection.Assembly.GetEntryAssembly().Location);
Console.WriteLine(
System.Reflection.Assembly.GetExecutingAssembly().Location);
Console.WriteLine(
System.Reflection.Assembly.GetCallingAssembly().Location);
}
Then I compiled the project and renamed its output to the test2.exe file. The output lines were correct and the same.
But, if I start it in the Visual Studio, the result is:
d:\test2.vhost.exe
d:\test2.exe
d:\test2.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll
The ReSharper plug-in to the Visual Studio has underlined the
System.Diagnostics.Process.GetCurrentProcess().MainModule
as possible System.NullReferenceException. If you look into documentation of the MainModule you will find that this property can throw also NotSupportedException, PlatformNotSupportedException and InvalidOperationException.
The GetEntryAssembly method is also not 100% "safe". MSDN:
The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.
For my solutions, I prefer the Assembly.GetEntryAssembly().Location
.
More interest is if need to solve the problem for the virtualization. For example, we have a project, where we use a Xenocode Postbuild to link the .net code into one executable. This executable must be renamed. So all the methods above didn't work, because they only gets the information for the original assembly or inner process.
The only solution I found is
var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(location);
var file = System.IO.Path.Combine(directory,
System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
import re
result=[x for x in re.split(',| ',your_string) if x!='']
this works fine for me.
In case if you are using node js, then this could be the possible solution
const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;
Not the same, but idea that works anyway.
#!/bin/bash
i='y'
while [ ${i:0:1} != n ]
do
# Command(s)
read -p " Again? Y/n " i
[[ ${#i} -eq 0 ]] && i='y'
done
Output:
Again? Y/n N
Again? Y/n Anything
Again? Y/n 7
Again? Y/n &
Again? Y/n nsijf
$
Now only checks 1st character of $i read.
Ternary operator has just been added to angular parser in 1.1.5.
So the simplest way to do this is now :
ng:class="($index==selectedIndex)? 'selected' : ''"
You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:
from IPython.display import clear_output
for i in range(10):
clear_output(wait=True)
print(i, flush=True)
What about using rawurlencode() ? http://www.php.net/manual/en/function.rawurlencode.php
Here is a function that sanitize even Chinese Chars:
public static function normalizeString ($str = '')
{
$str = strip_tags($str);
$str = preg_replace('/[\r\n\t ]+/', ' ', $str);
$str = preg_replace('/[\"\*\/\:\<\>\?\'\|]+/', ' ', $str);
$str = strtolower($str);
$str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
$str = htmlentities($str, ENT_QUOTES, "utf-8");
$str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
$str = str_replace(' ', '-', $str);
$str = rawurlencode($str);
$str = str_replace('%', '-', $str);
return $str;
}
Here is the explaination
OK, some filename will not be releavant but in most case it will work.
ex. Original Name: "???????-??-????????????.jpg"
Output Name: "-E1-83-A1-E1-83-90-E1-83-91-E1-83-94-E1-83-AD-E1-83-93-E1-83-98--E1-83-93-E1-83-90--E1-83-A2-E1-83-98-E1-83-9E-E1-83-9D-E1-83-92-E1-83-A0-E1-83-90-E1-83-A4-E1-83-98-E1-83-A3-E1-83-9A-E1-83-98.jpg"
It's better like that than an 404 error.
Hope that was helpful.
Carl.
Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:
List<Video> = new ArrayList<>(Arrays.asList(videoArray));
my_list[0] if len(my_list) else None
With me the problem was the fact that matplotlib was using the wrong backend. I am using Debian Jessie.
In a console I did the following:
import matplotlib
matplotlib.get_backend()
The result was: 'agg', while this should be 'TkAgg'.
The solution was simple:
I had a similar issue, my error was:
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException:org.glassfish.jersey.servlet.ServletContainer from [Module "deployment.RESTful_Services_CRUD.war:main" from Service Module Loader]
I use jboss
and glassfish
so I changed the web.xml
to the following:
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
Instead of:
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
Hope this work for you.
Below code is self-explanatory, We can use an enum with a switch case:
/**
*
*/
enum ClassNames {
STRING(String.class, String.class.getSimpleName()),
BOOLEAN(Boolean.class, Boolean.class.getSimpleName()),
INTEGER(Integer.class, Integer.class.getSimpleName()),
LONG(Long.class, Long.class.getSimpleName());
private Class typeName;
private String simpleName;
ClassNames(Class typeName, String simpleName){
this.typeName = typeName;
this.simpleName = simpleName;
}
}
Based on the class values from the enum can be mapped:
switch (ClassNames.valueOf(clazz.getSimpleName())) {
case STRING:
String castValue = (String) keyValue;
break;
case BOOLEAN:
break;
case Integer:
break;
case LONG:
break;
default:
isValid = false;
}
Hope it helps :)
There is also difference is in plan handling.
Oracle is able form an optimized plan with concatenation of branch filters when search contains comparison of nvl
result with an indexed column.
create table tt(a, b) as
select level, mod(level,10)
from dual
connect by level<=1e4;
alter table tt add constraint ix_tt_a primary key(a);
create index ix_tt_b on tt(b);
explain plan for
select * from tt
where a=nvl(:1,a)
and b=:2;
explain plan for
select * from tt
where a=coalesce(:1,a)
and b=:2;
nvl:
-----------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
-----------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 2 | 52 | 2 (0)| 00:00:01 |
| 1 | CONCATENATION | | | | | |
|* 2 | FILTER | | | | | |
|* 3 | TABLE ACCESS BY INDEX ROWID| TT | 1 | 26 | 1 (0)| 00:00:01 |
|* 4 | INDEX RANGE SCAN | IX_TT_B | 7 | | 1 (0)| 00:00:01 |
|* 5 | FILTER | | | | | |
|* 6 | TABLE ACCESS BY INDEX ROWID| TT | 1 | 26 | 1 (0)| 00:00:01 |
|* 7 | INDEX UNIQUE SCAN | IX_TT_A | 1 | | 1 (0)| 00:00:01 |
-----------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter(:1 IS NULL)
3 - filter("A" IS NOT NULL)
4 - access("B"=TO_NUMBER(:2))
5 - filter(:1 IS NOT NULL)
6 - filter("B"=TO_NUMBER(:2))
7 - access("A"=:1)
coalesce:
---------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
---------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 26 | 1 (0)| 00:00:01 |
|* 1 | TABLE ACCESS BY INDEX ROWID| TT | 1 | 26 | 1 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | IX_TT_B | 40 | | 1 (0)| 00:00:01 |
---------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
1 - filter("A"=COALESCE(:1,"A"))
2 - access("B"=TO_NUMBER(:2))
Credits go to http://www.xt-r.com/2012/03/nvl-coalesce-concatenation.html.
DECLARE @TableName varchar(max)=NULL
SELECT @TableName=COALESCE(@TableName+',','')+t.TABLE_CATALOG+'.'+ t.TABLE_SCHEMA+'.'+o.Name
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME=o.name
WHERE i.indid < 2
AND OBJECTPROPERTY(o.id,'IsMSShipped') = 0
AND i.rowcnt >350
AND o.xtype !='TF'
ORDER BY o.name ASC
print @tablename
You can get list of tables which has rowcounts >350 . You can see at the solution list of table as row.
I think you need str.contains
, if you need rows where values of column date
contains string 07311954
:
print df[df['date'].astype(str).str.contains('07311954')]
Or if type
of date
column is string
:
print df[df['date'].str.contains('07311954')]
If you want check last 4 digits for string
1954
in column date
:
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
Sample:
print df['date']
0 8152007
1 9262007
2 7311954
3 2252011
4 2012011
5 2012011
6 2222011
7 2282011
Name: date, dtype: int64
print df['date'].astype(str).str[-4:].str.contains('1954')
0 False
1 False
2 True
3 False
4 False
5 False
6 False
7 False
Name: date, dtype: bool
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
cmte_id trans_typ entity_typ state employer occupation date \
2 C00119040 24K CCM MD NaN NaN 7311954
amount fec_id cand_id
2 1000 C00140715 H2MD05155
Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.
Use the typedef
specifier to avoid re-using the struct
statement everytime you declare a struct variable:
typedef struct
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}Body;
Then declare your array of structs. Initialization of each element goes along with the declaration:
Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};
To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.
For anyone else looking for help on this matter, or experiencing a FileNotFoundException or a FirstChanceException, check out my answer here:
In general you must be absolutely certain that you are meeting all of the requirements for making the reference - I know it's the obvious answer, but you're probably overlooking a relatively simple requirement.
Sudo-less installation
If you do not want to grant RubyGems admin privileges for this process, you can tell RubyGems to install into your user directory by passing either the --user-install flag to gem install or by configuring the RubyGems environment. The latter is in our opinion the best solution. To do this, create or edit the .profile file in your home directory and add or amend it to include these lines:
export GEM_HOME=$HOME/.gem
export PATH=$GEM_HOME/bin:$PATH
Note that if you choose to use the --user-install option, you will still have to configure your .profile file to set the PATH or use the command prepended by the full path. You can find out where a gem is installed with gem which cocoapods. E.g.
$ gem install cocoapods --user-install
$ gem which cocoapods
/Users/eloy/.gem/ruby/2.0.0/gems/cocoapods-0.29.0/lib/cocoapods.rb
$ /Users/eloy/.gem/ruby/2.0.0/bin/pod install
Source: https://guides.cocoapods.org/using/getting-started.html
As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:
with open('my_file.txt', 'rU') as in_file:
data = in_file.read().split('\n')
That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:
with open('new_file.txt', 'w') as out_file:
out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters
Hopefully that fits what you're looking for.
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
For those who use Spring Boot 2.x
There is no need to do any of the above - Java 8 LocalDateTime is serialised/de-serialised out of the box. I had to do all of the above in 1.x, but with Boot 2.x, it works seamlessly.
See this reference too JSON Java 8 LocalDateTime format in Spring Boot
I for myself prefer Lukas Edger's solution.
But you might want to know there is also a function SYS_GUID which can be applied as a default value to a column and generate unique ids.
you can read more about pros and cons here
I keep hitting this answer. But none of them list the easiest solution for xsltproc (and probably most XSLT 1.0 processors):
<xsl:stylesheet
version="1.0"
xmlns:str="http://exslt.org/strings"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:value-of select="str:replace(., ' ', '')"/>
Perhaps this answers doesn't fit your explanation but question title. It's useful when you are trying to know when you tapped the back button on an UINavigationBar
.
In this case you can use UINavigationBarDelegate
protocol and implement one of this methods:
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item;
When didPopItem
method is called, it's because you either tapped the back button or you used [UINavigationBar popNavigationItemAnimated:]
method and the navigation bar did pop the item.
Now, if you want to know what action triggered the didPopItem
method you can use a flag.
With this approach I don't need to manually add a left bar button item with an arrow image in order to make it similar to iOS back button, and be able to set my custom target/action.
I have a view controller that has a page view controller, and a custom page indicator view. I'm also using a custom UINavigationBar to display a title to know on what page am I and the back button to go back to the previous page. And I also can swipe to previous/next page on page controller.
#pragma mark - UIPageViewController Delegate Methods
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {
if( completed ) {
//...
if( currentIndex > lastIndex ) {
UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"Some page title"];
[[_someViewController navigationBar] pushNavigationItem:navigationItem animated:YES];
[[_someViewController pageControl] setCurrentPage:currentIndex];
} else {
_autoPop = YES; //We pop the item automatically from code.
[[_someViewController navigationBar] popNavigationItemAnimated:YES];
[[_someViewController pageControl] setCurrentPage:currentIndex];
}
}
}
So then I implement UINavigationBar delegate methods:
#pragma mark - UINavigationBar Delegate Methods
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
if( !_autoPop ) {
//Pop by back button tap
} else {
//Pop from code
}
_autoPop = NO;
return YES;
}
In this case I used shouldPopItem
because the pop is animated and I wanted to handle the back button immediately and not to wait until transition is finished.
Nobody likes the "refer to this answer" answers, but in this case it may help: Change an HTML5 input's placeholder color with CSS
Since it's only supported by a couple of browsers, you can try the jQuery placeholder plugin (assuming you can\are using jQuery). It allows you to style the placeholder text via CSS since it's really only a swap trick it does with focus events.
The plugin does not activate on browsers that support it, though, so you can have CSS that targets chrome\firefox and the jQuery plugin's CSS to catch the rest.
The plugin can be found here: https://github.com/mathiasbynens/jquery-placeholder
To facilitate potentially solving your problem given the information you've provided, I'm going to assume you're seeking dynamic CSS. If this is the case, you can use a server-side scripting language to do so. For example (and I absolutely love doing things like this):
styles.css.php:
body
{
margin: 0px;
font-family: Verdana;
background-color: #cccccc;
background-image: url('<?php
echo 'images/flag_bg/' . $user_country . '.png';
?>');
}
This would set the background image to whatever was stored in the $user_country variable. This is only one example of dynamic CSS; there are virtually limitless possibilities when combining CSS and server-side code. Another case would be doing something like allowing the user to create a custom theme, storing it in a database, and then using PHP to set various properties, like so:
user_theme.css.php:
body
{
background-color: <?php echo $user_theme['BG_COLOR']; ?>;
color: <?php echo $user_theme['COLOR']; ?>;
font-family: <?php echo $user_theme['FONT']; ?>;
}
#panel
{
font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
background-image: <?php echo $user_theme['PANEL_BG']; ?>;
}
Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.
One of my beloved is foreach:
for (${iterable_type} ${iterable_element} : ${iterable}) {
${cursor}
}
And traceout, since I'm using it a lot for tracking:
System.out.println("${enclosing_type}.${enclosing_method}()");
I just thought about another one and have found it over the Internet some day, const:
private static final ${type} ${name} = new ${type} ${cursor};
I found that along with setting the -p port values, Docker for Windows uses vpnkit and inbound traffic for it was disabled by default on my host machine's firewall. After enabling the inbound TCP rules for vpnkit I was able to access my containers from other machines on the local network.
Assuming your json object from your GET request looks like the one you posted above simply do:
let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
Or am I missing something that prevents you from doing it this way?
Do a cross-domain AJAX call
Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do
then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Check the following for more information
If the array is multidimensional, this will work great:
//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
if($data == null)
return null;
if(is_array($data)){
return array_map('trimData', $data);
}else return trim($data);
}
one sample test is like this:
$arr=[" aaa ", " b ", "m ", [" .e ", " 12 3", "9 0 0 0 "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )
As mentioned by @SalCelli, chrome://restart
works. However, this relaunches all the tabs.
Another method is to launch in incognito mode as suggested by CEGRD
However, if you could not like to restart & use incognito, on Chrome 86 (Mac), I found that the answer provided by @opsb & Mike only works with the below additional steps.
Enter the wrong username in the url without the resources
eg: if the url is http://mywebsite.com/resources/
, it will not work if I enter http://[email protected]/resources/
, but will work if I enter only http://[email protected]/
However, entering the valid credentials will not work, as in the background, chrome still send the wrong user as part of the url, even though the url appears right in the address bar When prompted for credentials you would need to Cancel
, and click the address bar and reload the page from pressing enter
. Now enter the correct password
You can create static class inside your controller like this :
@Controller
public class HomeController {
@Autowired
private LoginServiceConfiguration loginServiceConfiguration;
@RequestMapping(value = "/view", method = RequestMethod.GET)
public ModelAndView display(HttpServletRequest req) {
ModelAndView mav = new ModelAndView("home");
mav.addObject("loginAction", loginServiceConfiguration.loginAction());
return mav;
}
@Configuration
public static class LoginServiceConfiguration {
@Bean(name = "loginActionBean")
@Scope("prototype")
public LoginAction loginAction() {
return new LoginAction();
}
}
}
Instant
and LocalDateTime
are two entirely different animals: One represents a moment, the other does not.
Instant
represents a moment, a specific point in the timeline.LocalDateTime
represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment. It represents potential moments along a range of about 26 to 27 hours, the range of all time zones around the globe. A LocalDateTime
value is inherently ambiguous.
LocalDateTime
is rather date/clock representation including time-zones for humans.
Your statement is incorrect: A LocalDateTime
has no time zone. Having no time zone is the entire point of that class.
To quote that class’ doc:
This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.
So Local…
means “not zoned, no offset”.
Instant
An Instant
is a moment on the timeline in UTC, a count of nanoseconds since the epoch of the first moment of 1970 UTC (basically, see class doc for nitty-gritty details). Since most of your business logic, data storage, and data exchange should be in UTC, this is a handy class to be used often.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
OffsetDateTime
The class OffsetDateTime
class represents a moment as a date and time with a context of some number of hours-minutes-seconds ahead of, or behind, UTC. The amount of offset, the number of hours-minutes-seconds, is represented by the ZoneOffset
class.
If the number of hours-minutes-seconds is zero, an OffsetDateTime
represents a moment in UTC the same as an Instant
.
ZoneOffset
The ZoneOffset
class represents an offset-from-UTC, a number of hours-minutes-seconds ahead of UTC or behind UTC.
A ZoneOffset
is merely a number of hours-minutes-seconds, nothing more. A zone is much more, having a name and a history of changes to offset. So using a zone is always preferable to using a mere offset.
ZoneId
A time zone is represented by the ZoneId
class.
A new day dawns earlier in Paris than in Montréal, for example. So we need to move the clock’s hands to better reflect noon (when the Sun is directly overhead) for a given region. The further away eastward/westward from the UTC line in west Europe/Africa the larger the offset.
A time zone is a set of rules for handling adjustments and anomalies as practiced by a local community or region. The most common anomaly is the all-too-popular lunacy known as Daylight Saving Time (DST).
A time zone has the history of past rules, present rules, and rules confirmed for the near future.
These rules change more often than you might expect. Be sure to keep your date-time library's rules, usually a copy of the 'tz' database, up to date. Keeping up-to-date is easier than ever now in Java 8 with Oracle releasing a Timezone Updater Tool.
Specify a proper time zone name in the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
Time Zone = Offset + Rules of Adjustments
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
ZonedDateTime
Think of ZonedDateTime
conceptually as an Instant
with an assigned ZoneId
.
ZonedDateTime = ( Instant + ZoneId )
To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone):
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Pass a `ZoneId` object such as `ZoneId.of( "Europe/Paris" )`.
Nearly all of your backend, database, business logic, data persistence, data exchange should all be in UTC. But for presentation to users you need to adjust into a time zone expected by the user. This is the purpose of the ZonedDateTime
class and the formatter classes used to generate String representations of those date-time values.
ZonedDateTime zdt = instant.atZone( z ) ;
String output = zdt.toString() ; // Standard ISO 8601 format.
You can generate text in localized format using DateTimeFormatter
.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String outputFormatted = zdt.format( f ) ;
mardi 30 avril 2019 à 23 h 22 min 55 s heure de l’Inde
LocalDate
, LocalTime
, LocalDateTime
The "local" date time classes, LocalDateTime
, LocalDate
, LocalTime
, are a different kind of critter. The are not tied to any one locality or time zone. They are not tied to the timeline. They have no real meaning until you apply them to a locality to find a point on the timeline.
The word “Local” in these class names may be counter-intuitive to the uninitiated. The word means any locality, or every locality, but not a particular locality.
So for business apps, the "Local" types are not often used as they represent just the general idea of a possible date or time not a specific moment on the timeline. Business apps tend to care about the exact moment an invoice arrived, a product shipped for transport, an employee was hired, or the taxi left the garage. So business app developers use Instant
and ZonedDateTime
classes most commonly.
So when would we use LocalDateTime
? In three situations:
Notice that none of these three cases involve a single certain specific point on the timeline, none of these are a moment.
Sometimes we want to represent a certain time-of-day on a certain date, but want to apply that into multiple localities across time zones.
For example, "Christmas starts at midnight on the 25th of December 2015" is a LocalDateTime
. Midnight strikes at different moments in Paris than in Montréal, and different again in Seattle and in Auckland.
LocalDate ld = LocalDate.of( 2018 , Month.DECEMBER , 25 ) ;
LocalTime lt = LocalTime.MIN ; // 00:00:00
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ; // Christmas morning anywhere.
Another example, "Acme Company has a policy that lunchtime starts at 12:30 PM at each of its factories worldwide" is a LocalTime
. To have real meaning you need to apply it to the timeline to figure the moment of 12:30 at the Stuttgart factory or 12:30 at the Rabat factory or 12:30 at the Sydney factory.
Another situation to use LocalDateTime
is for booking future events (ex: Dentist appointments). These appointments may be far enough out in the future that you risk politicians redefining the time zone. Politicians often give little forewarning, or even no warning at all. If you mean "3 PM next January 23rd" regardless of how the politicians may play with the clock, then you cannot record a moment – that would see 3 PM turn into 2 PM or 4 PM if that region adopted or dropped Daylight Saving Time, for example.
For appointments, store a LocalDateTime
and a ZoneId
, kept separately. Later, when generating a schedule, on-the-fly determine a moment by calling LocalDateTime::atZone( ZoneId )
to generate a ZonedDateTime
object.
ZonedDateTime zdt = ldt.atZone( z ) ; // Given a date, a time-of-day, and a time zone, determine a moment, a point on the timeline.
If needed, you can adjust to UTC. Extract an Instant
from the ZonedDateTime
.
Instant instant = zdt.toInstant() ; // Adjust from some zone to UTC. Same moment, same point on the timeline, different wall-clock time.
Some people might use LocalDateTime
in a situation where the time zone or offset is unknown.
I consider this case inappropriate and unwise. If a zone or offset is intended but undetermined, you have bad data. That would be like storing a price of a product without knowing the intended currency (dollars, pounds, euros, etc.). Not a good idea.
For completeness, here is a table of all the possible date-time types, both modern and legacy in Java, as well as those defined by the SQL standard. This might help to place the Instant
& LocalDateTime
classes in a larger context.
Notice the odd choices made by the Java team in designing JDBC 4.2. They chose to support all the java.time times… except for the two most commonly used classes: Instant
& ZonedDateTime
.
But not to worry. We can easily convert back and forth.
Converting Instant
.
// Storing
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Instant instant = odt.toInstant() ;
Converting ZonedDateTime
.
// Storing
OffsetDateTime odt = zdt.toOffsetDateTime() ;
myPreparedStatement.setObject( … , odt ) ;
// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZone( z ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I was unable to find the direct download detailed in davidnr's post. You can download the ISO directly from the Microsoft Download Center here: https://download.microsoft.com/download/b/e/d/bedddfc4-55f4-4748-90a8-ffe38a40e89f/vs2015.3.com_enu.iso.
I resolved this problem by separating my content into two tables.
One table is the header row.
The seconds is also <table>
tag, but wrapped by <div>
with static height and overflow scroll.
This example works great.
<button onclick="genPDF()">Generate PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
function genPDF() {
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
doc.save('Test.pdf');
}
</script>
I Had the same issue earlier,removing Persist Security Info=True
from connectionstring worked for me.
A cleaner alternative would be to use a Dictionary
to handle parameters. They are key-value pairs after all.
private static readonly HttpClient httpclient;
static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}
var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);
var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
Also dont forget to Dispose()
httpclient, if you dont use the keyword using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
Edit:
You may want to look into response.EnsureSuccessStatusCode();
instead of if (response.StatusCode == HttpStatusCode.OK)
.
You may want to keep your httpclient and dont Dispose()
it. See: Do HttpClient and HttpClientHandler have to be disposed?
Edit:
Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);
This overload starts looking for the substring from the given index.
What worked for me was to create a new report from scratch.
This done and the new report working, I will compare the 2 .rdl files in Visual Studio. These are in XML format and I am hoping a quick WindDiff or something would reveal what the issue was.
An initial look shows there are 700 lines of code or a bit more difference between both files, with the larger of the 2 being the faulty file. A cursory look at the TablixHeader tags didn't reveal anything obvious.
But in my case it was a corrupted .rdl file. This was originally copied from a working report so in the process of removing what wasn't re-used, this could have corrupted it. However, other reports where this same process was done, the headers could repeat when the correct settings were made in Properties.
Hope this helps. If you've got a complex report, this isn't the quick fix but it works.
Perhaps comparing known good XML files to faulty ones on your end would make a good forum post. I'll be trying that on my end.
My BASIC interpreter chops beginning and ending quotes with
str->pop_back();
str->erase(str->begin());
Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert
if not:
assert(str->front() == '"' && str->back() == '"');
Just my two cents.
Explicitly specifying the max_iter
resolves the warning as the default max_iter
is 100. [For Logistic Regression].
logreg = LogisticRegression(max_iter=1000)
I have faced same problem ... For the problem is like this, I am calling the PRC inside cpp program and my PRC taking 4 arguments but while calling I used only 1 arguments so this error came for me.
Begin Example_PRC(:1); End; // this cause the problem
Begin Example_PRC(:1,:2,:3,:4); End; // this is the solution
If your working at a company, they may be preventing you from downloading outside software and installing it. You may need to install the plugins manually or repoint to an internal mirror repository.
You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:
function addCallbacks(eles){
eles.hover(function(){alert("gotcha!")});
}
$(document).ready(function(){
addCallbacks($(".myEles"))
});
// ... add elements ...
addCallbacks($(".myNewElements"))
Can I increase the heap memory to 75% of physical memory(6GB Heap).
Yes you can. In fact, you can increase to more than the amount of physical memory, if you want to.
Whether it is a good idea to do this depends on how much else is running on your system. In particular, if the "working set" of the applications and services that are currently running significantly exceeds the available physical memory, your system is liable to "thrash", spending a lot of time moving virtual memory pages to and from disk. The net effect is that the system gets horribly slow.
Please be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.
Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:
func yourHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("header_name", "header_value")
}
info registers
show registers.display $esp
continue display esp registers in gdb command line.layout regs
continue show registers, with TUI mode.It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
DocumentElement
is the root node of the document so childNodes[1]
doesn't exist in that document. childNodes[0]
would be the <Settings> node
Reason is the old database credentials are cached /bootstap/cache/config.php
In the .env file, I modified it as follow
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Then removed that file
/bootstap/cache/config.php
If the issue still there you might try the following.
php artisan config:clear php artisan cache:clear php artisan config:cache
Exit vagrant by writing the exit
command
Then restart vargarnt/homestead config
vagrant reload --provision
Then opened vagrant again
Vagrant Up
Vagrant ssh
Try with below setting in iptables.config table
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
Run the below command to restart the iptable service
service iptables restart
change the httpd.config file to
Listen 192.170.2.1:80
re-start the apache.
Try now.
<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>
This work for me.
edit: An example with your snippet:
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
.container {_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="row-fluid">_x000D_
<div class="span6 pull-left">_x000D_
<p>Text left</p>_x000D_
</div>_x000D_
<div class="span6 text-right">_x000D_
<p>text right</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Try this:
net use * /delete /y
The /y
key makes it select Yes in prompt silently
If for example you want to get the lines 10 to 20 of a file you can use each of these two methods:
head -n 20 york.txt | tail -11
or
sed -n '10,20p' york.txt
p
in above command stands for printing.
The best way to decide questions like this to benchmark them:
use strict;
use warnings;
use Benchmark qw(:all);
our @input_array = (0..1000);
my $a = sub {
my @array = @{[ @input_array ]};
my $index = 0;
foreach my $element (@array) {
die unless $index == $element;
$index++;
}
};
my $b = sub {
my @array = @{[ @input_array ]};
my $index = 0;
while (defined(my $element = shift @array)) {
die unless $index == $element;
$index++;
}
};
my $c = sub {
my @array = @{[ @input_array ]};
my $index = 0;
while (scalar(@array) !=0) {
my $element = shift(@array);
die unless $index == $element;
$index++;
}
};
my $d = sub {
my @array = @{[ @input_array ]};
foreach my $index (0.. $#array) {
my $element = $array[$index];
die unless $index == $element;
}
};
my $e = sub {
my @array = @{[ @input_array ]};
for (my $index = 0; $index <= $#array; $index++) {
my $element = $array[$index];
die unless $index == $element;
}
};
my $f = sub {
my @array = @{[ @input_array ]};
while (my ($index, $element) = each @array) {
die unless $index == $element;
}
};
my $count;
timethese($count, {
'1' => $a,
'2' => $b,
'3' => $c,
'4' => $d,
'5' => $e,
'6' => $f,
});
And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi
I get:
Benchmark: running 1, 2, 3, 4, 5, 6 for at least 3 CPU seconds...
1: 3 wallclock secs ( 3.16 usr + 0.00 sys = 3.16 CPU) @ 12560.13/s (n=39690)
2: 3 wallclock secs ( 3.18 usr + 0.00 sys = 3.18 CPU) @ 7828.30/s (n=24894)
3: 3 wallclock secs ( 3.23 usr + 0.00 sys = 3.23 CPU) @ 6763.47/s (n=21846)
4: 4 wallclock secs ( 3.15 usr + 0.00 sys = 3.15 CPU) @ 9596.83/s (n=30230)
5: 4 wallclock secs ( 3.20 usr + 0.00 sys = 3.20 CPU) @ 6826.88/s (n=21846)
6: 3 wallclock secs ( 3.12 usr + 0.00 sys = 3.12 CPU) @ 5653.53/s (n=17639)
So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.
@ikegami also points out that there are quite a few differences in these implimentations other than speed.
What I do with my TestNG, (sorry, JUnit doesn't support this) test cases is I can assign a group to the test I want to run
@Test(groups="broken")
And then simply run 'mvn -Dgroups=broken'.
Additionally to
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain.key
I also generated Certificate Authority (CA) certificate:
openssl pkcs12 -in domain.pfx -out domain-ca.crt -nodes -nokeys -cacerts
And included it in Apache config file:
<VirtualHost 192.168.0.1:443>
...
SSLEngine on
SSLCertificateFile /path/to/domain.cer
SSLCertificateKeyFile /path/to/domain.key
SSLCACertificateFile /path/to/domain-ca.crt
...
</VirtualHost>
I had a similar issue, but it was related to the element not being visible in the viewport. I took a screenshot and realized the browser window was too narrow and the element couldn't be seen. I did one of these and it worked:
driver.maximize_window()
The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.
LIB.EXE is the librarian for VS
http://msdn.microsoft.com/en-us/library/7ykb2k5f(VS.80).aspx
(like libtool on Unix)
sns.boxplot() function returns Axes(matplotlib.axes.Axes) object. please refer the documentation you can add title using 'set' method as below:
sns.boxplot('Day', 'Count', data=gg).set(title='lalala')
you can also add other parameters like xlabel, ylabel to the set method.
sns.boxplot('Day', 'Count', data=gg).set(title='lalala', xlabel='its x_label', ylabel='its y_label')
There are some other methods as mentioned in the matplotlib.axes.Axes documentaion to add tile, legend and labels.
For me, as of Google Chrome Version 46.0.2490.71 m, the Headers info area is a little hidden. To access:
While the browser is open, press F12 to access Web Developer tools
When opened, click the "Network" option
Initially, it is possible the page data is not present/up to date. Refresh the page if necessary
Observe the page information appears in the listing. (Also, make sure "All" is selected next to the "Hide data URLs" checkbox)
to check if url is online or offline ---
function get_http_response_code($theURL) {
$headers = @get_headers($theURL);
return substr($headers[0], 9, 3);
}
Unset is a function. Therefore you have to submit which variable has to be destroyed.
unset($var);
In your case
unset ($_SESSION["products"]);
If you need to reset whole session variable just call
session_destroy ();
If you have php installed on your local machine try:
$ php -a
Interactive shell
php > phpinfo();
Instead of:
DOCS="/cygdrive/c/Users/my\ dir/Documents"
Try:
DOCS="/cygdrive/c/Users/my dir/Documents"
This should work on any POSIX system.
is
operator : New in Django 1.10
{% if somevar is None %}
This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
extended the very nice solution "with format string" from JSmyth to also support
console.log
variations (log
,debug
,info
,warn
,error
)09:05:11.518
vs. 2018-06-13T09:05:11.518Z
)console
or its functions do not exist in browsers.
var Utl = {
consoleFallback : function() {
if (console == undefined) {
console = {
log : function() {},
debug : function() {},
info : function() {},
warn : function() {},
error : function() {}
};
}
if (console.debug == undefined) { // IE workaround
console.debug = function() {
console.info( 'DEBUG: ', arguments );
}
}
},
/** based on timestamp logging: from: https://stackoverflow.com/a/13278323/1915920 */
consoleWithTimestamps : function( getDateFunc = function(){ return new Date().toJSON() } ) {
console.logCopy = console.log.bind(console)
console.log = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.logCopy.apply(this, args)
} else this.logCopy(timestamp, args)
}
}
console.debugCopy = console.debug.bind(console)
console.debug = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.debugCopy.apply(this, args)
} else this.debugCopy(timestamp, args)
}
}
console.infoCopy = console.info.bind(console)
console.info = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.infoCopy.apply(this, args)
} else this.infoCopy(timestamp, args)
}
}
console.warnCopy = console.warn.bind(console)
console.warn = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.warnCopy.apply(this, args)
} else this.warnCopy(timestamp, args)
}
}
console.errorCopy = console.error.bind(console)
console.error = function() {
var timestamp = getDateFunc()
if (arguments.length) {
var args = Array.prototype.slice.call(arguments, 0)
if (typeof arguments[0] === "string") {
args[0] = "%o: " + arguments[0]
args.splice(1, 0, timestamp)
this.errorCopy.apply(this, args)
} else this.errorCopy(timestamp, args)
}
}
}
} // Utl
Utl.consoleFallback()
//Utl.consoleWithTimestamps() // defaults to e.g. '2018-06-13T09:05:11.518Z'
Utl.consoleWithTimestamps( function(){ return new Date().toJSON().replace( /^.+T(.+)Z.*$/, '$1' ) } ) // e.g. '09:05:11.518'
I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!
$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news);
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
}
else {
echo $news;
}
You can use this:
df.dropna(subset=['EPS'], how='all', inplace=True)
Utilize the <a>
tag.
At the top of your website, put an anchor with specified name.
<a name="top"></a>
Then your "back to top" link points to it.
<a href="#top">back to top</a>
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
The problem you'll face is that there's two types of PEM formatted keys: PKCS8 and SSLeay. It doesn't help that OpenSSL seems to use both depending on the command:
The usual openssl genrsa
command will generate a SSLeay format PEM. An export from an PKCS12 file with openssl pkcs12 -in file.p12
will create a PKCS8 file.
The latter PKCS8 format can be opened natively in Java using PKCS8EncodedKeySpec
. SSLeay formatted keys, on the other hand, can not be opened natively.
To open SSLeay private keys, you can either use BouncyCastle provider as many have done before or Not-Yet-Commons-SSL have borrowed a minimal amount of necessary code from BouncyCastle to support parsing PKCS8 and SSLeay keys in PEM and DER format: http://juliusdavies.ca/commons-ssl/pkcs8.html. (I'm not sure if Not-Yet-Commons-SSL will be FIPS compliant)
By inference from the OpenSSL man pages, key headers for two formats are as follows:
PKCS8 Format
Non-encrypted: -----BEGIN PRIVATE KEY-----
Encrypted: -----BEGIN ENCRYPTED PRIVATE KEY-----
SSLeay Format
-----BEGIN RSA PRIVATE KEY-----
(These seem to be in contradiction to other answers but I've tested OpenSSL's output using PKCS8EncodedKeySpec
. Only PKCS8 keys, showing ----BEGIN PRIVATE KEY-----
work natively)
with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#
but it still limited on so many aspect. And browser support is also not so ready.
your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:
Update Fragment from ViewPager
You need to implement getItemPosition(Object obj)
method.
This method is called when you call
notifyDataSetChanged()
on your ViewPagerAdaper
. Implicitly this method returns POSITION_UNCHANGED
value that means something like this:
"Fragment is where it should be so don't change anything."
So if you need to update Fragment you can do it with:
POSITION_NONE
from getItemPosition()
method. It which
means: "Fragment must be always recreated"Example of second approach:
public interface Updateable {
public void update();
}
public class MyFragment extends Fragment implements Updateable {
...
public void update() {
// do your stuff
}
}
And in FragmentPagerAdapter you'll do something like this:
@Override
public int getItemPosition(Object object) {
MyFragment f = (MyFragment ) object;
if (f != null) {
f.update();
}
return super.getItemPosition(object);
}
And if you'll choose first approach it can looks like:
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Note: It's worth to think a about which approach you'll pick up.
for me i found some solutions: it is a working solution
@echo off
title a game for youtube
explorer "https://thepythoncoding.blogspot.com/2020/11/how-to-echo-with-different-colors-in.html"
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
echo say the name of the colors, don't read
call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"
goto :Beginoffile
:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof
:Beginoffile
You could try changing the button attribute like this:
element.setAttribute( "onClick", "javascript: Boo();" );
If you need to be able to switch between more than two versions at a time, you can use the following to change the version of PHP manually.
MAMP automatically rewrites the following line in your /Applications/MAMP/conf/apache/httpd.conf file when it restarts based on the settings in preferences. You can comment out this line and add the second one to the end of your file:
# Comment this out just under all the modules loaded
# LoadModule php5_module /Applications/MAMP/bin/php/php5.x.x/modules/libphp5.so
At the bottom of the httpd.conf file, you'll see where additional configurations are loaded from the extra folder. Add this to the bottom of the httpd.conf file
# PHP Version Change
Include /Applications/MAMP/conf/apache/extra/httpd-php.conf
Then create a new file here: /Applications/MAMP/conf/apache/extra/httpd-php.conf
# Uncomment the version of PHP you want to run with MAMP
# LoadModule php5_module /Applications/MAMP/bin/php/php5.2.17/modules/libphp5.so
# LoadModule php5_module /Applications/MAMP/bin/php/php5.3.27/modules/libphp5.so
# LoadModule php5_module /Applications/MAMP/bin/php/php5.4.19/modules/libphp5.so
LoadModule php5_module /Applications/MAMP/bin/php/php5.5.3/modules/libphp5.so
After you have this setup, just uncomment the version of PHP you want to use and restart the servers!
col-xs-*
have been dropped in Bootstrap 4 in favor of col-*
.
Replace col-xs-12
with col-12
and it will work as expected.
Also note col-xs-offset-{n}
were replaced by offset-{n}
in v4.
I was looking for the same answer to this question and after much head scratching this is the answer I came up with:
#Python 3.4.3 with Pygame
import pygame
pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))
# Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
# Mouse position and button clicking.
pos = pygame.mouse.get_pos()
pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
# Check if the rect collided with the mouse pos
# and if the left mouse button was pressed.
if Rectplace.collidepoint(pos) and pressed1:
print("You have opened a chest!")
# Quit pygame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit(1)
While the official docs are happy not to provide switch, I have seen a solution using dictionaries.
For example:
# define the function blocks
def zero():
print "You typed zero.\n"
def sqr():
print "n is a perfect square\n"
def even():
print "n is an even number\n"
def prime():
print "n is a prime number\n"
# map the inputs to the function blocks
options = {0 : zero,
1 : sqr,
4 : sqr,
9 : sqr,
2 : even,
3 : prime,
5 : prime,
7 : prime,
}
Then the equivalent switch block is invoked:
options[num]()
This begins to fall apart if you heavily depend on fall through.
In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]:
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
Add this to your NodeJS Server below imports:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.
This can be resolved by specifying a primary key on the @new_super table, as follows:
DECLARE @new_super TABLE (
row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
super_id int
);
This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.
@theczechsensation's solution is already half way there.
For those who like to exclude noisy log messages and keep the log to their app only this is the solution:
Add your exclusions to Log Tag like this: ^(?!(eglCodecCommon|tagToExclude))
Add your package name or prefix to Package Name: com.mycompany.
This way it is possible to filter for as many strings you like and keep the log to your package.
There is no hard and fast rule.
Here are some rules to make code thread safe in .NET and why these are not good rules:
lock
on a common thing. All locks must be done in same order. This will make the code thread safe, but it will be incredibly slow, and you might as well not use multiple threads.There is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location, and this for each function (static or otherwise) that is accessing common objects.
The autoload config does start below the vendor dir. So you might want change the vendor dir, e.g.
{
"config": {
"vendor-dir": "../vendor/"
},
"autoload": {
"psr-0": {"AppName": "src/"}
}
}
Or isn't this possible in your project?
In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account. The quick fix:
sudo rm ~/.rnd
For more information, here's the entry from the OpenSSL FAQ:
Sometimes the openssl command line utility does not abort with a "PRNG not seeded" error message, but complains that it is "unable to write 'random state'". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file ".rnd" in the current directory in this case, but this has changed with 0.9.6a.)
So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem.
If everything seems to be in order, you could try running with strace and see what exactly is going on.
I'm the maintainer of Mongoose. The more modern way to upsert a doc is to use the Model.updateOne()
function.
await Contact.updateOne({
phone: request.phone
}, { status: request.status }, { upsert: true });
If you need the upserted doc, you can use Model.findOneAndUpdate()
const doc = await Contact.findOneAndUpdate({
phone: request.phone
}, { status: request.status }, { upsert: true });
The key takeaway is that you need to put the unique properties in the filter
parameter to updateOne()
or findOneAndUpdate()
, and the other properties in the update
parameter.
Here's a tutorial on upserting documents with Mongoose.
Simple way to compare time is :
$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
// your code
}
If you're using ngRoute, you can inject $routeParams
into your controller
http://docs.angularjs.org/api/ngRoute/service/$routeParams
If you're using angular-ui-router, you can inject $stateParams
You can look at Open Source QR Code Library or messagingtoolkit-qrcode. I have not used either of them so I can not speak of their ease to use.
If you look at the docs for bytes
, it points you to bytearray
:
bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.
The optional source parameter can be used to initialize the array in a few different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
So bytes
can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.
For encoding a string, I think that some_string.encode(encoding)
is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding)
-- there is no explicit verb when you use the constructor.
Edit: I checked the Python source. If you pass a unicode string to bytes
using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode
; so you're just skipping a level of indirection if you call encode
yourself.
Also, see Serdalis' comment -- unicode_string.encode(encoding)
is also more Pythonic because its inverse is byte_string.decode(encoding)
and symmetry is nice.
Strong pattern matching — This is the method that I use here at Perishable Press. Using strong pattern matching, this technique prevents external access to any file containing “.hta”, “.HTA”, or any case-insensitive combination thereof. To illustrate, this code will prevent access through any of the following requests:
..etc., etc. Clearly, this method is highly effective at securing your site’s HTAccess files. Further, this technique also includes the fortifying “Satisfy All” directive. Note that this code should be placed in your domain’s root HTAccess file:
# STRONG HTACCESS PROTECTION
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
If you want to prompt the user to select a file, then read its contents:
// read the contents of a file input
const readInputFile = (inputElement, callback) => {
const reader = new FileReader();
reader.onload = () => {
callback(reader.result)
};
reader.readAsText(inputElement.files[0]);
};
// create a file input and destroy it after reading it
export const openFile = (callback) => {
var el = document.createElement('input');
el.setAttribute('type', 'file');
el.style.display = 'none';
document.body.appendChild(el);
el.onchange = () => {readInputFile(el, (data) => {
callback(data)
document.body.removeChild(el);
})}
el.click();
}
Usage:
// prompt the user to select a file and read it
openFile(data => {
console.log(data)
})
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
Arrow looks promising for this:
>>> import arrow
>>> arrow.get('2014-11-13T14:53:18.694072+00:00').datetime
datetime.datetime(2014, 11, 13, 14, 53, 18, 694072, tzinfo=tzoffset(None, 0))
Arrow is a Python library that provides a sensible, intelligent way of creating, manipulating, formatting and converting dates and times. Arrow is simple, lightweight and heavily inspired by moment.js and requests.
Exotic Windows Solution
import subprocess
subprocess.run("powershell Invoke-WebRequest {} -OutFile {}".format(your_url, filename), shell=True)
HttpClient is not supported any more in sdk 23. Android 6.0 (API Level 23) release removes support for the Apache HTTP client. You have to use
android {
useLibrary 'org.apache.http.legacy'
.
.
.
and also add below code snippet in your dependency :
//http final solution for web-service (including file uploading)
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
It will also help you while you use Use MultipartEntity for File upload.
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
Not sure if this is the best way, but it works.
if (cartDiv == null) {
cartDiv = "<div id='unique_id'></div>"; // document.createElement('div');
document.body.appendChild(cartDiv);
}
If all the previous answers didn't give any solution, you should check your user privileges.
If you could login as root
to mysql
then you should add this:
CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY '***';
GRANT ALL PRIVILEGES ON * . * TO 'root'@'192.168.1.100' IDENTIFIED BY '***' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100
. It should work.
You can invoke private method with reflection. Modifying the last bit of the posted code:
Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);
There are a couple of caveats. First, getDeclaredMethod
will only find method declared in the current Class
, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a SecurityManager
can prevent use of the setAccessible
method. So, it may need to run as a PrivilegedAction
(using AccessController
or Subject
).
Hope this will help.
input[readonly="readonly"]
{
background-color:blue;
}
reference:
you can use
var match=myList.Where(item=>item.Contains("Required String"));
foreach(var i in match)
{
//do something with the matched items
}
LINQ provides you with capabilities to "query" any collection of data. You can use syntax like a database query (select, where, etc) on a collection (here the collection (list) of strings).
so you are doing like "get me items from the list Where it satisfies a given condition"
inside the Where you are using a "lambda expression"
to tell briefly lambda expression is something like (input parameter => return value)
so for a parameter "item", it returns "item.Contains("required string")" . So it returns true if the item contains the string and thereby it gets selected from the list since it satisfied the condition.
you try this way
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
and
useEffect(() => {
fetchBusinesses();
});
it's work for you. But my suggestion is try this way also work for you. It's better than before way. I use this way:
useEffect(() => {
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
fetchBusinesses();
}, []);
if you get data on the base of specific id then add in callback useEffect [id]
then cannot show you warning
React Hook useEffect has a missing dependency: 'any thing'. Either include it or remove the dependency array
Why not just try loading all the files in the folder? If OpenCV can't open it, oh well. Move on to the next. cv2.imread()
returns None
if the image can't be opened. Kind of weird that it doesn't raise an exception.
import cv2
import os
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder,filename))
if img is not None:
images.append(img)
return images
There are two formats of case expression. You can do CASE
with many WHEN
as;
CASE WHEN Col1 = 1 OR Col3 = 1 THEN 1
WHEN Col1 = 2 THEN 2
...
ELSE 0 END as Qty
Or a Simple CASE
expression
CASE Col1 WHEN 1 THEN 11 WHEN 2 THEN 21 ELSE 13 END
Or CASE
within CASE
as;
CASE WHEN Col1 < 2 THEN
CASE Col2 WHEN 'X' THEN 10 ELSE 11 END
WHEN Col1 = 2 THEN 2
...
ELSE 0 END as Qty
It's Very important to know that android studio has two type of import
and our problem with android import type as import android.R
it's work good? but you did't import android.R?
android studio add this automatic but with different syntax
to solve our problem
and Easily copy the all contents of you Activity java class
"Don't copy modules and package only copy the content of class"
and don't forget to add extends .... to your class
you will see message ask you to import some of modules
you must deselect android.R and press OK
it's will work correctly
" If you find android.R only at the dialog box you must click cancel"
//See Next Image
Select Class To Import if you don't know exactly where the java class file which cased this problem do this solution with all java file in your project
//Good Luck @ ABT
version for data.table based on code from dmanuge :
convNumValues<-function(ds){
ds<-data.table(ds)
dsnum<-data.table(data.matrix(ds))
num_cols <- sapply(dsnum,function(x){mean(as.numeric(is.na(x)))<0.5})
nds <- data.table( dsnum[, .SD, .SDcols=attributes(num_cols)$names[which(num_cols)]]
,ds[, .SD, .SDcols=attributes(num_cols)$names[which(!num_cols)]] )
return(nds)
}
Plain HTML does not support this. You'll need to use some JavaScript code.
Also, note that large parts of the world are using a popup blocker nowadays. You may want to reconsider your design!
How about writing a custom attribute:
public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
public LocalizedDisplayNameAttribute(string resourceId)
: base(GetMessageFromResource(resourceId))
{ }
private static string GetMessageFromResource(string resourceId)
{
// TODO: Return the string from the resource file
}
}
which could be used like this:
public class MyModel
{
[Required]
[LocalizedDisplayName("labelForName")]
public string Name { get; set; }
}
You can pip install pickle by running command pip install pickle-mixin
.
Proceed to import it using import pickle
.
This can be then used normally.
Here is a method for getting a random color:
private static Random sRandom;
public static synchronized int randomColor() {
if (sRandom == null) {
sRandom = new Random();
}
return 0xff000000 + 256 * 256 * sRandom.nextInt(256) + 256 * sRandom.nextInt(256)
+ sRandom.nextInt(256);
}
Benefits:
java.awt.Color
or android.graphics.Color
Random
.I ran across this error recently using a javascript library which changes the parameters of a function based on conditions.
You can test an object to see if it has the function. I would only do this in scenarios where you don't control what is getting passed to you.
if( param.indexOf != undefined ) {
// we have a string or other object that
// happens to have a function named indexOf
}
You can test this in your browser console:
> (3).indexOf == undefined;
true
> "".indexOf == undefined;
false
If you use the Geolocation API, it would be as simple as using the following code.
navigator.geolocation.getCurrentPosition(function(location) {
console.log(location.coords.latitude);
console.log(location.coords.longitude);
console.log(location.coords.accuracy);
});
You may also be able to use Google's Client Location API.
This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.
Fix it by install metro-config of the latest version (0.57.0 for now) they had fixed the problem:
npm install metro-config
you can remove it later, after react-native guys update module versions
You could try to "weight" certain columns, like this:
<table border="1" style="width: 100%;">
<colgroup>
<col width="80%" />
<col width="20%" />
</colgroup>
<tr>
<td>This cell has more content.</td>
<td>Less content here.</td>
</tr>
</table>
You can also try some more interesting tweaks, like using 0%-width columns and using some combination of the white-space
CSS property.
<table border="1" style="width: 100%;">
<colgroup>
<col width="100%" />
<col width="0%" />
</colgroup>
<tr>
<td>This cell has more content.</td>
<td style="white-space: nowrap;">Less content here.</td>
</tr>
</table>
You get the idea.
Try to use this:
using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
{
//add parameters on request
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("test", "test"),
new KeyValuePair<string, string>("test1", "test1")
};
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
//client.DefaultRequestHeaders.Add("Accept", "*/*");
client.Timeout = TimeSpan.FromMilliseconds(10000);
var res = await client.PostAsync("", new FormUrlEncodedContent(body));
if (res.IsSuccessStatusCode)
{
var exec = await res.Content.ReadAsStringAsync();
Console.WriteLine(exec);
}
}
}
What worked for me:
adb kill-server
chrome://inspect/#devices
windows/tabsadb start-server
adb devices
Another alternative is using SDKMAN! See https://wimdeblauwe.wordpress.com/2018/09/26/switching-between-jdk-8-and-11-using-sdkman/
First install SDKMAN: https://sdkman.io/install and then...
sdk install java 8.0.181-oracle
sdk install java 11.0.0-open
To switch:
sdk use java 8.0.181-oracle
sdk use java 11.0.0-open
To set a default:
sdk default java 8.0.181-oracle
sdk default java 11.0.0-open
The easiest way is to use python-memcached-stats package, https://github.com/abstatic/python-memcached-stats
The keys() method should get you going.
Example -
from memcached_stats import MemcachedStats
mem = MemcachedStats()
mem.keys()
['key-1',
'key-2',
'key-3',
... ]
It looks like you are trying to use (almost) straight up C code here. Go has a few differences.
const
. The term const
has a different meaning in Go, as it does in C. The list should be defined as var
instead.basenameOpts
as opposed to basename_opts
.char
type in Go. You probably want byte
(or rune
if you intend to allow unicode codepoints).var x = foo
.For example:
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts = []opt {
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
An alternative is to declare the list with its type and then use an init
function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init
functions are run when the program is being initialized and are guaranteed to finish before main
is executed. You can have multiple init
functions in a package, or even in the same source file.
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts []opt
func init() {
basenameOpts = []opt{
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
}
Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.
It clutters your namespace, requiring you to fully specify any classnames that are ambiguous. The most common occurence of this is with:
import java.util.*;
import java.awt.*;
...
List blah; // Ambiguous, needs to be qualified.
It also helps make your dependencies concrete, as all of your dependencies are listed at the top of the file.
On the windows platform, I met that problem too The solution for me is just add
C:\Windows\System32
to the PATH
and restart the computer.
In Sublime Text, after you select multiple regions of text, a click is considered a way to exit the multi-select mode. Move the cursor with the keyboard keys (arrows, Ctrl+arrows, etc.) instead, and you'll be fine
I'm not sure why, but I needed to use the old skool document.getElementById();
<audio id="player" src="http://audio.micronemez.com:8000/micronemez-radio.ogg"> </audio>
<a id="button" title="button">play sound</a>
and the JS:
$(document).ready(function() {
var playing = false;
$('a#button').click(function() {
$(this).toggleClass("down");
if (playing == false) {
document.getElementById('player').play();
playing = true;
$(this).text("stop sound");
} else {
document.getElementById('player').pause();
playing = false;
$(this).text("restart sound");
}
});
});
Check out an example: http://jsfiddle.net/HY9ns/1/
It's compiling because printf
isn't type safe, since it uses variable arguments in the C sense1. printf
has no option for std::string
, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.
The easiest way to fix this, since you're using C++, is printing it normally with std::cout
, since std::string
supports that through operator overloading:
std::cout << "Follow this command: " << myString;
If, for some reason, you need to extract the C-style string, you can use the c_str()
method of std::string
to get a const char *
that is null-terminated. Using your example:
#include <iostream>
#include <string>
#include <stdio.h>
int main()
{
using namespace std;
string myString = "Press ENTER to quit program!";
cout << "Come up and C++ me some time." << endl;
printf("Follow this command: %s", myString.c_str()); //note the use of c_str
cin.get();
return 0;
}
If you want a function that is like printf
, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format
.
[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf
, that means a string with encoded type information like %d
meaning int
. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.
Its based on from which file you are trying to access those files.
If it is in the same folder where your working project file is, then you can use just the file name. no need of path.
If it is in the another folder which is under the same parent folder of your working project file then you can use location like in the following /javascript/sample.js
In your example if you are trying to access your js file from your html file you can use the following location
../javascript/sample.js
the prefix../ will go to the parent folder of the file(Folder upward journey)
It seems that the compiler is better in optimizing a switch-statement than an if-statement.
The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.
Here's a small comparison:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx
You can also use format function. Which can also implicitly take care of type conversion of text, int, etc by itself.
create or replace function concat_return_row_count(tbl_name text, column_name text, value int)
returns integer as $row_count$
declare
total integer;
begin
EXECUTE format('select count(*) from %s WHERE %s = %s', tbl_name, column_name, value) INTO total;
return total;
end;
$row_count$ language plpgsql;
postgres=# select concat_return_row_count('tbl_name','column_name',2); --2 is the value