I can't comment on ars's answer, but I actually got Roland Tapken's code running using QtWebkit and it works quite well.
Just wanted to confirm that what Roland posts on his blog works great on Ubuntu. Our production version ended up not using any of what he wrote but we are using the PyQt/QtWebKit bindings with much success.
Note: The URL used to be: http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/ I've updated it with a working copy.
Here is a solution using hooks, Timer component, I'm replicating same logic above with hooks
import React from 'react'
import { useState, useEffect } from 'react';
const Timer = (props:any) => {
const {initialMinute = 0,initialSeconds = 0} = props;
const [ minutes, setMinutes ] = useState(initialMinute);
const [seconds, setSeconds ] = useState(initialSeconds);
useEffect(()=>{
let myInterval = setInterval(() => {
if (seconds > 0) {
setSeconds(seconds - 1);
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(myInterval)
} else {
setMinutes(minutes - 1);
setSeconds(59);
}
}
}, 1000)
return ()=> {
clearInterval(myInterval);
};
});
return (
<div>
{ minutes === 0 && seconds === 0
? null
: <h1> {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
}
</div>
)
}
export default Timer;
There are several possibilities:
stdout
.stderr
.stdin
.Server:
namespace SocketServer
{
class Program
{
static Socket klient;
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888);
server.Bind(endPoint);
server.Listen(20);
while(true)
{
Console.WriteLine("Waiting...");
klient = server.Accept();
Console.WriteLine("Client connected");
Task t = new Task(ServisClient);
t.Start();
}
}
static void ServisClient()
{
try
{
while (true)
{
byte[] buffer = new byte[64];
Console.WriteLine("Waiting for answer...");
klient.Receive(buffer, 0, buffer.Length, 0);
string message = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Answer: " + message);
string answer = "Actualy date is " + DateTime.Now;
buffer = Encoding.UTF8.GetBytes(answer);
Console.WriteLine("Sending {0}", answer);
klient.Send(buffer);
}
}
catch
{
Console.WriteLine("Disconnected");
}
}
}
}
You can have a regular Python module, say config.py, like this:
truck = dict(
color = 'blue',
brand = 'ford',
)
city = 'new york'
cabriolet = dict(
color = 'black',
engine = dict(
cylinders = 8,
placement = 'mid',
),
doors = 2,
)
and use it like this:
import config
print(config.truck['color'])
Try using - declare let $ :any;
or import * as $ from 'jquery/dist/jquery.min.js'; provide exact path of the lib
CSS
If this doesn't work:
.modal-backdrop {
background-color: red;
}
try this:
.modal {
background-color: red !important;
}
Open the Servers view -> double click tomcat -> drop down the Timeouts section
There you can increase the startup time for each particular server.
If Vagrantfile
as below:
config.ssh.username = 'root'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'
But vagrant still ask you root password, most likely the base box you used do not configured to allow root login.
For example, the offical ubuntu14.04 box do not set PermitRootLogin yes
in /etc/ssh/sshd_config
.
So If you want a box can login as root default(only Vagrantfile, no more work), you have to :
Setup a vm by username vagrant
(whatever name but root)
Login and edit sshd config file.
ubuntu: edit /etc/ssh/sshd_config
, set PermitRootLogin yes
others: ....
(I only use ubuntu, feel free to add workaround of other platforms)
Build a new base box:
vagrant package --base your-vm-name
this create a file package.box
Add that base box to vagrant:
vagrant box add ubuntu-root file:///somepath/package.box
then, you need use this base box to build vm which allow auto login as root.
Destroy original vm by vagrant destroy
Edit original Vagrantfile
, change box name to ubuntu-root
and username to root
, then vagrant up
create a new one.
It cost me some time to figure out , it is too complicate in my opinion. Hope vagrant would improve this.
The source for String.valueOf shows this:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Not that it matters much, but I would use toString.
Copying the ".txt" file from one folder to another is very simple and question contains the logic. Only missing part is substituting with right information as below:
import os, shutil, glob
src_fldr = r"Source Folder/Directory path"; ## Edit this
dst_fldr = "Destiantion Folder/Directory path"; ## Edit this
try:
os.makedirs(dst_fldr); ## it creates the destination folder
except:
print "Folder already exist or some error";
below lines of code will copy the file with *.txt extension files from src_fldr to dst_fldr
for txt_file in glob.glob(src_fldr+"\\*.txt"):
shutil.copy2(txt_file, dst_fldr);
I have also been through this problem,
First i tried setting my password of root to blank using command :
SET PASSWORD FOR root@localhost=PASSWORD('');
But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.
SET PASSWORD FOR [email protected]=PASSWORD('');
Just replace localhost with 127.0.0.1 and you are done .
Maybe you can filter rows by possible columns like this :
DataRow[] filteredRows =
datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));
Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch;
somewhere in your CSS.
The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch;
or putting -webkit-overflow-scrolling: auto;
with
NoviceCoding's solution.
Borrowing, slightly enhancing and simplifying from this Blog post the following simple SQL statement seems to do the job quite well:
SELECT DISTINCT (:val) "Search Value", TABLE_NAME "Table", COLUMN_NAME "Column"
FROM cols,
TABLE (XMLSEQUENCE (DBMS_XMLGEN.GETXMLTYPE(
'SELECT "' || COLUMN_NAME || '" FROM "' || TABLE_NAME || '" WHERE UPPER("'
|| COLUMN_NAME || '") LIKE UPPER(''%' || :val || '%'')' ).EXTRACT ('ROWSET/ROW/*')))
ORDER BY "Table";
So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.
The basic idea is to signal the reader to split on the carriage character "\n"
(or "\r\n"
for Windows). Python can do this with the file.readline()
function.
import json
def json_reader(filename):
with open(filename) as f:
for line in f:
yield json.loads(line)
However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.
def json_writer(file, json_objects):
with open(file, "w") as f:
for jsonobj in json_objects:
jsonstr = json.dumps(jsonobj)
f.write(jsonstr + "\n")
You could also do the same operation with file.writelines()
and a list comprehension:
...
json_strs = [json.dumps(j) + "\n" for j in json_objects]
f.writelines(json_strs)
...
And if you wanted to append the data instead of writing a new file just change open(file, "w")
to open(file, "a")
.
In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.
On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write
lst = list(json_reader(file))
Have them try to write a program that can evaluate arbitrary simple arithmetic expressions. This is a simple problem to understand but as you start getting deeper into it a lot of basic parsing starts to make sense.
I usually do this to switch back and forth between forms.
Firstly, in Program file I keep ApplicationContext and add a helper SwitchMainForm method.
static class Program
{
public static ApplicationContext AppContext { get; set; }
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Save app context
Program.AppContext = new ApplicationContext(new LoginForm());
Application.Run(AppContext);
}
//helper method to switch forms
public static void SwitchMainForm(Form newForm)
{
var oldMainForm = AppContext.MainForm;
AppContext.MainForm = newForm;
oldMainForm?.Close();
newForm.Show();
}
}
Then anywhere in the code now I call SwitchMainForm method to switch easily to the new form.
// switch to some other form
var otherForm = new MyForm();
Program.SwitchMainForm(otherForm);
Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,
public class PersonHelper
{
public static Person person;
}
I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.
If you need to tolerate decimal point and thousand marker
var regex = new Regex(@"^-?[0-9][0-9,\.]+$");
You will need a "-", if the number can go negative.
This is a very simple to create file in git bash at first write touch then file name with extension
for example
touch filename.extension
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
Instead of disabled
, you could consider using readonly
. With some extra CSS you can style the input so it looks like an disabled
field.
There is actually another problem. The event change
only triggers when the element looses focus, which is not logic considering an disabled
field. Probably you are pushing data into this field from another call. To make this work you can use the event 'bind'.
$('form').bind('change', 'input', function () {
console.log('Do your thing.');
});
var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];
for(var i in jsonData){
var key = i;
var val = jsonData[i];
for(var j in val){
var sub_key = j;
var sub_val = val[j];
console.log(sub_key);
}
}
EDIT
var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj); // returns ["person", "age"]
Object
has a property
keys
, returns an Array
of keys from that Object
Chrome, FF & Safari supports Object.keys
I just added H:i:s to Rocket's answer to get the time along with the date.
echo date('m/d/Y H:i:s', 1299446702);
Output: 03/06/2011 16:25:02
Instant.now() // Capture the current moment in UTC.
.atZone( ZoneId.systemDefault() ) // Adjust into the JVM's current default time zone. Same moment, different wall-clock time. Produces a `ZonedDateTime` object.
.toInstant() // Extract a `Instant` (always in UTC) object from the `ZonedDateTime` object.
.atZone( ZoneId.of( "Europe/Paris" ) ) // Adjust the `Instant` into a specific time zone. Renders a `ZonedDateTime` object. Same moment, different wall-clock time.
.toInstant() // And back to UTC again.
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes (Date
, Calendar
, etc.).
Your use of the word "local" contradicts the usage in the java.time class. In java.time, "local" means any locality or all localities, but not any one particular locality. The java.time classes with names starting with "Local…" all lack any concept of time zone or offset-from-UTC. So they do not represent a specific moment, they are not a point on the timeline, whereas your Question is all about moments, points on the timeline viewed through various wall-clock times.
Get the current system time (local time)
If you want to capture the current moment in UTC, use Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Adjust into a time zone by applying a ZoneId
to get a ZonedDateTime
. Same moment, same point on the timeline, different wall-clock time.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
As a shortcut, you can skip the usage of Instant
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Convert Local time to UTC // Works Fine Till here
You can adjust from the zoned date-time to UTC by extracting an Instant
from a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Instant instant = zdt.toInstant() ;
Reverse the UTC time, back to local time.
As shown above, apply a ZoneId
to adjust the same moment into another wall-clock time used by the people of a certain region (a time zone).
Instant instant = Instant.now() ; // Capture current moment in UTC.
ZoneId zDefault = ZoneId.systemDefault() ; // The JVM's current default time zone.
ZonedDateTime zdtDefault = instant.atZone( zDefault ) ;
ZoneId zTunis = ZoneId.of( "Africa/Tunis" ) ; // The JVM's current default time zone.
ZonedDateTime zdtTunis = instant.atZone( zTunis ) ;
ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ; // The JVM's current default time zone.
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;
Going back to UTC from a zoned date-time, call ZonedDateTime::toInstant
. Think of it conceptually as: ZonedDateTime = Instant + ZoneId.
Instant instant = zdtAuckland.toInstant() ;
All of these objects, the Instant
and the three ZonedDateTime
objects all represent the very same simultaneous moment, the same point in history.
Followed 3 different approaches (listed below) but all the 3 approaches retains the time in UTC only.
Forget about trying to fix code using those awful Date
, Calendar
, and GregorianCalendar
classes. They are a wretched mess of bad design and flaws. You need never touch them again. If you must interface with old code not yet updated to java.time, you can convert back-and-forth via new conversion methods added to the old classes.
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
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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.
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.
std::string::data
would seem to be sufficient and most efficient. If you want to have non-const memory to manipulate (strange for encryption) you can copy the data to a buffer using memcpy:
unsigned char buffer[mystring.length()];
memcpy(buffer, mystring.data(), mystring.length());
STL fanboys would encourage you to use std::copy instead:
std::copy(mystring.begin(), mystring.end(), buffer);
but there really isn't much of an upside to this. If you need null termination use std::string::c_str()
and the various string duplication techniques others have provided, but I'd generally avoid that and just query for the length
. Particularly with cryptography you just know somebody is going to try to break it by shoving nulls in to it, and using std::string::data()
discourages you from lazily making assumptions about the underlying bits in the string.
They are pre-compiled (once), so faster for repeated execution of dynamic SQL (where parameters change)
Database statement caching boosts DB execution performance
Databases store caches of execution plans for previously executed statements. This allows the database engine to reuse the plans for statements that have been executed previously. Because PreparedStatement uses parameters, each time it is executed it appears as the same SQL, the database can reuse the previous access plan, reducing processing. Statements "inline" the parameters into the SQL string and so do not appear as the same SQL to the DB, preventing cache usage.
Binary communications protocol means less bandwidth and faster comms calls to DB server
Prepared statements are normally executed through a non-SQL binary protocol. This means that there is less data in the packets, so communications to the server is faster. As a rule of thumb network operations are an order of magnitude slower than disk operations which are an order of magnitude slower than in-memory CPU operations. Hence, any reduction in amount of data sent over the network will have a good effect on overall performance.
They protect against SQL injection, by escaping text for all the parameter values provided.
They provide stronger separation between the query code and the parameter values (compared to concatenated SQL strings), boosting readability and helping code maintainers quickly understand inputs and outputs of the query.
In java, can call getMetadata() and getParameterMetadata() to reflect on the result set fields and the parameter fields, respectively
In java, intelligently accepts java objects as parameter types via setObject, setBoolean, setByte, setDate, setDouble, setDouble, setFloat, setInt, setLong, setShort, setTime, setTimestamp - it converts into JDBC type format that is comprehendible to DB (not just toString() format).
In java, accepts SQL ARRAYs, as parameter type via setArray method
In java, accepts CLOBs, BLOBs, OutputStreams and Readers as parameter "feeds" via setClob/setNClob, setBlob, setBinaryStream, setCharacterStream/setAsciiStream/setNCharacterStream methods, respectively
In java, allows DB-specific values to be set for SQL DATALINK, SQL ROWID, SQL XML, and NULL via setURL, setRowId, setSQLXML ans setNull methods
In java, inherits all methods from Statement. It inherits the addBatch method, and additionally allows a set of parameter values to be added to match the set of batched SQL commands via addBatch method.
In java, a special type of PreparedStatement (the subclass CallableStatement) allows stored procedures to be executed - supporting high performance, encapsulation, procedural programming and SQL, DB administration/maintenance/tweaking of logic, and use of proprietary DB logic & features
Try this
<head>
<style type ="text/css" >
.footer{
position: fixed;
text-align: center;
bottom: 0px;
width: 100%;
}
</style>
</head>
<body>
<div class="footer">All Rights Reserved</div>
</body>
If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:
CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();
it should be slightly faster since it doesn't need to parse an input format.
Another approach to count number of list elements:
var num = $("#menu").find("li").length;_x000D_
if (num > 1) {_x000D_
console.log(num);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul id="menu">_x000D_
<li>Element 1</li>_x000D_
<li>Element 2</li>_x000D_
<li>Element 3</li>_x000D_
</ul>
_x000D_
I know that this has been answered, but it's at least useful to note that you can use:
http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx
Which will not give you a "unique id" directly, but combined with WeakReferences (and a hashset?) could give you a pretty easy way of tracking various instances.
This was my scenario:
for i in generate_numbers():
do_something(i)
# Use the last i.
I can’t easily determine the length of the iterable, and that means that i
may or may not exist depending on whether the iterable produces an empty sequence.
If I want to use the last i
of the iterable (an i
that doesn’t exist for an empty sequence) I can do one of two things:
i = None # Declare the variable.
for i in generate_numbers():
do_something(i)
use_last(i)
or
for i in generate_numbers():
do_something(i)
try:
use_last(i)
except UnboundLocalError:
pass # i didn’t exist because sequence was empty.
The first solution may be problematic because I can’t tell (depending on the sequence values) whether i
was the last element. The second solution is more accurate in that respect.
ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:
C:\>assoc .py .py=Python.File
Next, you need to know how Windows is executing things with that extension. It's associated with the file type "Python.File", so this command shows what it will be doing:
C:\>ftype Python.File Python.File="c:\python26\python.exe" "%1" %*
So on my machine, when I type "blah.py foo", it will execute this exact command, with no difference in results than if I had typed the full thing myself:
"c:\python26\python.exe" "blah.py" foo
If you type the same thing, including the quotation marks, then you'll get results identical to when you just type "blah.py foo". Now you're in a position to figure out the rest of your problem for yourself.
(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)
Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the
HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command
key to:
"C:\Python26\python26.exe" "%1" %*
Likely, previously, %*
was missing. Similarly, set
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command
The registry path may vary, use python26.exe
or python.exe
or whichever is already in the registry.
Echo inside an HTML element with class
and style the element:
echo "<span class='name'>" . $ip['cityName'] . "</span>";
Seems like just adding meta tags to index.html doesn't prevent page from zooming. Adding below style will do the magic.
:root {
touch-action: pan-x pan-y;
height: 100%
}
EDIT: Demo: https://no-mobile-zoom.stackblitz.io
Create a static constructor to add values in the Dictionary
enum Commands
{
StudentDetail
}
public static class Quires
{
public static Dictionary<Commands, String> quire
= new Dictionary<Commands, String>();
static Quires()
{
quire.add(Commands.StudentDetail,@"SELECT * FROM student_b");
}
}
cmd /c ipconfig /all & Output.txt
This command execute command and open Output.txt
file in a single command
They are lists because you type them as lists in the dictionary:
bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}
You should use the bike-class instead:
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100),
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165)
}
This will allow you to get the cost of the bikes with bike.cost as you were trying to.
for bike in bikes.values():
profit = bike.cost * margin
print(bike.name + " : " + str(profit))
This will now print:
Kruzer : 33.0
Trike : 20.0
You could also try something like this:
input[type="radio"] {_x000D_
margin-top: -1px;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<label class="child"><input id = "warm" type="radio" name="weathertype" value="warm" checked> Warm<br></label>_x000D_
<label class="child1"><input id = "cold" type="radio" name="weathertype" value="cold" checked> Cold<br></label>
_x000D_
Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference
under the info tar
command.
x
means --extract
. v
means --verbose
. f
means --file
. z
means --gzip
. You can combine one-letter arguments together, and f
takes an argument, the filename. There is something you have to watch out for:
Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).
This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:tar cfz archive.tar.gz file tar -cfz archive.tar.gz file
are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.
You can use a struct to read write into a file. You do not need to cast it as a `char*. Struct size will also be preserved. (This point is not closest to the topic but guess it: behaving on hard memory is often similar to RAM one.)
To move (to & from) a single string field you must use strncpy
and a transient string buffer '\0'
terminating.
Somewhere you must remember the length of the record string field.
To move other fields you can use the dot notation, ex.:
NodeB->one=intvar;
floatvar2=(NodeA->insidebisnode_subvar).myfl;
struct mynode {
int one;
int two;
char txt3[3];
struct{char txt2[6];}txt2fi;
struct insidenode{
char txt[8];
long int myl;
void * mypointer;
size_t myst;
long long myll;
} insidenode_subvar;
struct insidebisnode{
float myfl;
} insidebisnode_subvar;
} mynode_subvar;
typedef struct mynode* Node;
...(main)
Node NodeA=malloc...
Node NodeB=malloc...
You can embed each string into a structs that fit it,
to evade point-2 and behave like Cobol:
NodeB->txt2fi=NodeA->txt2fi
...but you will still need of a transient string
plus one strncpy
as mentioned at point-2 for scanf
, printf
otherwise an operator longer input (shorter),
would have not be truncated (by spaces padded).
(NodeB->insidenode_subvar).mypointer=(NodeA->insidenode_subvar).mypointer
will create a pointer alias.NodeB.txt3=NodeA.txt3
causes the compiler to reject:
error: incompatible types when assigning to type ‘char[3]’ from type ‘char *’
point-4 works only because NodeB->txt2fi
& NodeA->txt2fi
belong to the same typedef
!!
A correct and simple answer to this topic I found at In C, why can't I assign a string to a char array after it's declared? "Arrays (also of chars) are second-class citizens in C"!!!
Marquee (<marquee>
) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!
I added binary before the column name and solve the charset error.
insert into tableA values(binary stringcolname1);
set time1=%time%
call timeout 10
set time2=%time%
echo. time1
echo. time2
echo.
pause
I was using gradle 3.3.0. It was the main culprit. Wasted 6.50 hours from my life. Gradle 3.2.1 removed the error.
classpath 'com.android.tools.build:gradle:3.2.1'
Problem resolved after changing the gradle version. Details history can be found here.
Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.
After you run the install file SQLExpr.exe
look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)
After that, find the file sqlncli_x64.msi
in the setup folder, and run it.
Now you are ready the run the setup.exe
file and install SQL server 2005 without errors
Do it like this:
var value = $("#text").val(); // value = 9.61 use $("#text").text() if you are not on select box...
value = value.replace(".", ":"); // value = 9:61
// can then use it as
$("#anothertext").val(value);
Updated to reflect to current version of jQuery. And also there are a lot of answers here that would best fit to any same situation as this. You, as a developer, need to know which is which.
To replace multiple characters at a time use some thing like this: name.replace(/&/g, "-")
. Here I am replacing all &
chars with -
. g
means "global"
Note - you may need to add square brackets to avoid an error - title.replace(/[+]/g, " ")
credits vissu and Dante Cullari
appendChild()
is a more native way:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'script.js';
document.head.appendChild(script);
I came across this question as a duplicate of a newer question which asked what the non-deprecated way to get a Date
at a specific year, month, and day was.
The answers here so far say to use the Calendar
class, and that was true until Java 8 came out. But as of Java 8, the standard way to do this is:
LocalDate localDate = LocalDate.of(1985, 1, 1);
And then if you really really need a java.util.Date
, you can use the suggestions in this question.
For more info, check out the API or the tutorials for Java 8.
This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.
Another alternative is KMP (Knuth–Morris–Pratt).
The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.
Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:
// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
function kmpSearch(pattern, text) {_x000D_
if (pattern.length == 0)_x000D_
return 0; // Immediate match_x000D_
_x000D_
// Compute longest suffix-prefix table_x000D_
var lsp = [0]; // Base case_x000D_
for (var i = 1; i < pattern.length; i++) {_x000D_
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
j = lsp[j - 1];_x000D_
if (pattern.charAt(i) == pattern.charAt(j))_x000D_
j++;_x000D_
lsp.push(j);_x000D_
}_x000D_
_x000D_
// Walk through text string_x000D_
var j = 0; // Number of chars matched in pattern_x000D_
for (var i = 0; i < text.length; i++) {_x000D_
while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
j = lsp[j - 1]; // Fall back in the pattern_x000D_
if (text.charAt(i) == pattern.charAt(j)) {_x000D_
j++; // Next char matched, increment position_x000D_
if (j == pattern.length)_x000D_
return i - (j - 1);_x000D_
}_x000D_
}_x000D_
return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
Still surprised that no one proposed the shortest solution with align-center justify-center
to center content vertically and horizontally. Check this CodeSandbox and code below:
<v-container fluid fill-height>
<v-layout align-center justify-center>
<v-flex>
<!-- Some HTML elements... -->
</v-flex>
</v-layout>
</v-container>
Yes you can.... you can place something on top of the link element.
<!DOCTYPE html>
<html>
<head>
<title>Yes you CAN</title>
<style type="text/css">
ul{
width: 500px;
border: 5px solid black;
}
.product-type-simple {
position: relative;
height: 150px;
width: 150px;
}
.product-type-simple:before{
position: absolute;
height: 100% ;
width: 100% ;
content: '';
background: green;//for debugging purposes , remove this if you want to see whats behind
z-index: 999999999999;
}
</style>
</head>
<body>
<ul>
<li class='product-type-simple'>
<a href="/link1">
<img src="http://placehold.it/150x150">
</a>
</li>
<li class='product-type-simple'>
<a href="/link2">
<img src="http://placehold.it/150x150">
</a>
</li>
</ul>
</body>
</html>
the magic sauce happens at product-type-simple:before class Whats happening here is that for each element that has class of product-type-simple you create something that has the width and height equal to that of the product-type-simple , then you increase its z-index to make sure it will place it self on top of the content of product-type-simple. You can toggle the background color if you want to see whats going on.
here is an example of the code https://jsfiddle.net/92qky63j/
If anybody still facing the error with using google's design library as mentioned in the answer then, please use this as commented by @h_k which is -
Instead of calling setError on TextInputLayout, You might be using setError on EditText itself.
def proc = 'cmd /c C:/TortoiseSVN/bin/TortoiseProc.exe /command:update /path:"C:/work/new/1.2/" /closeonend:2'.execute()
This is my 'svn.groovy' file.
You have a few issues with your code:
<select name="dbType" id=dbType">
should be <select name="dbType" id="dbType">
$('this')
should be $(this)
: there is no need for the quotes inside the paranthesis.
use .val() instead of .value() when you want to retrieve the value of an option
when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function
try this:
$('#dbType').on('change',function(){
if( $(this).val()==="other"){
$("#otherType").show()
}
else{
$("#otherType").hide()
}
});
UPDATE for use with switch:
$('#dbType').on('change',function(){
var selection = $(this).val();
switch(selection){
case "other":
$("#otherType").show()
break;
default:
$("#otherType").hide()
}
});
UPDATE with links for jQuery and jQuery-UI:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>??
If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.
If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.
Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.
In case someone wants to get the data frame in a "long format" (leaf values have the same type) without multiindex, you can do this:
pd.DataFrame.from_records(
[
(level1, level2, level3, leaf)
for level1, level2_dict in user_dict.items()
for level2, level3_dict in level2_dict.items()
for level3, leaf in level3_dict.items()
],
columns=['UserId', 'Category', 'Attribute', 'value']
)
UserId Category Attribute value
0 12 Category 1 att_1 1
1 12 Category 1 att_2 whatever
2 12 Category 2 att_1 23
3 12 Category 2 att_2 another
4 15 Category 1 att_1 10
5 15 Category 1 att_2 foo
6 15 Category 2 att_1 30
7 15 Category 2 att_2 bar
(I know the original question probably wants (I.) to have Levels 1 and 2 as multiindex and Level 3 as columns and (II.) asks about other ways than iteration over values in the dict. But I hope this answer is still relevant and useful (I.): to people like me who have tried to find a way to get the nested dict into this shape and google only returns this question and (II.): because other answers involve some iteration as well and I find this approach flexible and easy to read; not sure about performance, though.)
NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.
The table:
create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));
Now if you do:
insert into xyz (name) values('one'),('two'),('three');
The mysqli::insert_id will be 1 not 3.
To get the correct value do:
mysqli::insert_id + mysqli::affected_rows) - 1
This has been document but it is a bit obscure.
Just replace <div class="container">
with <div class="container-fluid">
, which is the container with no margins on both sides.
I think this is the best solution because it avoids some useless overriding and makes use of built-in classes, it's clean.
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
Batch files don't work that way. They don't just "type" everything - they run system commands, in this case ftp
, wait for them to return, and run the next command... so in this case, the interpreter is simply waiting for ftp
to exit.
If you must use the ftp
command, then prepare a script file (for example, commands.txt
and run ftp -s:commands.txt
.
But using cURL, or a PHP/Perl/Python/whatever script may be a better idea.
TLDR: Use map
(returning undefined
when needed) and then filter
.
First, I believe that a map + filter function is useful since you don't want to repeat a computation in both. Swift originally called this function flatMap
but then renamed it to compactMap
.
For example, if we don't have a compactMap
function, we might end up with computation
defined twice:
let array = [1, 2, 3, 4, 5, 6, 7, 8];
let mapped = array
.filter(x => {
let computation = x / 2 + 1;
let isIncluded = computation % 2 === 0;
return isIncluded;
})
.map(x => {
let computation = x / 2 + 1;
return `${x} is included because ${computation} is even`
})
// Output: [2 is included because 2 is even, 6 is included because 4 is even]
Thus compactMap
would be useful to reduce duplicate code.
A really simple way to do something similar to compactMap
is to:
undefined
.undefined
values.This of course relies on you never needing to return undefined values as part of your original map function.
Example:
let array = [1, 2, 3, 4, 5, 6, 7, 8];
let mapped = array
.map(x => {
let computation = x / 2 + 1;
let isIncluded = computation % 2 === 0;
if (isIncluded) {
return `${x} is included because ${computation} is even`
} else {
return undefined
}
})
.filter(x => typeof x !== "undefined")
If you don't want to clutter up your console with error messages, you can also run
git ls-files file_name
and then check the result. If git returns nothing, then the file is not tracked. If it's tracked, git will return the file path.
This comes in handy if you want to combine it in a script, for example PowerShell:
$gitResult = (git ls-files $_) | out-string
if ($gitResult.length -ne 0)
{
## do stuff with the tracked file
}
Options:
data.Seek
as suggested by ken2kUse the somewhat simpler Position
property:
data.Position = 0;
Use the ToArray
call in MemoryStream
to make your life simpler to start with:
byte[] buf = data.ToArray();
The third option would be my preferred approach.
Note that you should have a using
statement to close the file stream automatically (and optionally for the MemoryStream
), and I'd add a using directive for System.IO
to make your code cleaner:
byte[] buf;
using (MemoryStream data = new MemoryStream())
{
using (Stream file = TestStream())
{
file.CopyTo(data);
buf = data.ToArray();
}
}
// Use buf
You might also want to create an extension method on Stream
to do this for you in one place, e.g.
public static byte[] CopyToArray(this Stream input)
{
using (MemoryStream memoryStream = new MemoryStream())
{
input.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
Note that this doesn't close the input stream.
Try this :
sc delete Apache2.4
or try this :
C:\Apache24\bin>httpd -k uninstall
hope this will be helpful
I found a way to style all previous siblings (opposite of ~
) that may work depending on what you need.
Let's say you have a list of links and when hovering on one, all the previous ones should turn red. You can do it like this:
/* default link color is blue */_x000D_
.parent a {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
/* prev siblings should be red */_x000D_
.parent:hover a {_x000D_
color: red;_x000D_
}_x000D_
.parent a:hover,_x000D_
.parent a:hover ~ a {_x000D_
color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<a href="#">link</a>_x000D_
<a href="#">link</a>_x000D_
<a href="#">link</a>_x000D_
<a href="#">link</a>_x000D_
<a href="#">link</a>_x000D_
</div>
_x000D_
This depends on implementation, but the general rule is that the domain is checked against all SANs and the common name. If the domain is found there, then the certificate is ok for connection.
RFC 5280, section 4.1.2.6 says "The subject name MAY be carried in the subject field and/or the subjectAltName extension". This means that the domain name must be checked against both SubjectAltName extension and Subject property (namely it's common name parameter) of the certificate. These two places complement each other, and not duplicate it. And SubjectAltName is a proper place to put additional names, such as www.domain.com or www2.domain.com
Update: as per RFC 6125, published in 2011, the validator must check SAN first, and if SAN exists, then CN should not be checked. Note that RFC 6125 is relatively recent and there still exist certificates and CAs that issue certificates, which include the "main" domain name in CN and alternative domain names in SAN. I.e. by excluding CN from validation if SAN is present, you can deny some otherwise valid certificate.
You can define your title programatically using setTitle
within your Activity
, this method can accept either a String
or an ID defined in your values/strings.xml
file. Example:
public class YourActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
setTitle(R.string.your_title);
setContentView(R.layout.main);
}
}
You are copying all files to a single file called TEST_BACKUP_FOLDER
try this:
md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER
Try the following
Dictionary<int, DateTime> existingItems =
(from ObjType ot in TableObj).ToDictionary(x => x.Key);
Or the fully fledged type inferenced version
var existingItems = TableObj.ToDictionary(x => x.Key);
Your regex "sentence(.*)"
is right. To retrieve the contents of the group in parenthesis, you would call:
Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
String s = m.group(1); // " that is awesome"
}
Note the use of m.find()
in this case (attempts to find anywhere on the string) and not m.matches()
(would fail because of the prefix "some lame"; in this case the regex would need to be ".*sentence(.*)"
)
the toString()
converts the specified object to a string value.
Don't know if this will be everybody's answer, but after some digging, here's what we came up with.
The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent
After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).
The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.
So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.
Here is another option
public static bool UrlIsValid(string url)
{
bool br = false;
try {
IPHostEntry ipHost = Dns.Resolve(url);
br = true;
}
catch (SocketException se) {
br = false;
}
return br;
}
This is easier to do if you convert your matrix to a data frame using as.data.frame(). In that case the previous answers (using subset or m$three) will work, otherwise they will not.
To perform the operation on a matrix, you can define a column by name:
m[m[, "three"] == 11,]
Or by number:
m[m[,3] == 11,]
Note that if only one row matches, the result is an integer vector, not a matrix.
Here is a function that does this:
function days_between(date1, date2) {
// The number of milliseconds in one day
const ONE_DAY = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
const differenceMs = Math.abs(date1 - date2);
// Convert back to days and return
return Math.round(differenceMs / ONE_DAY);
}
Try using "w+"
as the write mode instead of just "w"
:
File.open("out.txt", "w+") { |file| file.write("boo!") }
If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you
This allows you to just get the image data and set to the img src, which is cool.
var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
var blob = oReq.response;
var imgSrc = URL.createObjectURL( blob );
var $img = $( '<img/>', {
"alt": "test image",
"src": imgSrc
} ).appendTo( $( '#bb_theImageContainer' ) );
window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );
The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.
import React, { useRef, useState } from 'react'
...
const inputRef = useRef()
....
function chooseFile() {
const { current } = inputRef
(current || { click: () => {}}).click()
}
...
<input
onChange={e => {
setFile(e.target.files)
}}
id="select-file"
type="file"
ref={inputRef}
/>
<Button onClick={chooseFile} shadow icon="/upload.svg">
Choose file
</Button>
I have had this error.And my solution is following as:
1. Create a custom listview which is non scrollable
public class NonScrollListView extends ListView {
public NonScrollListView(Context context) {
super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
2. Use above custom class for xml file
<com.Example.NonScrollListView
android:id="@+id/lv_nonscroll_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.Example.NonScrollListView>
Hope best for you.
IMHO, the most frustrating experience comes from getting / setting a value of a specific scope related to an visual element. I did a lot of breakpoints not only in my own code, but also in angular.js itself, but sometimes it is simply not the most effective way. Although the methods below are very powerful, they are definitely considered to be bad practice if you actually use in production code, so use them wisely!
In many non-IE browsers, you can select an element by right clicking an element and clicking "Inspect Element". Alternatively you can also click on any element in Elements tab in Chrome, for example. The latest selected element will be stored in variable $0
in console.
Depending on whether there exists a directive that creates an isolate scope, you can retrieve the scope by angular.element($0).scope()
or angular.element($0).isolateScope()
(use $($0).scope()
if $ is enabled). This is exactly what you get when you are using the latest version of Batarang. If you are changing the value directly, remember to use scope.$digest()
to reflect the changes on UI.
Not necessarily for debugging. scope.$eval(expression)
is very handy when you want to quickly check whether an expression has the expected value.
The difference between scope.bla
and scope.$eval('bla')
is the former does not consider the prototypically inherited values. Use the snippet below to get the whole picture (you cannot directly change the value, but you can use $eval
anyway!)
scopeCopy = function (scope) {
var a = {};
for (x in scope){
if (scope.hasOwnProperty(x) &&
x.substring(0,1) !== '$' &&
x !== 'this') {
a[x] = angular.copy(scope[x])
}
}
return a
};
scopeEval = function (scope) {
if (scope.$parent === null) {
return hoho(scope)
} else {
return angular.extend({}, haha(scope.$parent), hoho(scope))
}
};
Use it with scopeEval($($0).scope())
.
Sometimes you may want to monitor the values in ngModel
when you are writing a directive. Use $($0).controller('ngModel')
and you will get to check the $formatters
, $parsers
, $modelValue
, $viewValue
$render
and everything.
In Sqlite
:
CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
This function from this answer is the best way to handle this as $.ready
explicitly fails for iframes. Here's the decision not to support this.
The load
event also doesn't fire if the iframe has already loaded. Very frustrating that this remains a problem in 2020!
function onIframeReady($i, successFn, errorFn) {
try {
const iCon = $i.first()[0].contentWindow,
bl = "about:blank",
compl = "complete";
const callCallback = () => {
try {
const $con = $i.contents();
if($con.length === 0) { // https://git.io/vV8yU
throw new Error("iframe inaccessible");
}
successFn($con);
} catch(e) { // accessing contents failed
errorFn();
}
};
const observeOnload = () => {
$i.on("load.jqueryMark", () => {
try {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href !== bl || src === bl || src === "") {
$i.off("load.jqueryMark");
callCallback();
}
} catch(e) {
errorFn();
}
});
};
if(iCon.document.readyState === compl) {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href === bl && src !== bl && src !== "") {
observeOnload();
} else {
callCallback();
}
} else {
observeOnload();
}
} catch(e) {
errorFn();
}
}
Please try this:
<input class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2" type="text" name="name" value="" placeholder="Your Name" style="background-color:blue;"/>
You basically put all the CSS inside the style part of the input tag and it works.
Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)
...._x000D_
exports.AddSomething = (req,res,next) =>{_x000D_
const newSomething = new SomeEntity({_x000D_
_id:new mongoose.Types.ObjectId(), //its very own ID_x000D_
somethingName:req.body.somethingName,_x000D_
theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID_x000D_
})_x000D_
}_x000D_
...
_x000D_
Hope it Helps
Just in case you ever want to do this not on Android it's helpful to think about which day where as not all devices mark their calendar in local time.
From Java 8 onwards:
LocalDate.now(ZoneId.of("America/Detroit")).getDayOfWeek()
Another veneration of find_elements_by_xpath(".//*")
is:
from selenium.webdriver.common.by import By
find_elements(By.XPATH, ".//*")
Here's an example of how you could implement a list view:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//We have our list view
final ListView dynamic = findViewById(R.id.dynamic);
//Create an array of elements
final ArrayList<String> classes = new ArrayList<>();
classes.add("Data Structures");
classes.add("Assembly Language");
classes.add("Calculus 3");
classes.add("Switching Systems");
classes.add("Analysis Tools");
//Create adapter for ArrayList
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, classes);
//Insert Adapter into List
dynamic.setAdapter(adapter);
//set click functionality for each list item
dynamic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("User clicked ", classes.get(position));
}
});
}
I am running a Windows 10 machine and had some problems, too. I installed graphviz via msi installer. Adding via System settings did not work for me.
I removed the installation with the msi and used chocolatey, a windows package manager. Removing the installed version is necessary, otherwise chocolatey won't install.
Now it runs fine. I would recommend doing it this way.
Simply save it with a .pyw
extension. This will prevent the console window from opening.
On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.
Apple's recommendation recoded in Swift + Using UIScrollView with Auto Layout in iOS (basing on these following links: link 1, link 2, link 3):
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var t1: UITextField!
@IBOutlet var t2: UITextField!
@IBOutlet var t3: UITextField!
@IBOutlet var t4: UITextField!
@IBOutlet var srcScrollView: UIScrollView!
@IBOutlet var contentView: UIView!
var contentViewCoordinates: CGPoint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
/* Constraints on content view */
let leftConstraint = NSLayoutConstraint(item:self.contentView,
attribute:NSLayoutAttribute.Leading,
relatedBy:NSLayoutRelation.Equal,
toItem:self.view,
attribute:NSLayoutAttribute.Left,
multiplier:1.0,
constant:0)
self.view.addConstraint(leftConstraint)
let rightConstraint = NSLayoutConstraint(item:self.contentView,
attribute:NSLayoutAttribute.Trailing,
relatedBy:NSLayoutRelation.Equal,
toItem:self.view,
attribute:NSLayoutAttribute.Right,
multiplier:1.0,
constant:0)
self.view.addConstraint(rightConstraint)
/* Tap gesture */
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")
// prevents the scroll view from swallowing up the touch event of child buttons
tapGesture.cancelsTouchesInView = false
srcScrollView.addGestureRecognizer(tapGesture)
/* Save content view coordinates */
contentViewCoordinates = contentView.frame.origin
}
func hideKeyboard() {
t1.resignFirstResponder()
t2.resignFirstResponder()
t3.resignFirstResponder()
t4.resignFirstResponder()
}
var activeField: UITextField?
func textFieldDidBeginEditing(textField: UITextField) {
activeField = textField
}
func textFieldDidEndEditing(textField: UITextField) {
activeField = nil
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "keyboardOnScreen:", name: UIKeyboardDidShowNotification, object: nil)
center.addObserver(self, selector: "keyboardOffScreen:", name: UIKeyboardDidHideNotification, object: nil)
}
func keyboardOnScreen(notification: NSNotification){
// Retrieve the size and top margin (inset is the fancy word used by Apple)
// of the keyboard displayed.
let info: NSDictionary = notification.userInfo!
let kbSize = info.valueForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue().size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize!.height, 0.0)
srcScrollView.contentInset = contentInsets
srcScrollView.scrollIndicatorInsets = contentInsets
var aRect: CGRect = self.view.frame
aRect.size.height -= kbSize!.height
//you may not need to scroll, see if the active field is already visible
if (CGRectContainsPoint(aRect, activeField!.frame.origin) == false) {
let scrollPoint:CGPoint = CGPointMake(0.0, activeField!.frame.origin.y - kbSize!.height)
srcScrollView.setContentOffset(scrollPoint, animated: true)
}
}
// func keyboardOnScreen(aNotification: NSNotification) {
// let info: NSDictionary = aNotification.userInfo!
// let kbSize = info.valueForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue().size
//
// var bkgndRect: CGRect! = activeField?.superview?.frame
//
// bkgndRect.size.height += kbSize!.height
//
// activeField?.superview?.frame = bkgndRect
//
// srcScrollView.setContentOffset(CGPointMake(0.0, activeField!.frame.origin.y - kbSize!.height), animated: true)
// }
func keyboardOffScreen(notification: NSNotification){
let contentInsets:UIEdgeInsets = UIEdgeInsetsZero
srcScrollView.contentInset = contentInsets
srcScrollView.scrollIndicatorInsets = contentInsets
self.srcScrollView.setContentOffset(CGPointMake(0, -self.view.frame.origin.y/2), animated: true)
}
}
I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt
Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....
I also experienced an issue like this, my workspace was corrupted and didn't do all the important things anymore.
For some reason, I had a corrupt resource on one of my projects. It didn't show up in the package tree, but it did show in the error log in Eclipse as
Error while creating a link for external folder X:\somefolder
After checking every project (because the error didn't point to one), I indeed found this resource in one of the build paths (in Configure Build Path menu it did show an error icon!) and deleted it.
See Eclipse (Kepler) Workspace acting weird (type hierarchy, searching for references not working) for a wider description of my issue if you're experiencing something similar.
Posted this for future developers to reference.
The percentage %
sign followed by two hexadecimal numbers (UTF-8 character representation) typically denotes a string which has been encoded to be part of a URI. This ensures that characters that would otherwise have special meaning don't interfere. In your case %20
is immediately recognisable as a whitespace character - while not really having any meaning in a URI it is encoded in order to avoid breaking the string into multiple "parts".
Don't get me wrong, regex is the bomb! However any web technology worth caring about will already have tools available in it's library to handle standards like this for you. Why re-invent the wheel...?
var str = 'xPasswords%20do%20not%20match';
console.log( decodeURI(str) ); // "xPasswords do not match"
Javascript has both decodeURI
and decodeURIComponent
which differ slightly in respect to their encodeURI
and encodeURIComponent
counterparts - you should familiarise yourself with the documentation.
Though you can solve passing the formatter by storing it in local buffer first, but that needs stack and can sometime be issue to deal with. I tried following and it seems to work fine.
#include <stdarg.h>
#include <stdio.h>
void print(char const* fmt, ...)
{
va_list arg;
va_start(arg, fmt);
vprintf(fmt, arg);
va_end(arg);
}
void printFormatted(char const* fmt, va_list arg)
{
vprintf(fmt, arg);
}
void showLog(int mdl, char const* type, ...)
{
print("\nMDL: %d, TYPE: %s", mdl, type);
va_list arg;
va_start(arg, type);
char const* fmt = va_arg(arg, char const*);
printFormatted(fmt, arg);
va_end(arg);
}
int main()
{
int x = 3, y = 6;
showLog(1, "INF, ", "Value = %d, %d Looks Good! %s", x, y, "Infact Awesome!!");
showLog(1, "ERR");
}
Hope this helps.
In the hope of providing clarity over common cinfusion...
I have written many python <--> bash <--> elfbin toolchains and the proper way to see it is such as this:
Each process (originator) has a state of the environment inherited from whatever invoked it. Any change remains lokal to that process. Transfering an environment state is a function by itself and runs in two directions, each with it's own caveats. The most common thing is to modify environment before running a sub-process. To go down to the metal, look at the exec() - call in C. There is a variant that takes a pointer to environment data. This is the only actually supported transfer of environment in typical OS'es.
Shell scripts will create a state to pass when running children when you do an export. Otherwise it just uses that which it got in the first place.
In all other cases it will be some generic mechanism used to pass a set of data to allow the calling process itself to update it's environment based on the result of the child-processes output.
Ex:
ENVUPDATE = $(CMD_THAT_OUTPUTS_KEYVAL_LISTS)
echo $ENVUPDATE > $TMPFILE
source $TMPFILE
The same can of course be done using json, xml or other things as long as you have the tools to interpret and apply.
The need for this may be (50% chance) a sign of misconstruing the basic primitives and that you need a better config or parameter interchange in your solution.....
Oh, in python I would do something like... (need improvement depending on your situation)
import re
RE_KV=re.compile('([a-z][\w]*)\s*=\s*(.*)')
OUTPUT=RunSomething(...) (Assuming 'k1=v1 k2=v2')
for kv in OUTPUT.split(' ')
try:
k,v=RE_KV.match(kv).groups()
os.environ[k]=str(v)
except:
#The not a property case...
pass
Replace double quotes with single ones:
INSERT
INTO MY.LOGFILE
(id,severity,category,logdate,appendername,message,extrainfo)
VALUES (
'dee205e29ec34',
'FATAL',
'facade.uploader.model',
'2013-06-11 17:16:31',
'LOGDB',
NULL,
NULL
)
In SQL, double quotes are used to mark identifiers, not string constants.
For anyone who finds this page looking for unix timestamp w/ milliseconds, the documentation says
moment().valueOf()
or
+moment();
you can also get it through moment().format('x')
(or .format('X')
[capital X] for unix seconds with decimal milliseconds), but that will give you a string. Which moment.js won't actually parse back afterwards, unless you convert/cast it back to a number first.
There are after and before methods for Timestamp
which will do the trick
Non of the above solved my problem, you can check pod version using two commands
pod --version
gem which cocoapods
In my case pod --version
always showed "1.5.0" while gem which cocopods
shows
Library/Ruby/Gems/2.3.0/gems/cocoapods-1.9.0/lib/cocoapods.rb
. I tried every thing but unable to update version showed from pod --version
. sudo gem install cocopods
result in installing latest version but pod --version
always showing previous version. Finally I tried these commands
sudo gem update
sudo gem uninstall cocoapods
sudo gem install cocopods
pod setup``pod install
catch for me was sudo gem update. Hopefully it will help any body else.
NOTE this answer has received some attention recently. I am not advocating this as a solution (it is a solution I have seen in the past, before the STL). It is an interesting approach and should only be applied over std::string
or std::stringstream
if after profiling your code you discover this makes an improvement.
I normally use either std::string
or std::stringstream
. I have never had any problems with these. I would normally reserve some room first if I know the rough size of the string in advance.
I have seen other people make their own optimized string builder in the distant past.
class StringBuilder {
private:
std::string main;
std::string scratch;
const std::string::size_type ScratchSize = 1024; // or some other arbitrary number
public:
StringBuilder & append(const std::string & str) {
scratch.append(str);
if (scratch.size() > ScratchSize) {
main.append(scratch);
scratch.resize(0);
}
return *this;
}
const std::string & str() {
if (scratch.size() > 0) {
main.append(scratch);
scratch.resize(0);
}
return main;
}
};
It uses two strings one for the majority of the string and the other as a scratch area for concatenating short strings. It optimise's appends by batching the short append operations in one small string then appending this to the main string, thus reducing the number of reallocations required on the main string as it gets larger.
I have not required this trick with std::string
or std::stringstream
. I think it was used with a third party string library before std::string, it was that long ago. If you adopt a strategy like this profile your application first.
if you are findind keyboard shortcuts for Fix doc comment like this:
/**
* ...
*/
you can do it by useing Live Template(setting - editor - Live Templates - add)
/**
* $comment$
*/
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
You can directly use the EnvironmentPlugin
available in webpack
to have access to any environment variable during the transpilation.
You just have to declare the plugin in your webpack.config.js
file:
var webpack = require('webpack');
module.exports = {
/* ... */
plugins = [
new webpack.EnvironmentPlugin(['NODE_ENV'])
]
};
Note that you must declare explicitly the name of the environment variables you want to use.
Mobile browsers generally ignore this attribute to prevent consuming data until user explicitly starts the download.
UPDATE: newer version of mobile browser on Android and iOS do support autoplay function. But it only works if the video is muted or has no audio channel:
Some additional info: https://webkit.org/blog/6784/new-video-policies-for-ios/
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
There isn't so much an advantage or disadvantage aside from "do I want this variable, function, class, etc. to be public or private?"
The use of http.createClient
is now deprecated. You can pass Headers in options collection as below.
var options = {
hostname: 'example.com',
path: '/somePath.php',
method: 'GET',
headers: {'Cookie': 'myCookie=myvalue'}
};
var results = '';
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
results = results + chunk;
//TODO
});
res.on('end', function () {
//TODO
});
});
req.on('error', function(e) {
//TODO
});
req.end();
/*
This procedure is for finding any string or date in all tables
if search string is date, its format should be yyyy-MM-dd
eg. 2011-07-05
*/
-- ================================================
-- Exec SearchInTables 'f6f56934-a5d4-4967-80a1-1a2223b9c7b1'
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Joshy,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE SearchInTables
@myValue nvarchar(1000)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE @searchsql nvarchar(max)
DECLARE @table_name nvarchar(1000)
DECLARE @Schema_name nvarchar(1000)
DECLARE @ParmDefinition nvarchar(500)
DECLARE @XMLIn nvarchar(max)
SET @ParmDefinition = N'@XMLOut varchar(max) OUTPUT'
SELECT A.name,b.name
FROM sys.tables A
INNER JOIN sys.schemas B ON A.schema_id=B.schema_id
WHERE A.name like 'tbl_Tax_Sections'
DECLARE tables_cur CURSOR FOR
SELECT A.name,b.name FOM sys.tables A
INNER JOIN sys.schemas B ON A.schema_id=B.schema_id
WHERE A.type = 'U'
OPEN tables_cur
FETCH NEXT FROM tables_cur INTO @table_name , @Schema_name
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @searchsql ='SELECT @XMLOut=(SELECT PATINDEX(''%'+ @myValue+ '%'''
SET @searchsql =@searchsql + ', (SELECT * FROM '+@Schema_name+'.'+@table_name+' FOR XML AUTO) ))'
--print @searchsql
EXEC sp_executesql @searchsql, @ParmDefinition, @XMLOut=@XMLIn OUTPUT
--print @XMLIn
IF @XMLIn <> 0 PRINT @Schema_name+'.'+@table_name
FETCH NEXT FROM tables_cur INTO @table_name , @Schema_name
END
CLOSE tables_cur
DEALLOCATE tables_cur
RETURN
END
GO
There is an indexOf
method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.
Make sure that your test class is public.
You can use std::ifstream
, funcion like is_open
, fail
, for example as below code (the cout "open" means file exist or not):
cited from this answer
shell("C:\Users\USERNAME\AppData\Local\Google\Chrome\Application\Chrome.exe -url http:google.ca")
Use NgForm
's .resetForm()
rather than .reset()
because it is the method that is officially documented in NgForm
's public api. (Ref [1])
<form (ngSubmit)="mySubmitHandler(); myNgForm.resetForm()" #myNgForm="ngForm">
The .resetForm()
method will reset the NgForm
's FormGroup
and set it's submit
flag to false
(See [2]).
Tested in @angular versions 2.4.8 and 4.0.0-rc3
Try to check for existence:
IF NOT EXISTS (SELECT * FROM dbo.Employee WHERE ID = @SomeID)
INSERT INTO dbo.Employee(Col1, ..., ColN)
VALUES(Val1, .., ValN)
ELSE
UPDATE dbo.Employee
SET Col1 = Val1, Col2 = Val2, ...., ColN = ValN
WHERE ID = @SomeID
You could easily wrap this into a stored procedure and just call that stored procedure from the outside (e.g. from a programming language like C# or whatever you're using).
Update: either you can just write this entire statement in one long string (doable - but not really very useful) - or you can wrap it into a stored procedure:
CREATE PROCEDURE dbo.InsertOrUpdateEmployee
@ID INT,
@Name VARCHAR(50),
@ItemName VARCHAR(50),
@ItemCatName VARCHAR(50),
@ItemQty DECIMAL(15,2)
AS BEGIN
IF NOT EXISTS (SELECT * FROM dbo.Table1 WHERE ID = @ID)
INSERT INTO dbo.Table1(ID, Name, ItemName, ItemCatName, ItemQty)
VALUES(@ID, @Name, @ItemName, @ItemCatName, @ItemQty)
ELSE
UPDATE dbo.Table1
SET Name = @Name,
ItemName = @ItemName,
ItemCatName = @ItemCatName,
ItemQty = @ItemQty
WHERE ID = @ID
END
and then just call that stored procedure from your ADO.NET code
The posted solutions will not link any hidden files. To include them, try this:
cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib
not /mnt/usr/lib
), you could do this:
cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
It permanently comments out that code so the compiler will never compile it.
The coder can later change the #ifdef to have that code compile in the program if he wants to.
It's exactly like the code doesn't exist.
User Konrad Rudolph advocates for DirectCast() in Stack Overflow question "Hidden Features of VB.NET".
you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn
List<AttributeHistory> findByValueIn(List<String> values);
I believe the following should work with many well-behaved classed in Python:
def copy(obj):
return type(obj)(obj)
(Of course, I am not talking here about "deep copies," which is a different story, and which may be not a very clear concept -- how deep is deep enough?)
According to my tests with Python 3, for immutable objects, like tuples or strings, it returns the same object (because there is no need to make a shallow copy of an immutable object), but for lists or dictionaries it creates an independent shallow copy.
Of course this method only works for classes whose constructors behave accordingly. Possible use cases: making a shallow copy of a standard Python container class.
I had tried restart the device, and it's work, popup and ask want to trust the mac for debug mode.
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
Chrome (technically, Blink) will not implement maxlength for <input type="number">
.
The HTML5 specification says that maxlength is only applicable to the types text, url, e-mail, search, tel, and password.
Try inserting <xsl:number format="1. "/><xsl:value-of select="."/><xsl:text>
in the place of ???.
Note the "1. " - this is the number format. More info: here
I found a solution by myself after doing some research:
Now everything works fine.
Whether or not you install opencv3 manually or from Gohlke's whl package, I found the need to create/edit the file cv.py in site_packages as follows to make compatable with old code:
import cv2 as cv
For test navegation on Express
:
const request = require('supertest');
const server = require('../bin/www');
describe('navegation', () => {
it('login page', function(done) {
this.timeout(4000);
const timeOut = setTimeout(done, 3500);
request(server)
.get('/login')
.expect(200)
.then(res => {
res.text.should.include('Login');
clearTimeout(timeOut);
done();
})
.catch(err => {
console.log(this.test.fullTitle(), err);
clearTimeout(timeOut);
done(err);
});
});
});
In the example the test time is 4000 (4s).
Note: setTimeout(done, 3500)
is minor for than done
is called within the time of the test but clearTimeout(timeOut)
it avoid than used all these time.
This my variant of the solution based on LINQ and the Descendants method of the XDocument
class
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument xml = XDocument.Parse(@"
<root>
<child id='1'/>
<child id='2'>
<subChild id='3'>
<extChild id='5' />
<extChild id='6' />
</subChild>
<subChild id='4'>
<extChild id='7' />
</subChild>
</child>
</root>");
xml.Descendants().Where(p => p.Name.LocalName == "extChild")
.ToList()
.ForEach(e => Console.WriteLine(e));
Console.ReadLine();
}
}
It is possible! Yes
In many cases, you might want to use XAMPP with a different PHP version than the one that comes preinstalled. You might do this to get the benefits of a newer version of PHP, or to reproduce bugs using an earlier version of PHP.
To use a different version of PHP with XAMPP, follow these steps:
Download a binary build of the PHP version that you wish to use from the PHP website, and extract the contents of the compressed archive file to your XAMPP installation directory (usually, C:\xampp). Ensure that you give it a different directory name to avoid overwriting the existing PHP version. For example, in this tutorial, we’ll call the new directory
C:\xampp\php5-6-0
. NOTE : Ensure that the PHP build you download matches the Apache build (VC9 or VC11) in your XAMPP platform.Within the new directory, rename the php.ini-development file to php.ini. If you prefer to use production settings, you could instead rename the php.ini-production file to php.ini.
Edit the httpd-xampp.conf file in the apache\conf\extra\ subdirectory of your XAMPP installation directory. Within this file, search for all instances of the old PHP directory path and replace them with the path to the new PHP directory created in Step 1. In particular, be sure to change the lines
LoadFile "/xampp/php/php5ts.dll"
LoadFile "/xampp/php/libpq.dll"
LoadModule php5_module "/xampp/php/php5apache2_4.dll"
to
LoadFile "/xampp/php5-6-0/php5ts.dll"
LoadFile "/xampp/php5-6-0/libpq.dll"
LoadModule php5_module "/xampp/php5-6-0/php5apache2_4.dll"
NOTE : Remember to adjust the file and directory paths above to reflect valid paths on your system.
- Restart your Apache server through the XAMPP control panel for your changes to take effect. The new version of PHP should now be active. To verify this, browse to the URL
http://localhost/xampp/phpinfo.php
, which displays the output of the phpinfo() command, and check the version number at the top of the page.
Change your div
into a flex container:
div { display:flex; }
Now there are two methods to center the alignments for all the content:
Method 1:
div { align-items:center; }
Method 2:
div * { margin-top:auto; margin-bottom:auto; }
Try different width and height values on the img
and different font size values on the span
and you'll see they always remain in the middle of the container.
Use regular expression no need to convert it to char array
if(Regex.IsMatch("yourString",".*?[a-zA-Z].*?"))
{
errorCounter++;
}
from flask import request
request.headers.get('your-header-name')
request.headers
behaves like a dictionary, so you can also get your header like you would with any dictionary:
request.headers['your-header-name']
I just looked at code that did this today. This is a variation on AviewAnew's answer.
collectionOfStrings = /* source string collection */;
String csList = StringUtils.join(collectionOfStrings.toArray(), ",");
The StringUtils ( <-- commons.lang 2.x, or commons.lang 3.x link) we used is from Apache Commons.
It could also be wrong Segue Identifier Name. Eg -
performSegueWithIdentifier("wrongSegueName", sender: self)
You can, but the variable in your last include will overwrite the variable in your first one:
myfile.php
$var = 'test';
mysecondfile.php
$var = 'tester';
test.php
include 'myfile.php';
echo $var;
include 'mysecondfile.php';
echo $var;
Output:
test
tester
I suggest using different variable names.
I have really looked at a lot of ideas, the only solution was this way (works with different email Providers):
try
{
ViewProgressbar("Try to connect mail-server...", progressBar1.Value = 20);
string host = dsProvider.Rows[y]["POP_hostOut"].ToString();
int port = int.Parse(dsProvider.Rows[y]["POP_portOut"].ToString()); //587
string[] email = von1.Split('@');
string userName = (dsProvider.Rows[y]["login"].ToString() == "email[0]@email[1]")? email[0]+"@"+email[1] : email[0];
string password = layer.getUserPassword(listSender.SelectedValue.ToString());
SmtpClient client = new SmtpClient(host, port);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
//A idea from MSDN but it not works. You got "The server response was: 5.5.1 Authentication Required."
//System.Net.NetworkCredential myCreds = new System.Net.NetworkCredential(userName, password, host);
//System.Net.CredentialCache cache = new System.Net.CredentialCache();
//cache.Add(host, port, "NTLM", myCreds);
///cache.GetCredential(host, port, "NTLM"); //NTLM
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Host = host;
client.Port = port;
client.EnableSsl = true;
client.Send(message);
ViewProgressbar();
}
catch (SmtpException ex)...
if you want to upgrade only a single column of a table row then you can use as following:
$this->db->set('column_header', $value); //value that used to update column
$this->db->where('column_id', $column_id_value); //which row want to upgrade
$this->db->update('table_name'); //table name
Thanks for David Brown's answer. In my case of JSON.Net 3.5, the convert methods are under the JsonConvert static class:
XmlNode myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString); // is node not note
// or .DeserilizeXmlNode(myJsonString, "root"); // if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);
<project name="Build" basedir="." default="clean">
<property name="default.build.type" value ="Release"/>
<target name="clean">
<echo>Value Buld is now ${PARAM_BUILD_TYPE} is set</echo>
<condition property="build.type" value="${PARAM_BUILD_TYPE}" else="${default.build.type}">
<isset property="PARAM_BUILD_TYPE"/>
</condition>
<echo>Value Buld is now ${PARAM_BUILD_TYPE} is set</echo>
<echo>Value Buld is now ${build.type} is set</echo>
</target>
</project>
In my Case DPARAM_BUILD_TYPE=Debug
if it is supplied than, I need to build for for Debug otherwise i need to go for building Release build.
I write like above condition it worked and i have tested as below it is working fine for me.
And property ${build.type}
we can pass this to other target or macrodef for processing which i am doing in my other ant macrodef.
D:\>ant -DPARAM_BUILD_TYPE=Debug
Buildfile: D:\build.xml
clean:
[echo] Value Buld is now Debug is set
[echo] Value Buld is now Debug is set
[echo] Value Buld is now Debug is set
main:
BUILD SUCCESSFUL
Total time: 0 seconds
D:\>ant
Buildfile: D:\build.xml
clean:
[echo] Value Buld is now ${PARAM_BUILD_TYPE} is set
[echo] Value Buld is now ${PARAM_BUILD_TYPE} is set
[echo] Value Buld is now Release is set
main:
BUILD SUCCESSFUL
Total time: 0 seconds
It work for me to implement condition so posted hope it will helpful.
sounds like you're looking for setInterval. It's as easy as this:
function FetchData() {
// do something
}
setInterval(FetchData, 60000);
if you only want to call something once, theres setTimeout.
Update: ICS emulator supports camera.
I had an issue with the proposed solutions, using lookup
does not always return the expected value.
This is due to DNS caching, the value of the call is cached and intead of doing a proper call on the next try it gives back the cached value. Of course this is an issue here as it means if you lose connectivity and call lookup
it could still return the cached value as if you had internet, and conversely, if you reconnect your internet after lookup
returned null it will still return null for the duration of the cache, which can be a few minutes, even if you do have internet now.
TL;DR: lookup
returning something does not necessarily mean you have internet, and it not returning anything does not necessarily mean you don't have internet. It is not reliable.
I implemented the following solution by taking inspiration from the data_connection_checker
plugin:
/// If any of the pings returns true then you have internet (for sure). If none do, you probably don't.
Future<bool> _checkInternetAccess() {
/// We use a mix of IPV4 and IPV6 here in case some networks only accept one of the types.
/// Only tested with an IPV4 only network so far (I don't have access to an IPV6 network).
final List<InternetAddress> dnss = [
InternetAddress('8.8.8.8', type: InternetAddressType.IPv4), // Google
InternetAddress('2001:4860:4860::8888', type: InternetAddressType.IPv6), // Google
InternetAddress('1.1.1.1', type: InternetAddressType.IPv4), // CloudFlare
InternetAddress('2606:4700:4700::1111', type: InternetAddressType.IPv6), // CloudFlare
InternetAddress('208.67.222.222', type: InternetAddressType.IPv4), // OpenDNS
InternetAddress('2620:0:ccc::2', type: InternetAddressType.IPv6), // OpenDNS
InternetAddress('180.76.76.76', type: InternetAddressType.IPv4), // Baidu
InternetAddress('2400:da00::6666', type: InternetAddressType.IPv6), // Baidu
];
final Completer<bool> completer = Completer<bool>();
int callsReturned = 0;
void onCallReturned(bool isAlive) {
if (completer.isCompleted) return;
if (isAlive) {
completer.complete(true);
} else {
callsReturned++;
if (callsReturned >= dnss.length) {
completer.complete(false);
}
}
}
dnss.forEach((dns) => _pingDns(dns).then(onCallReturned));
return completer.future;
}
Future<bool> _pingDns(InternetAddress dnsAddress) async {
const int dnsPort = 53;
const Duration timeout = Duration(seconds: 3);
Socket socket;
try {
socket = await Socket.connect(dnsAddress, dnsPort, timeout: timeout);
socket?.destroy();
return true;
} on SocketException {
socket?.destroy();
}
return false;
}
The call to _checkInternetAccess
takes at most a duration of timeout
to complete (3 seconds here), and if we can reach any of the DNS it will complete as soon as the first one is reached, without waiting for the others (as reaching one is enough to know you have internet). All the calls to _pingDns
are done in parallel.
It seems to work well on an IPV4 network, and when I can't test it on an IPV6 network (I don't have access to one) I think it should still work. It also works on release mode builds, but I yet have to submit my app to Apple to see if they find any issue with this solution.
It should also work in most countries (including China), if it does not work in one you can add a DNS to the list that is accessible from your target country.
Remove the public
keyword from int[] locations={1,2,3};
. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.
If your goal is to use this reference in many a method, you might want to move the declaration outside the method.
you can get value of checkbox and status by
$('.i-checks').on('ifChanged', function(event) {
alert('checked = ' + event.target.checked);
alert('value = ' + event.target.value);
});
Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.
Also based on your markup your selector is wrong. it should be #advisersDiv
function fadeIn() {
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
setTimeout(fadeOut,1); //<-- Provide any delay here
};
function fadeOut() {
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();
In my app/build.gradle file , version code was like this:-
In place of versionCode flutterVersionCode.toInteger() , i replaced it with as versionCode 2
You can use typeof
:
if (typeof pagetype === 'undefined') {
// pagetype doesn't exist
}
Try this, it will combine your arrays removing duplicates
array1 = ["foo", "bar"]
array2 = ["foo1", "bar1"]
array3 = array1|array2
http://www.ruby-doc.org/core/classes/Array.html
Further documentation look at "Set Union"
I found this nice code on web.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Unicode {
public static void main(String[] args) {
System.out.println("Use CTRL+C to quite to program.");
// Create the reader for reading in the text typed in the console.
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
try {
String line = null;
while ((line = bufferedReader.readLine()).length() > 0) {
for (int index = 0; index < line.length(); index++) {
// Convert the integer to a hexadecimal code.
String hexCode = Integer.toHexString(line.codePointAt(index)).toUpperCase();
// but the it must be a four number value.
String hexCodeWithAllLeadingZeros = "0000" + hexCode;
String hexCodeWithLeadingZeros = hexCodeWithAllLeadingZeros.substring(hexCodeWithAllLeadingZeros.length()-4);
System.out.println("\\u" + hexCodeWithLeadingZeros);
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
Your code does work (tested with cpython 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2):
>>> a = set(["Blah", "Hello"])
>>> a = list(a) # You probably wrote a = list(a()) here or list = set() above
>>> a
['Blah', 'Hello']
Check that you didn't overwrite list
by accident:
>>> assert list == __builtins__.list
\
does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character.
Consider this command:
mysql -uroot \ -hlocalhost
If there is a space after \
, the line continuation will not work. The reason is that \
removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \
in this example.
Here's an alternative regular expression:
^(?=(.{4})*$)[A-Za-z0-9+/]*={0,2}$
It satisfies the following conditions:
(?=^(.{4})*$)
[A-Za-z0-9+/]*
={0,2}
SortedSet and Comparator. Comparator should honour the id field.
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
Compilr seems to be going in that direction: http://compilr.com/teachers
Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not.
However, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could have over-written the file.
for example:
filename = 'cd.pkl'
with open(filename, 'wb') as f:
classification_dict = pickle.load(f)
This will over-write the pickled file. You might have done this by mistake before using:
...
open(filename, 'rb') as f:
And then got the EOFError because the previous block of code over-wrote the cd.pkl file.
When working in Jupyter, or in the console (Spyder) I usually write a wrapper over the reading/writing code, and call the wrapper subsequently. This avoids common read-write mistakes, and saves a bit of time if you're going to be reading the same file multiple times through your travails
I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60
returns nothing. The command find . -mmin -60 |xargs ls -l
, however, returns every file in the directory which is consistent with what happens when ls -l
is run without an argument.
To make sure that ls -l
is only run when a file is found, try:
find . -mmin -60 -type f -exec ls -l {} +
as System environment Variable:
Windows:
Start -> type "envi" select environment variables and add a new:
Name: spring_profiles_active
Value: dev
(or whatever yours is)
Linux: add following line to /etc/environment under PATH:
spring_profiles_active=prod
(or whatever profile is)
then also export spring_profiles_active=prod
so you have it in the runtime now.
Try /[^;]*/
Google regex character classes
for details.
Do not forget that you also can pass these use
variables by reference.
The use cases are when you need to change the use
'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).
$sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
$newarray = [];
array_walk($sourcearray, function ($item) use (&$newarray) {
$newarray[] = (object) ['times2' => $item->a * 2];
});
var_dump($newarray);
Now $newarray
will comprise (pseudocode here for brevity) [{times2:2},{times2:4}]
.
On the contrary, using $newarray
with no &
modifier would make outer $newarray
variable be read-only accessible from within the closure scope. But $newarray
within closure scope would be a completelly different newly created variable living only within the closure scope.
Despite both variables' names are the same these would be two different variables. The outer $newarray
variable would comprise []
in this case after the code has finishes.
I found other answers to be inaccurate/outdated. Best is to refer to the actual documentation.
Short version: in most cases gem update --system
will suffice.
You should not blindly use sudo
. In fact if you're not required to do so you most likely should not use it.
strcat
concats str2
onto str1
You'll get runtime errors because str1
is not being properly allocated for concatenation
I encountered this same symptom and none of the solutions above were helpful. I finally got a stack trace of the problem by importing the ear project again to eclipse, and was able to trace this down to the org.eclipse.m2e.wtp.MavenDeploymentDescriptorManagement which was trying to delete a directory in windows' temp directory called ".mavenDeploymentDescriptorManagement", which caused an irrational NullPointerException from the java.io.File.exists() method, particularly because the code already had successfully done the same thing in a previous method with the same variable, then called file.isFile() without problem.
Checking this out on the file system revealed that the file could only be accessed with administrator privileges. Apparently I had at some point launched eclipse from an administrator console by mistake. In the end I just made hidden files visible in windows explorer and deleted the temporary file manually, which solved the problem.
The workaround is simple. Just use the Uri().ToString() method and percent-encode white-spaces, if any, afterwards.
string path = new Uri("C:\my example?.txt").ToString().Replace(" ", "%20");
properly returns file:///C:/my%20example?.txt
Based on the previous answer,
from urllib.request import Request, urlopen
#specify url
url = 'https://xyz/xyz'
req = Request(url, headers={'User-Agent': 'XYZ/3.0'})
response = urlopen(req, timeout=20).read()
This worked for me by extending the timeout.
AllDogs.First(d => d.Id == "2").Name = "some value";
However, a safer version of that might be this:
var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }
Since the above answers clearly explains how to play safely with Optionals. I will try explain what Optionals are really in swift.
Another way to declare an optional variable is
var i : Optional<Int>
And Optional type is nothing but an enumeration with two cases, i.e
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some(Wrapped)
.
.
.
}
So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)
According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil
We have to conform to a protocol called ExpressibleByNilLiteral
and great if you guessed it, only Optionals
conform to ExpressibleByNilLiteral
and conforming to other types is discouraged.
ExpressibleByNilLiteral
has a single method called init(nilLiteral:)
which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil
literal.
Even myself has to wrap (no pun intended) my head around Optionals :D Happy Swfting All.
Sometimes it is not eligible to set height to pixel values.
However, it is possible to show vertical scrollbar through setting height of div to 100%
and overflow
to auto
.
Let me show an example:
<div id="content" style="height: 100%; overflow: auto">
<p>some text</p>
<ul>
<li>text</li>
.....
<li>text</li>
</div>
In cases wherein the width/height of the space is beyond
I usually use:
For horizontal spacer:
<span style="display:inline-block; width: YOURWIDTH;"></span>
For vertical spacer:
<span style="display:block; height: YOURHEIGHT;"></span>
For ASP.NET web pages (not MVC), you can use Sys.UI.DomEvent
object as wrapper of native event.
<div onclick="event.stopPropagation();" ...
or, pass event as a parameter to inner function:
<div onclick="someFunction(event);" ...
and in someFunction:
function someFunction(event){
event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
// other onclick logic
}
For someone who need to update the PHP version in WAMP, I can recommend this http://wampserver.aviatechno.net/
I had a problems with updating too, but on this website are Wampserver addons like new php version (php 7.1.4 etc.) And you don't have to manually edit files like php.ini or phpForApache.
Enjoy!
You should be using pip
to install packages, since it gives you uninstall capabilities.
Also, look into virtualenv
. It works well with pip
and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.
You can use LOWER function
and UPPER function
. Like
SELECT LOWER('THIS IS TEST STRING')
Result:
this is test string
And
SELECT UPPER('this is test string')
result:
THIS IS TEST STRING
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
Just to summarize the available options:
Tools
Browsers
Other
Please feel free to edit/add new items
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
There are several problems here:
DateTime.Now
instead of Start
DateTime.Now
is a value of type DateTime
, not Integer
, so the assignment wouldn't work anywayStart
variable anyway; it's doing no goodtotal.Text
is a property of type String
- not DateTime
or Integer
(Some of these would only show up at execution time unless you have Option Strict
on, which you really should.)
You should use:
total.Text = DateTime.Now.ToString()
... possibly specifying a culture and/or format specifier if you want the result in a particular format.
For Windows (7), the same folder is located at,
%APPDATA%\Subversion\auth
Type in the above in the Run(Win key + R) dialog box and hit Enter,
To check the existing username open the below file as a text file,
%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx
You can use tool dpkg for managing packages in Debian operating system.
dpkg --get-selections | grep mysql
if it's listed as installed, you got it. Else you need to get it.
Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))
SELECT Count([MSysObjects].[Name]) AS [Count]
FROM MSysObjects
WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));
Yes, but none of them will manage to produce readable enough code to worth the effort. You will spend more time trying to read the decompiled source with assembler blocks inside, than rewriting your old app from scratch.
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
The key is already the ... ehm ... key
echo $array[20120504];
If you are unsure, if the key exists, test for it
$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;
Minor addition:
$result = @$array[$key] ?: null;
One may argue, that @
is bad, but keep it serious: This is more readable and straight forward, isn't?
Update: With PHP7 my previous example is possible without the error-silencer
$result = $array[$key] ?? null;
You can write your php file to the action
attr of form element.
At the php side you can get the form value by $_POST['element_name']
.
Using function Find is cleaner way.
MyClass item = MyList.Find(item => item.name == "foo");
if (item != null) // check item isn't null
{
....
}
Don't use delete
to remove an item from array and use splice()
instead.
this.data.splice(this.data.indexOf(msg), 1);
See a similar question: How do I remove a particular element from an array in JavaScript?
Note, that TypeScript is a superset of ES6 (arrays are the same in both TypeScript and JavaScript) so feel free to look for JavaScript solutions even when working with TypeScript.
Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :
<div id="searchbycharacter">
<a class="searchbychar" href="#" data-target="numeric">0-9 |</a>
<a class="searchbychar" href="#" data-target="A"> A |</a>
<a class="searchbychar" href="#" data-target="B"> B |</a>
<a class="searchbychar" href="#" data-target="C"> C |</a>
... Untill Z
</div>
As for the jquery :
$(document).on('click','.searchbychar', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
https://developer.apple.com/reference/foundation/userdefaults
A default object must be a property list—that is, an instance of (or for collections, a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.
When we are dealing with time-series, calculating z-scores (or anomalies - not the same thing, but you can adapt this code easily) is a bit more complicated. For example, you have 10 years of temperature data measured weekly. To calculate z-scores for the whole time-series, you have to know the means and standard deviations for each day of the year. So, let's get started:
Assume you have a pandas DataFrame. First of all, you need a DateTime index. If you don't have it yet, but luckily you do have a column with dates, just make it as your index. Pandas will try to guess the date format. The goal here is to have DateTimeIndex. You can check it out by trying:
type(df.index)
If you don't have one, let's make it.
df.index = pd.DatetimeIndex(df[datecolumn])
df = df.drop(datecolumn,axis=1)
Next step is to calculate mean and standard deviation for each group of days. For this, we use the groupby method.
mean = pd.groupby(df,by=[df.index.dayofyear]).aggregate(np.nanmean)
std = pd.groupby(df,by=[df.index.dayofyear]).aggregate(np.nanstd)
Finally, we loop through all the dates, performing the calculation (value - mean)/stddev; however, as mentioned, for time-series this is not so straightforward.
df2 = df.copy() #keep a copy for future comparisons
for y in np.unique(df.index.year):
for d in np.unique(df.index.dayofyear):
df2[(df.index.year==y) & (df.index.dayofyear==d)] = (df[(df.index.year==y) & (df.index.dayofyear==d)]- mean.ix[d])/std.ix[d]
df2.index.name = 'date' #this is just to look nicer
df2 #this is your z-score dataset.
The logic inside the for loops is: for a given year we have to match each dayofyear to its mean and stdev. We run this for all the years in your time-series.
<a name='fb_share' type='button_count' href='http://www.facebook.com/sharer.php?appId={YOUR APP ID}&link=<?php the_permalink() ?>' rel='nofollow'>Share</a><script src='http://static.ak.fbcdn.net/connect.php/js/FB.Share' type='text/javascript'></script>
The assertion libraries in Mocha work by throwing an error if the assertion was not correct. Throwing an error results in a rejected promise, even when thrown in the executor function provided to the catch
method.
.catch((error) => {
assert.isNotOk(error,'Promise error');
done();
});
In the above code the error
objected evaluates to true
so the assertion library throws an error... which is never caught. As a result of the error the done
method is never called. Mocha's done
callback accepts these errors, so you can simply end all promise chains in Mocha with .then(done,done)
. This ensures that the done method is always called and the error would be reported the same way as when Mocha catches the assertion's error in synchronous code.
it('should transition with the correct event', (done) => {
const cFSM = new CharacterFSM({}, emitter, transitions);
let timeout = null;
let resolved = false;
new Promise((resolve, reject) => {
emitter.once('action', resolve);
emitter.emit('done', {});
timeout = setTimeout(() => {
if (!resolved) {
reject('Timedout!');
}
clearTimeout(timeout);
}, 100);
}).then(((state) => {
resolved = true;
assert(state.action === 'DONE', 'should change state');
})).then(done,done);
});
I give credit to this article for the idea of using .then(done,done) when testing promises in Mocha.
I came up with a React component – check it out if you use React or browse the source code if you don't, so you can adapt it to your environment.
It sets the fullscreen div's height to window.innerHeight
and then updates it on window resizes.
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...