How do I create PDF's in FPDF that support Chinese, Japanese, Russian, etc.?
(snapshots of code in use below)
I'd like to provide: a summary of the problem, the solution, a github project with the working code, and an online example with the expected, resultant PDF.
The Problem :
You actually need a font that supports the UTF-8 characters you are using.
I.E., merely using Helvetica and trying to display Japanese will not work. If you use Font Forge, or some other font tool, you can scroll to the Chinese characters of the font, and see that they are blank.
Google has a font (Noto font) that contains all languages, and it is 20mb, which is usually several factors the size of your text. So, you can see why many fonts simply won't cover every single language.
The Solution :
I'm using rounded-mgenplus-20140828.ttf and ZCOOL_QingKe_HuangYou.ttf font packs for Japanese and Chinese, which are open source and can be found in many open source projects. In tFPDF itself, or a new inheriting class of it, like class HTMLtoPDF extends tFPDF {...}
, you'll do this...
$this->AddFont('japanese', '', 'rounded-mgenplus-20140828.ttf', true);
$this->SetFont('japanese', '', 14);
$this->Write(14, '???');
Should be nothing more to it!
Code Package on GitHub :
https://github.com/HoldOffHunger/php-html-to-pdf
Working, Online Demo of Japanese :
Place this meta tag after head tag
<meta http-equiv="x-ua-compatible" content="IE=edge">
How to make form minimize when closing was already answered, but how to remove the minimize and maximize buttons wasn't.
FormBorderStyle
: FixedDialog
MinimizeBox
: false
MaximizeBox
: false
There's a bunch of functions to trim strings in go.
See them there : Trim
Here's an example, adapted from the documentation, removing leading and trailing white spaces :
fmt.Printf("[%q]", strings.Trim(" Achtung ", " "))
just give
a{
color:blue
}
even if its is visited it will always be blue
.fadeOut{
background-color: rgba(255, 0, 0, 0.83);
border-radius: 8px;
box-shadow: silver 3px 3px 5px 0px;
border: 2px dashed yellow;
padding: 3px;
}
.fadeOut.end{
transition: all 1s ease-in-out;
background-color: rgba(255, 0, 0, 0.0);
box-shadow: none;
border: 0px dashed yellow;
border-radius: 0px;
}
This will give you the second row of each group (zero indexed, nth(0) is the same as first()):
df.groupby('id').nth(1)
Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group
# Open the file
f = open('morseCode.txt', 'r')
# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
if not Line.strip(): break
letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
letters.append((letter.lower(), code))
f.close()
# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ")
# Convert the codes to morse code
out = []
for c in i:
found = False
for letter, code in letters:
if letter == c.lower():
found = True
out.append(code)
break
if not found:
raise Exception('invalid character: %s' % c)
# Print the output
print ' '.join(out)
Eclipse failed to connect to SVN https repositories (should also apply to any app using SSL/TLS).
svn: E175002: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints
The issue was caused by latest Java 8 OpenJDK update that disabled MD5 related algorithms. As a workaround until new certificates are issued (if ever), change the following keys at java.security file
WARNING
Keep in mind that this could have security implications as disabled algorithms are considered weak. As an alternative, the workaround can be applied on a JVM basis by a command line option to use an external java.security file with this changes, e.g.:
java -Djava.security.properties=/etc/sysconfig/noMD5.java.security
For Eclipse, add a line on eclipse.ini below -vmargs
-Djava.security.properties=/etc/sysconfig/noMD5.java.security
jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768
jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, DH keySize < 768
java.security file is located in linux 64 at /usr/lib64/jvm/java/jre/lib/security/java.security
On old versions of Debian and Ubuntu, you solved this by installing the Curl extension for PHP, and restarting the webserver. Assuming the webserver is Apache 2:
sudo apt-get install php5-curl
sudo service apache2 restart
On newer versions, the package name as changed:
sudo apt install php-curl
It's possible you'll need to install more:
sudo apt-get install curl libcurl3 libcurl3-dev;
This should work with any div
or screen size:
.center-screen {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
min-height: 100vh;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="center-screen">_x000D_
I'm in the center_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
See more details about flex
here. This should work on most of the browsers, see compatibility matrix here.
Nexus 5 with Win7 x64
-USB computer connection : Uncheck MTP and PTP
-Use a 2.0 USB port.
-Try to use the original USB cable.
Now device manager will detect nexus 5 as an androide device with ADB driver.
I didn't have the name in my Input ... my request was empty... glad that is finished and I can keep coding. Thanks everyone!
Answer I used by Jason Kim:
So instead of
<input type="password" class="form-control" id="password">
I have this
<input type="password" class="form-control" id="password" name="password">
In this line ...
if (*message == "\0") {
... as you can see in the warning ...
warning: comparison between pointer and integer ('int' and 'char *')
... you are actually comparing an int
with a char *
, or more specifically, an int
with an address to a char
.
To fix this, use one of the following:
if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...
On a side note, if you'd like to compare strings you should use strcmp
or strncmp
, found in string.h
.
Step 1: convert the string to an array using the str_split
function
$array = str_split($your_string);
Step 2: loop through the newly created array
foreach ($array as $char) {
echo $char;
}
You can check the PHP docs for more information: str_split
You can use this to get remaining charged in percentage.
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
batterLevel.setText("Battery Level Remaining: " + level + "%");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
Check "PASSWORD_LIFE_TIME" by
Sql > select * from dba_profiles;
Set to Never expire
Sql> ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
Then reset the password of locked user.
typedef
is used to alias types; in this case you're aliasing FunctionFunc
to void(*)()
.
Indeed the syntax does look odd, have a look at this:
typedef void (*FunctionFunc) ( );
// ^ ^ ^
// return type type name arguments
No, this simply tells the compiler that the FunctionFunc
type will be a function pointer, it doesn't define one, like this:
FunctionFunc x;
void doSomething() { printf("Hello there\n"); }
x = &doSomething;
x(); //prints "Hello there"
Put a large div inside the div, center that, and the center the image inside that div.
This centers it horizontally:
HTML:
<div class="imageContainer">
<div class="imageCenterer">
<img src="http://placekitten.com/200/200" />
</div>
</div>
CSS:
.imageContainer {
width: 100px;
height: 100px;
overflow: hidden;
position: relative;
}
.imageCenterer {
width: 1000px;
position: absolute;
left: 50%;
top: 0;
margin-left: -500px;
}
.imageCenterer img {
display: block;
margin: 0 auto;
}
Demo: http://jsfiddle.net/Guffa/L9BnL/
To center it vertically also, you can use the same for the inner div, but you would need the height of the image to place it absolutely inside it.
None of the above answers worked for me using Hibernate 5.2.10, Jersey 2.25.1 and Jackson 2.8.9. I finally found the answer (sort of, they reference hibernate4module but it works for 5 too) here. None of the Json annotations worked at all with @Transient
. Apparently Jackson2 is 'smart' enough to kindly ignore stuff marked with @Transient
unless you explicitly tell it not to. The key was to add the hibernate5 module (which I was using to deal with other Hibernate annotations) and disable the USE_TRANSIENT_ANNOTATION
feature in my Jersey Application:
ObjectMapper jacksonObjectMapper = new ObjectMapper();
Hibernate5Module jacksonHibernateModule = new Hibernate5Module();
jacksonHibernateModule.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
jacksonObjectMapper.registerModule(jacksonHibernateModule);
Here is the dependency for the Hibernate5Module:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.8.9</version>
</dependency>
margin
to align images:Since we wanted the image
to be left-aligned
, we added:
img {
margin-right: auto;
}
Similarly for image
to be right-aligned
, we can add margin-right: auto;
. The snippet shows a demo for both types of alignment.
Good Luck...
div {_x000D_
display:flex; _x000D_
flex-direction:column;_x000D_
border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
text-align: center;_x000D_
}_x000D_
hr {_x000D_
border: 1px black solid;_x000D_
width: 100%_x000D_
}_x000D_
img.one {_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
<h1>Flex Box</h1>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="one" _x000D_
/>_x000D_
_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="two" _x000D_
/>_x000D_
_x000D_
<hr />_x000D_
</div>
_x000D_
I like the solution from
http://www.nautsch.net/2008/10/28/class-von-type-parameter-java-generics/
public class Dada<T> {
private Class<T> typeOfT;
@SuppressWarnings("unchecked")
public Dada() {
this.typeOfT = (Class<T>)
((ParameterizedType)getClass()
.getGenericSuperclass())
.getActualTypeArguments()[0];
}
...
Add into ~/.Rprofile
local({r <- getOption("repos")
r["CRAN"] <- "mirror_site" #for example, https://mirrors.ustc.edu.cn/CRAN/
options(repos=r)
options(BioC_mirror="bioc_mirror_site") #if using biocLite
})
I came across this while looking for an answer to my issue which was that I was trying to remove a table row then add it back in at the bottom of the table (because I was dynamically creating data rows but wanted to show an 'Add New Record' type row at the bottom).
I had the same issue, in that it was returning the innerHtml so was missing the TR tags, which held the ID of that row and meant it was impossible to repeat the procedure.
The answer I found was that the jquery remove()
function actually returns the element, that it removes, as an object. So, to remove and re-add a row it was as simple as this...
var a = $("#trRowToRemove").remove();
$('#tblMyTable').append(a);
If you're not removing the object but want to copy it somewhere else, use the clone()
function instead.
Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.
Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.
If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.
For a solution in Swift please refer to this thread on SO.
Basically the solution in Swift would look like this:
#if DEBUG
println("I'm running in DEBUG mode")
#else
println("I'm running in a non-DEBUG mode")
#endif
Additionally you will need to set the DEBUG
symbol in Swift Compiler - Custom Flags
section for the Other Swift Flags
key via a -D DEBUG
entry. See the following screenshot for an example:
Have you created a package.json file? Maybe run this command first again.
C:\Users\Nuwanst\Documents\NodeJS\3.chat>npm init
It creates a package.json file in your folder.
Then run,
C:\Users\Nuwanst\Documents\NodeJS\3.chat>npm install socket.io --save
The --save
ensures your module is saved as a dependency in your package.json file.
Let me know if this works.
Assuming, as seems to be the case, ${triningIdArray}
is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
var traingIds = ${triningIdArray};
not
var traingIds = "${triningIdArray}";
All answers describe specific cases, but there is a general answer:
You call the dtor explicitly every time you need to just destroy the object (in C++ sense) without releasing the memory the object resides in.
This typically happens in all the situation where memory allocation / deallocation is managed independently from object construction / destruction. In those cases construction happens via placement new upon an existent chunk of memory, and destruction happens via explicit dtor call.
Here is the raw example:
{
char buffer[sizeof(MyClass)];
{
MyClass* p = new(buffer)MyClass;
p->dosomething();
p->~MyClass();
}
{
MyClass* p = new(buffer)MyClass;
p->dosomething();
p->~MyClass();
}
}
Another notable example is the default std::allocator
when used by std::vector
: elements are constructed in vector
during push_back
, but the memory is allocated in chunks, so it pre-exist the element contruction. And hence, vector::erase
must destroy the elements, but not necessarily it deallocates the memory (especially if new push_back have to happen soon...).
It is "bad design" in strict OOP sense (you should manage objects, not memory: the fact objects require memory is an "incident"), it is "good design" in "low level programming", or in cases where memory is not taken from the "free store" the default operator new
buys in.
It is bad design if it happens randomly around the code, it is good design if it happens locally to classes specifically designed for that purpose.
Yes, Possible to download a folder instead of downloading the whole repository. Even any/last commit
Nice way to do this
D:\Lab>git svn clone https://github.com/Qamar4P/LolAdapter.git/trunk/lol-adapter -r HEAD
-r HEAD will only download last revision, ignore all history.
Note trunk and /specific-folder
Copy and change URL before and after /trunk/
. I hope this will help someone. Enjoy :)
Updated on 26 Sep 2019
The easiest solution is to toggleClass()
both classes individually.
Let's say you have an icon:
<i id="target" class="fa fa-angle-down"></i>
To toggle between fa-angle-down
and fa-angle-up
do the following:
$('.sometrigger').click(function(){
$('#target').toggleClass('fa-angle-down');
$('#target').toggleClass('fa-angle-up');
});
Since we had fa-angle-down
at the beginning without fa-angle-up
each time you toggle both, one leaves for the other to appear.
Today (2020.05.08) I perform tests for chosen solutions - for two cases: input date is ISO8601 string (Ad,Bd,Cd,Dd,Ed) and input date is timestamp (At, Ct, Dt). Solutions Bd,Cd,Ct not return js Date object as results, but I add them because they can be useful but I not compare them with valid solutions. This results can be useful for massive date parsing.
new Date
(Ad) is 50-100x faster than moment.js (Dd) for all browsers for ISO date and timestampnew Date
(Ad) is ~10x faster than parseDate
(Ed)Date.parse
(Bd) is fastest if wee need to get timestamp from ISO date on all browsersI perform test on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0. Solution parseDate
(Ed) use new Date(0)
and manually set UTC date components.
let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date
let ts = +'1589328000000'; // timestamp
let Ad = new Date(ds);
let Bd = Date.parse(ds);
let Cd = moment(ds);
let Dd = moment(ds).toDate();
let Ed = parseDate(ds);
let At = new Date(ts);
let Ct = moment(ts);
let Dt = moment(ts).toDate();
log = (n,d) => console.log(`${n}: ${+d} ${d}`);
console.log('from date string:', ds)
log('Ad', Ad);
log('Bd', Bd);
log('Cd', Cd);
log('Dd', Dd);
log('Ed', Ed);
console.log('from timestamp:', ts)
log('At', At);
log('Ct', Ct);
log('Dt', Dt);
function parseDate(dateStr) {
let [year,month,day] = dateStr.split(' ')[0].split('-');
let d=new Date(0);
d.setUTCFullYear(year);
d.setUTCMonth(month-1);
d.setUTCDate(day)
return d;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script>
This snippet only presents used soultions
_x000D_
Results for chrome
You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()
).
If so, just use unset()
:
unset($arr[1]);
The general idea of abstract classes and interfaces is to be extended/implemented by other classes (cannot be constructed alone) that use these general "settings" (some kind of a template), making it simple to set a specific-general behaviour for all the objects that later extend it.
An abstract class has regular methods set AND abstract methods. Extended classes can include unset methods after being extended by an abstract class. When setting abstract methods - they are defined by the classes that are extending it later.
Interfaces have the same properties as an abstract class, but includes only abstract methods, which could be implemented in an other class/es (and can be more than one interface to implement), this creates a more permanent-solid definishion of methods/static variables. Unlike the abstract class, you cannot add custom "regular" methods.
It is also possible to open the pdf link in a new window and let the browser handle the rest:
window.open(pdfUrl, '_blank');
or:
window.open(pdfUrl);
(document.body.outerHTML).constructor
will return String
. (take off .constructor
and that's your string)
That aughta do it :)
Here I found another good option to migrate your MongoDB data to Elasticsearch. A go daemon that syncs mongodb to elasticsearch in realtime. Its the Monstache. Its available at : Monstache
Below the initial setp to configure and use it.
Step 1:
C:\Program Files\MongoDB\Server\4.0\bin>mongod --smallfiles --oplogSize 50 --replSet test
Step 2 :
C:\Program Files\MongoDB\Server\4.0\bin>mongo
C:\Program Files\MongoDB\Server\4.0\bin>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.2
Server has startup warnings:
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Start the server with --bind_ip <address> to specify which IP
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
MongoDB Enterprise test:PRIMARY>
Step 3 : Verify the replication.
MongoDB Enterprise test:PRIMARY> rs.status();
{
"set" : "test",
"date" : ISODate("2019-01-18T11:39:00.380Z"),
"myState" : 1,
"term" : NumberLong(2),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"appliedOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"durableOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
}
},
"lastStableCheckpointTimestamp" : Timestamp(1547811517, 1),
"members" : [
{
"_id" : 0,
"name" : "localhost:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 736,
"optime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2019-01-18T11:38:57Z"),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1547810805, 1),
"electionDate" : ISODate("2019-01-18T11:26:45Z"),
"configVersion" : 1,
"self" : true,
"lastHeartbeatMessage" : ""
}
],
"ok" : 1,
"operationTime" : Timestamp(1547811537, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1547811537, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
MongoDB Enterprise test:PRIMARY>
Step 4.
Download the "https://github.com/rwynn/monstache/releases".
Unzip the download and adjust your PATH variable to include the path to the folder for your platform.
GO to cmd and type "monstache -v"
# 4.13.1
Monstache uses the TOML format for its configuration. Configure the file for migration named config.toml
Step 5.
My config.toml -->
mongo-url = "mongodb://127.0.0.1:27017/?replicaSet=test"
elasticsearch-urls = ["http://localhost:9200"]
direct-read-namespaces = [ "admin.users" ]
gzip = true
stats = true
index-stats = true
elasticsearch-max-conns = 4
elasticsearch-max-seconds = 5
elasticsearch-max-bytes = 8000000
dropped-collections = false
dropped-databases = false
resume = true
resume-write-unsafe = true
resume-name = "default"
index-files = false
file-highlighting = false
verbose = true
exit-after-direct-reads = false
index-as-update=true
index-oplog-time=true
Step 6.
D:\15-1-19>monstache -f config.toml
Right code of two ppl before ^_^
/* return true if values of array are empty
*/
function is_array_empty($arr){
if(is_array($arr)){
foreach($arr as $value){
if(!empty($value)){
return false;
}
}
}
return true;
}
Resolved answer: To copy a directory's content to another directory I use the next:
- name: copy consul_ui files
command: cp -r /home/{{ user }}/dist/{{ item }} /usr/share/nginx/html
with_items:
- "index.html"
- "static/"
It copies both items to the other directory. In the example, one of the items is a directory and the other is not. It works perfectly.
For React.js, you can do this with more readable code. Hope it helps.
handleCheckboxChange(e) {
console.log('value of checkbox : ', e.target.checked);
}
render() {
return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}
fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f: #lines count
for line in f:
num_lines += 1
num_lines_input = int (input("Enter line numbers: "))
if num_lines_input <= num_lines:
f = open(fname, "r")
for x in range(num_lines_input):
a = f.readline()
print(a)
else:
f = open(fname, "r")
for x in range(num_lines_input):
a = f.readline()
print(a)
print("Don't have", num_lines_input, " lines print as much as you can")
print("Total lines in the text",num_lines)
In programming, there are 2 main ways to measure time, with different results:
>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001 # took 0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075 # took 10 seconds and a bit
Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.
time.process_time()
Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.
Use time.perf_counter()
time.time()
also measures wall-clock time but can be reset, so you could go back in timetime.monotonic()
cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()
If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them
For people who want to do it with raw SQL, without using php, java, python etc.
SET SQL_SAFE_UPDATES = 0;
UPDATE db.table SET value=ceil(value/10)*10 where value not like '%0';
Use the location header flag:
curl -L <URL>
It's something they've built themselves - it's called Bigtable.
http://en.wikipedia.org/wiki/BigTable
There is a paper by Google on the database:
I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).
public class StringTest {
public static void main(String[] args) {
String[] errorSoon = new String[100];
errorSoon[0] = "Error, why?";
//another approach would be direct initialization
String[] errorsoon = {"Error , why?"};
}
}
If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok
While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.
@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)
It happened to me when Eclipse(Luna)/AndroidSDK(not Android Stduio) were used with the latest tools and library as of Jan. 14, 2015 during the project like HelloWorld. When I installed those tools and made HelloWorld the first app, I accepted all the defaults. - This is the problem in my case.
First, check whether or not the "Android Support Library" library is installed. If not, install it. It is not installed by default. You may do it all in "Android SDK manager" available in the menu.
(Android SDK Manager -> Extra -> Android Support Library)
Blessings, (a debtor)<><
I had this same problem and it turns out I had a '\' instead of a '/' in the xml tag. It still gave the same error but just due to a syntax problem.
If you are using this to get a LINQ to SQL which I do and wanted for my Visual Developer, 1) get the free Visual WEB Developer, use that to connect to SQL Server instance, create your LINQ interface, then copy the generated files into your Vis-Dev project (I don't use VD because it sounds funny). Include only the *.dbml files. The Vis-Dev environment will take a second or two to recognize the supporting files. It is a little extra step but for sure better than doing it by hand or giving up on it altogether or EVEN WORSE, paying for it. Mooo ha ha haha.
array = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
col1 = [val[1] for val in array]
col2 = [val[2] for val in array]
col3 = [val[3] for val in array]
col4 = [val[4] for val in array]
print(col1)
print(col2)
print(col3)
print(col4)
Output:
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
I've had the same problem for a long time. What I recently chose is the following directory structure:
project_path
+-- Makefile
+-- src
¦ +-- script_1.py
¦ +-- script_2.py
¦ +-- script_3.py
+-- tests
+-- __init__.py
+-- test_script_1.py
+-- test_script_2.py
+-- test_script_3.py
and in the __init__.py
script of the test folder, I write the following:
import os
import sys
PROJECT_PATH = os.getcwd()
SOURCE_PATH = os.path.join(
PROJECT_PATH,"src"
)
sys.path.append(SOURCE_PATH)
Super important for sharing the project is the Makefile, because it enforces running the scripts properly. Here is the command that I put in the Makefile:
run_tests:
python -m unittest discover .
The Makefile is important not just because of the command it runs but also because of where it runs it from. If you would cd in tests and do python -m unittest discover .
, it wouldn't work because the init script in unit_tests calls os.getcwd(), which would then point to the incorrect absolute path (that would be appended to sys.path and you would be missing your source folder). The scripts would run since discover finds all the tests, but they wouldn't run properly. So the Makefile is there to avoid having to remember this issue.
I really like this approach because I don't have to touch my src folder, my unit tests or my environment variables and everything runs smoothly.
Let me know if you guys like it.
Hope that helps,
Yes, but you can select only one column in your subselect
SELECT (SELECT id FROM bla) AS my_select FROM bla2
If you get the "Failed to find DDMS files..." do this:
Don't be alarmed that its not https, this helps to fetch stuff over http. This trick helped me to resolve the issue on MAC, I believe that this also should work on Windows / Linux
Hope this helps !
ENGINE=MEMORY
is not supported when table contains BLOB
/TEXT
columns
I traced my problem back to the Puma server as did @Ahmed Elkoussy, but I solved just by commenting the following line on the puma.rb file:
# pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id
and date
.
ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);
Then when inserting a record add the condition when a conflict is encountered:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value
This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms. Hope it helps someone using Swift.
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
PhpStorm supports all the features of WebStorm but some are not bundled so you might need to install the corresponding plugin for some framework via Settings > Plugins > Install JetBrains Plugin.
I think using okhttp is the easiest solution. Here you can see an example for POST method, sending a json, and with auth.
val url = "https://example.com/endpoint"
val client = OkHttpClient()
val JSON = MediaType.get("application/json; charset=utf-8")
val body = RequestBody.create(JSON, "{\"data\":\"$data\"}")
val request = Request.Builder()
.addHeader("Authorization", "Bearer $token")
.url(url)
.post(body)
.build()
val response = client . newCall (request).execute()
println(response.request())
println(response.body()!!.string())
Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
UPDATE: July 7th, 2019 I'm gonna give two examples using latest Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).
UPDATE: January 25th, 2021 Everything is okay with the most updated versions.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-kotlin -->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
<version>2.12.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
Get Method
fun get() {
val client = OkHttpClient()
val url = URL("https://reqres.in/api/users?page=2")
val request = Request.Builder()
.url(url)
.get()
.build()
val response = client.newCall(request).execute()
val responseBody = response.body!!.string()
//Response
println("Response Body: " + responseBody)
//we could use jackson if we got a JSON
val mapperAll = ObjectMapper()
val objData = mapperAll.readTree(responseBody)
objData.get("data").forEachIndexed { index, jsonNode ->
println("$index $jsonNode")
}
}
POST Method
fun post() {
val client = OkHttpClient()
val url = URL("https://reqres.in/api/users")
//just a string
var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"
//or using jackson
val mapperAll = ObjectMapper()
val jacksonObj = mapperAll.createObjectNode()
jacksonObj.put("name", "Rolando")
jacksonObj.put("job", "Fakeador")
val jacksonString = jacksonObj.toString()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jacksonString.toRequestBody(mediaType)
val request = Request.Builder()
.url(url)
.post(body)
.build()
val response = client.newCall(request).execute()
val responseBody = response.body!!.string()
//Response
println("Response Body: " + responseBody)
//we could use jackson if we got a JSON
val objData = mapperAll.readTree(responseBody)
println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
}
I would give the requests library a try for this. Essentially just a much easier to use wrapper around the standard library modules (i.e. urllib2, httplib2, etc.) you would use for the same thing. For example, to fetch json data from a url that requires basic authentication would look like this:
import requests
response = requests.get('http://thedataishere.com',
auth=('user', 'password'))
data = response.json()
For kerberos authentication the requests project has the reqests-kerberos library which provides a kerberos authentication class that you can use with requests:
import requests
from requests_kerberos import HTTPKerberosAuth
response = requests.get('http://thedataishere.com',
auth=HTTPKerberosAuth())
data = response.json()
Your Mac does indeed run a BASH shell, but this is more a question of which implementation of sed you are dealing with. On a Mac sed comes from BSD and is subtly different from the sed you might find on a typical Linux box. I suggest you man sed
.
If I understand your question correctly, I've made a fiddle that has this working correctly. This issue is with how you're assigning the event handlers and as others have said you have over riding event handlers. The current jQuery best practice is to use on()
to register event handlers. Here's a link to the jQuery docs about on
: link
Your original solution was pretty close but the way you added the event handlers is a bit confusing. It's considered best practice to not add events to HTML elements. I recommend reading up on Unobstrusive JavaScript.
Here's the JavaScript code. I added a counter variable so you can see that it is working correctly.
$('#answer').on('click', function() {
feedback('hey there');
});
var counter = 0;
function feedback(message) {
$('#feedback').remove();
$('.answers').append('<div id="feedback">' + message + ' ' + counter + '</div>');
counter++;
}
git status
output tells you three things by default:
When you did git commit
, it committed to your local repository, thus #3 shows nothing to commit, however, #2 should show that you need to push or pull if you have setup the tracking branch.
If you find the output of git status verbose and difficult to comprehend, try using git status -sb
this is less verbose and will show you clearly if you need to push or pull. In your case, the output would be something like:
master...origin/master [ahead 1]
git status
is pretty useful, in the workflow you described do a git status -sb
: after touching the file, after adding the file and after committing the file, see the difference in the output, it will give you more clarity on untracked, tracked and committed files.
Update #1
This answer is applicable if there was a misunderstanding in reading the git status output. However, as it was pointed out, in the OPs case, the upstream was not set correctly. For that, Chris Mae's answer is correct.
<script type="text/javascript">
function BindEvents() {
$(document).ready(function() {
$(".tr-base").mouseover(function() {
$(this).toggleClass("trHover");
}).mouseout(function() {
$(this).removeClass("trHover");
});
}
</script>
The area which is going to be updated.
<asp:UpdatePanel...
<ContentTemplate
<script type="text/javascript">
Sys.Application.add_load(BindEvents);
</script>
*// Staff*
</ContentTemplate>
</asp:UpdatePanel>
CDATA stands for Character Data. You can use this to escape some characters which otherwise will be treated as regular XML. The data inside this will not be parsed.
For example, if you want to pass a URL that contains &
in it, you can use CDATA to do it. Otherwise, you will get an error as it will be parsed as regular XML.
try this:
$('form').submit(function(){
// this function will be raised when submit button is clicked.
// perform submit operations here
});
Use the .text()
function:
var text = $("<p> example ive got a string</P>").text();
Update: As Brilliand points out below, if the input string does not contain any tags and you are unlucky enough, it might be treated as a CSS selector. So this version is more robust:
var text = $("<div/>").html("<p> example ive got a string</P>").text();
How about this ? checking for length of undefined array may throw exception.
if(image_array){
//array exists
if(image_array.length){
//array has length greater than zero
}
}
I had the same problem. If you have installed first nodejs by apt and then you use the tar.gz from nodejs.org, you have to delete the folder located in /usr/lib/node_modules
.
Try with Beautifulsoup:
from BeautifulSoup import BeautifulSoup
import urllib2
import re
html_page = urllib2.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page)
for link in soup.findAll('a'):
print link.get('href')
In case you just want links starting with http://
, you should use:
soup.findAll('a', attrs={'href': re.compile("^http://")})
In Python 3 with BS4 it should be:
from bs4 import BeautifulSoup
import urllib.request
html_page = urllib.request.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page, "html.parser")
for link in soup.findAll('a'):
print(link.get('href'))
io.StringIO is another option for getting XML into xml.etree.ElementTree:
import io
f = io.StringIO(xmlstring)
tree = ET.parse(f)
root = tree.getroot()
Hovever, it does not affect the XML declaration one would assume to be in tree
(although that's needed for ElementTree.write()). See How to write XML declaration using xml.etree.ElementTree.
The simple way to create Current TimeStamp. like below,
func generateCurrentTimeStamp () -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
return (formatter.string(from: Date()) as NSString) as String
}
equals()
function is a method of Object
class which should be overridden by programmer. String
class overrides it to check if two strings are equal i.e. in content and not reference.
==
operator checks if the references of both the objects are the same.
Consider the programs
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
Here the abc
and xyz
, both refer to same String
"Awesome"
. Hence the expression (abc == xyz)
is true
.
String abc = "Hello World";
String xyz = "Hello World";
if(abc == xyz)
System.out.println("Refers to same string");
else
System.out.println("Refers to different strings");
if(abc.equals(xyz))
System.out.prinln("Contents of both strings are same");
else
System.out.prinln("Contents of strings are different");
Here abc
and xyz
are two different strings with the same content "Hello World"
. Hence here the expression (abc == xyz)
is false
where as (abc.equals(xyz))
is true
.
Hope you understood the difference between ==
and <Object>.equals()
Thanks.
java.time.temporal.ChronoUnit.DAYS.between(
earlier.toLocalDate(),
later.toLocalDate()
)
…or…
java.time.temporal.ChronoUnit.HOURS.between(
earlier.truncatedTo( ChronoUnit.HOURS ) ,
later.truncatedTo( ChronoUnit.HOURS )
)
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
The equivalent of Joda-Time DateTime
is ZonedDateTime
.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
Apparently you want to count the days by dates, meaning you want to ignore the time of day. For example, starting a minute before midnight and ending a minute after midnight should result in a single day. For this behavior, extract a LocalDate
from your ZonedDateTime
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate localDateStart = zdtStart.toLocalDate() ;
LocalDate localDateStop = zdtStop.toLocalDate() ;
Use the ChronoUnit
enum to calculate elapsed days or other units.
long days = ChronoUnit.DAYS.between( localDateStart , localDateStop ) ;
As for you asking about a more general way to do this counting where you are interested the delta of hours as hour-of-the-clock rather than complete hours as spans-of-time of sixty minutes, use the truncatedTo
method.
Here is your example of 14:45 to 15:12 on same day.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime start = ZonedDateTime.of( 2017 , 1 , 17 , 14 , 45 , 0 , 0 , z );
ZonedDateTime stop = ZonedDateTime.of( 2017 , 1 , 17 , 15 , 12 , 0 , 0 , z );
long hours = ChronoUnit.HOURS.between( start.truncatedTo( ChronoUnit.HOURS ) , stop.truncatedTo( ChronoUnit.HOURS ) );
1
This does not work for days. Use toLocalDate() in this case.
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.
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.
You probably want to use an ExpandableListView, a special ListView that allows you to open and close groups.
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
I got the same error for python 32 bit. After install 64bit, the problem was fixed.
I have 2 answers Methods 1: Insert Javascript into Batch
@if (@a==@b) @end /*
:: batch portion
@ECHO OFF
cscript /e:jscript "%~f0"
:: JScript portion */
Input Javascript here
( I don't know much about JavaScript )
Method 2: Loop in Batch
@echo off
set loopcount=5
:loop
echo Hello World!
set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop
pause
(Thanks FluorescentGreen5)
You can use the --system-site-packages
and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.
This is what worked for me:
public static Map<String, Object> toMap(JSONObject jsonobj) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keys = jsonobj.keys();
while(keys.hasNext()) {
String key = keys.next();
Object value = jsonobj.get(key);
if (value instanceof JSONArray) {
value = toList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
} return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if (value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
} return list;
}
Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java
There are a couple of ways of doing I first did the way Grendal2501 did it. I then did it similar to user15163, you can store the image URL in the firebase and host the image on your firebase host or also Amazon S3;
There is just a caveat that I discovered today.
If you have a function that is calling a plot a lot of times you better use plt.close(fig)
instead of fig.clf()
somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).
So the the following script will produce an empty list:
for i in range(5):
fig = plot_figure()
plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())
Whereas this one will produce a list with five figures on it.
for i in range(5):
fig = plot_figure()
fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())
From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.
If you want to try a complete script there you have:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
plt.close(fig)
print(plt.get_fignums())
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
fig.clf()
print(plt.get_fignums())
If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted
Just to extend Mark Byers's answer with an example:
import java.util.UUID;
public class RandomStringUUID {
public static void main(String[] args) {
UUID uuid = UUID.randomUUID();
System.out.println("UUID=" + uuid.toString() );
}
}
div {
// set a width
word-wrap: break-word
}
The 'word-wrap
' solution only works in IE and browsers supporting CSS3
.
The best cross browser solution is to use your server side language (php or whatever) to locate long strings and place inside them in regular intervals the html entity ​
This entity breaks the long words nicely, and works on all browsers.
e.g.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa​aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Static:
Obj.someMethod
Use static
when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.
A non-Javascript alternative that can be easily overlooked: can you use the readonly
attribute instead of the disabled
attribute? It prevents editing the text in the input, but browsers style the input differently (less likely to "grey it out")
e.g. <input readonly type="text" ...>
I think the "messy" second method, which is linked from another question here may be the only pure CSS solution.
If you're thinking about using JavaScript, then this was my solution to the problem:
demo: using a
canvas
element to fade text against an animated backgroundThe idea is that your element with the text and the
canvas
element are one on top of the other. You keep the text in your element (in order to allow text selection, which isn't possible withcanvas
text), but make it completely transparent (withrgba(0,0,0,0)
, in order to have the text visible in IE8 and older - that's because you have noRGBa
support and nocanvas
support in IE8 and older).You then read the text inside your element and write it on the canvas with the same font properties so that each letter you write on the canvas is over the corresponding letter in the element with the text.
The
canvas
element does not support multi-line text, so you'll have to break the text into words and then keep adding words on a test line which you then measure. If the width taken by the test line is bigger than the maximum allowed width you can have for a line (you get that maximum allowed width by reading the computed width of the element with the text), then you write it on the canvas without the last word added, you reset the test line to be that last word, and you increase the y coordinate at which to write the next line by one line height (which you also get from the computed styles of your element with the text). With each line that you write, you also decrease the opacity of the text with an appropriate step (this step being inversely proportional to the average number of characters per line).What you cannot do easily in this case is to justify text. It can be done, but it gets a bit more complicated, meaning that you would have to compute how wide should each step be and write the text word by word rather than line by line.
Also, keep in mind that if your text container changes width as you resize the window, then you'll have to clear the canvas and redraw the text on it on each resize.
OK, the code:
HTML:
<article> <h1>Interacting Spiral Galaxies NGC 2207/ IC 2163</h1> <em class='timestamp'>February 4, 2004 09:00 AM</em> <section class='article-content' id='art-cntnt'> <canvas id='c' class='c'></canvas>In the direction of <!--and so on--> </section> </article>
CSS:
html { background: url(moving.jpg) 0 0; background-size: 200%; font: 100%/1.3 Verdana, sans-serif; animation: ani 4s infinite linear; } article { width: 50em; /* tweak this ;) */ padding: .5em; margin: 0 auto; } .article-content { position: relative; color: rgba(0,0,0,0); /* add slash at the end to check they superimpose * color: rgba(255,0,0,.5);/**/ } .c { position: absolute; z-index: -1; top: 0; left: 0; } @keyframes ani { to { background-position: 100% 0; } }
JavaScript:
var wrapText = function(ctxt, s, x, y, maxWidth, lineHeight) { var words = s.split(' '), line = '', testLine, metrics, testWidth, alpha = 1, step = .8*maxWidth/ctxt.measureText(s).width; for(var n = 0; n < words.length; n++) { testLine = line + words[n] + ' '; metrics = ctxt.measureText(testLine); testWidth = metrics.width; if(testWidth > maxWidth) { ctxt.fillStyle = 'rgba(0,0,0,'+alpha+')'; alpha -= step; ctxt.fillText(line, x, y); line = words[n] + ' '; y += lineHeight; } else line = testLine; } ctxt.fillStyle = 'rgba(0,0,0,'+alpha+')'; alpha -= step; ctxt.fillText(line, x, y); return y + lineHeight; } window.onload = function() { var c = document.getElementById('c'), ac = document.getElementById('art-cntnt'), /* use currentStyle for IE9 */ styles = window.getComputedStyle(ac), ctxt = c.getContext('2d'), w = parseInt(styles.width.split('px')[0], 10), h = parseInt(styles.height.split('px')[0], 10), maxWidth = w, lineHeight = parseInt(styles.lineHeight.split('px')[0], 10), x = 0, y = parseInt(styles.fontSize.split('px')[0], 10), text = ac.innerHTML.split('</canvas>')[1]; c.width = w; c.height = h; ctxt.font = '1em Verdana, sans-serif'; wrapText(ctxt, text, x, y, maxWidth, lineHeight); };
If you are using jQuery, you could scroll with an animation using the following:
$(MyContainerDiv).animate({scrollTop: $(MyContainerDiv).scrollTop() + ($('element_within_div').offset().top - $(MyContainerDiv).offset().top)});
The animation is optional: you could also take the scrollTop value calculated above and put it directly in the container's scrollTop property.
Maybe this old topic but i found this library is very helpful and easy to use
example for using it in android
Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
Well, found a solution to my problem; Updating all rows using a SQL query and a SQL Task in SSIS Like Below. May help others if they face same challenge in future.
update Original
set Original.Vaal= t.vaal
from Original join (select * from staging1 union select * from staging2) t
on Original.id=t.id
Security Warning:
md5(uniqid(rand(), TRUE))
is not a secure way to generate random numbers. See this answer for more information and a solution that leverages a cryptographically secure random number generator.
Looks like you need an else with your if.
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();
}
else
{
$token = $_SESSION['token'];
}
It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.
You can use following code to insert an image through script.
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Above example has been copied from this link. Check noogui's reply for details.
In case you need to insert image from Google Drive, please check this link for current updates.
The best option, in my opinion, is to use the Value
property for the ListItem
, which is available in the RadioButtonList
.
I must remark that ListItem
does NOT have an ID property.
So, in your case, to select the second element (option2) that would be:
// SelectedValue expects a string
radio1.SelectedValue = "1";
Alternatively, yet in very much the same vein you may supply an int to SelectedIndex.
// SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0.
radio1.SelectedIndex = 1;
See adeneo's answer, but don't forget encodeURIComponent
!
a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvString);
Also, I needed to do "\r\n" not just "\n" for the row delimiter.
var csvString = csvRows.join("\r\n");
Revised fiddle: http://jsfiddle.net/7Q3c6/
Using annotations, as described in the question.
Annotation: @Monitor
Annotation on class, app/PagesController.java
:
package app;
@Controller
@Monitor
public class PagesController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody String home() {
return "w00t!";
}
}
Annotation on method, app/PagesController.java
:
package app;
@Controller
public class PagesController {
@Monitor
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody String home() {
return "w00t!";
}
}
Custom annotation, app/Monitor.java
:
package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}
Aspect for annotation, app/MonitorAspect.java
:
package app;
@Component
@Aspect
public class MonitorAspect {
@Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
public void before(JoinPoint joinPoint) throws Throwable {
LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
}
@After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
public void after(JoinPoint joinPoint) throws Throwable {
LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
}
}
Enable AspectJ, servlet-context.xml
:
<aop:aspectj-autoproxy />
Include AspectJ libraries, pom.xml
:
<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>
You can refer to this answer - https://stackoverflow.com/a/24105062/3629912
It worked for me everytime.
adb shell dumpsys window InputMethod | grep "mHasSurface"
It will return true, if software keyboard is visible.
For the accepted answer when you try to hide any view inside stack view, the constraint works not correct.
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x618000086e50 UIView:0x7fc11c4051c0.height == 120 (active)>",
"<NSLayoutConstraint:0x610000084fb0 'UISV-hiding' UIView:0x7fc11c4051c0.height == 0 (active)>"
)
Reason is when hide the view
in stackView
it will set the height to 0 to animate it.
Solution change the constraint priority
as below.
import UIKit
class ViewController: UIViewController {
let stackView = UIStackView()
let a = UIView()
let b = UIView()
override func viewDidLoad() {
super.viewDidLoad()
a.backgroundColor = UIColor.red
a.widthAnchor.constraint(equalToConstant: 200).isActive = true
let aHeight = a.heightAnchor.constraint(equalToConstant: 120)
aHeight.isActive = true
aHeight.priority = 999
let bHeight = b.heightAnchor.constraint(equalToConstant: 120)
bHeight.isActive = true
bHeight.priority = 999
b.backgroundColor = UIColor.green
b.widthAnchor.constraint(equalToConstant: 200).isActive = true
view.addSubview(stackView)
stackView.backgroundColor = UIColor.blue
stackView.addArrangedSubview(a)
stackView.addArrangedSubview(b)
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Just add a button in xib file or storyboard and add connect this action.
@IBAction func test(_ sender: Any) {
a.isHidden = !a.isHidden
}
}
Sometimes size
"picks the wrong one" and returns a hash (which is what count
would do)
In that case, use length
to get an integer instead of hash.
Simple:
if(pll_current_language() == 'en'){
//do your work here
}
If You have jar file then create bat file with:
java -jar NameOfJar.jar
The pdfrw
library can do this quite easily, assuming you don't need to preserve bookmarks and annotations, and your PDFs aren't encrypted. cat.py
is an example concatenation script, and subset.py
is an example page subsetting script.
The relevant part of the concatenation script -- assumes inputs
is a list of input filenames, and outfn
is an output file name:
from pdfrw import PdfReader, PdfWriter
writer = PdfWriter()
for inpfn in inputs:
writer.addpages(PdfReader(inpfn).pages)
writer.write(outfn)
As you can see from this, it would be pretty easy to leave out the last page, e.g. something like:
writer.addpages(PdfReader(inpfn).pages[:-1])
Disclaimer: I am the primary pdfrw
author.
I solved this in Windows 10 by using cmd instead of GitBash.
It has to do with character case and how git and command lines handles them.
You should be using IHtmlString
instead:
IHtmlString str = new HtmlString("<a href="/Home/Profile/seeker">seeker</a> has applied to <a href="/Jobs/Details/9">Job</a> floated by you.</br>");
Whenever you have model properties or variables that need to hold HTML, I feel this is generally a better practice. First of all, it is a bit cleaner. For example:
@Html.Raw(str)
Compared to:
@str
Also, I also think it's a bit safer vs. using @Html.Raw()
, as the concern of whether your data is HTML is kept in your controller. In an environment where you have front-end vs. back-end developers, your back-end developers may be more in tune with what data can hold HTML values, thus keeping this concern in the back-end (controller).
I generally try to avoid using Html.Raw()
whenever possible.
One other thing worth noting, is I'm not sure where you're assigning str
, but a few things that concern me with how you may be implementing this.
First, this should be done in a controller, regardless of your solution (IHtmlString
or Html.Raw
). You should avoid any logic like this in your view, as it doesn't really belong there.
Additionally, you should be using your ViewModel
for getting values to your view (and again, ideally using IHtmlString
as the property type). Seeing something like @Html.Encode(str)
is a little concerning, unless you were doing this just to simplify your example.
add display:block;
and it'll work. Images are inline by default
To clarify, the default width for a block
element is auto
, which of course fills the entire available width of the containing element.
By setting the margin to auto
, the browser assigns half the remaining space to margin-left
and the other half to margin-right
.
If you are using the package device_id to get the unique device id then that will add an android.permission.READ_PHONE_STATE
without your knowledge which eventually will lead to the Play Store warning.
Instead you can use the device_info package for the same purpose without the need of the extra permission. Check this SO thread
throw new RuntimeException(msg);
You need the new
in there. It's creating an instance and throwing it, not calling a method.
if the database is InnoDB you dont need to do joins in deletion. only
DELETE FROM spawnlist WHERE spawnlist.type = "monster";
can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.
CREATE TABLE IF NOT EXIST spawnlist (
npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXIST npc (
idTemplate VARCHAR(20) NOT NULL,
FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE
)ENGINE=InnoDB;
if you uses MyISAM you can delete records joining like this
DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';
in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.
When you have unmanaged resources and you need to make sure they will be cleaned up when your object goes away. Good example would be COM objects or File Handlers.
npm install --unsafe-perm
worked for me. See https://docs.npmjs.com/. The --unsafe-perm
parameter lets you run the scripts from the package instalation as root. The problem in my case was that some depandencies failed to install.
I believe it would be like this
takedata.match(/(\[.+\])/g);
the g
at the end means global, so it doesn't stop at the first match.
It's the ASCII keycode in hexadecimal for a comma (,
).
You should use your language's URL encoding methods when placing strings in URLs.
You can see a handy list of characters with man ascii
. It has this compact diagram available for mapping hexadecimal codes to the character:
2 3 4 5 6 7
-------------
0: 0 @ P ` p
1: ! 1 A Q a q
2: " 2 B R b r
3: # 3 C S c s
4: $ 4 D T d t
5: % 5 E U e u
6: & 6 F V f v
7: ' 7 G W g w
8: ( 8 H X h x
9: ) 9 I Y i y
A: * : J Z j z
B: + ; K [ k {
C: , < L \ l |
D: - = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL
You can also quickly check a character's hexadecimal equivalent with:
$ echo -n , | xxd -p
2c
If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared item.
<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>
-Oisin
My definitive solution on Eclipse Luna and m2eclipse: Custom Classloader (download and add to your project, 5 classes only) :http://git.eclipse.org/c/jdt/eclipse.jdt.ui.git/plain/org.eclipse.jdt.ui/jar%20in%20jar%20loader/org/eclipse/jdt/internal/jarinjarloader/; this classloader is very best of one-jar classloader and very fast;
<project.mainClass>org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader</project.mainClass>
<project.realMainClass>my.Class</project.realMainClass>
Edit in JIJConstants "Rsrc-Class-Path" to "Class-Path"
mvn clean dependency:copy-dependencies package
is created a jar with dependencies in lib folder with a thin classloader
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*</include>
</includes>
<targetPath>META-INF/</targetPath>
</resource>
<resource>
<directory>${project.build.directory}/dependency/</directory>
<includes>
<include>*.jar</include>
</includes>
<targetPath>lib/</targetPath>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>${project.mainClass}</mainClass>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
<manifestEntries>
<Rsrc-Main-Class>${project.realMainClass} </Rsrc-Main-Class>
<Class-Path>./</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
You JSON is not a valid string as P. Galbraith has told you above.
and here is the solution for it.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Use this code it will work for you.
substr: It's providing us to fetch part of the string based on specified index. syntax of substr- string.substr(start,end) start - start index tells where the fetching start. end - end index tells upto where string fetches. It's optional.
slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index. syntax of slice - string.slice(start,end) start - start index tells where the fetching start.It's end - end index tells upto where string fetches. It's optional. In 'splice' both start and end index helps to take positive and negative index.
sample code for 'slice' in string
var str="Javascript";
console.log(str.slice(-5,-1));
output: crip
sample code for 'substring' in string
var str="Javascript";
console.log(str.substring(1,5));
output: avas
[*Note: negative indexing starts at the end of the string.]
If you want to select only one of two nodes with union operator, you can use this solution:
(//bookstore/book/title | //bookstore/city/zipcode/title)[1]
try c_x freeze it can create a good standalone
Returns last day of last month:
>>> import datetime
>>> datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().day)
datetime.datetime(2020, 9, 30, 14, 13, 15, 67582)
Returns the same day last month:
>>> x = datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().day)
>>> x.replace(day=datetime.datetime.now().day)
datetime.datetime(2020, 9, 7, 14, 22, 14, 362421)
The hint (using axfr) only works if the NS you're querying (ns1.foo.bar in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question.
Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. dig a.some_domain.com
, dig b.some_domain.com
, ...), which I can't recommend, as it could be viewed as a denial of service attack.
Use rel="preload"
to make it download independently, then use onload="this.rel='stylesheet'"
to apply it to the stylesheet (as="style"
is necessary to apply it to stylesheet else the onload
won't work)
<link rel="preload" as="style" type="text/css" href="mystyles.css" onload="this.rel='stylesheet'">
It is mentioned in the .data()
documentation
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)
This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?
The demo on my original answer below doesn't seem to work any more.
Updated answer
Again, from the .data()
documentation
The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.
So for <div data-role="page"></div>
the following is true $('div').data('role') === 'page'
I'm fairly sure that $('div').data('data-role')
worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.
Also see jQuery Data vs Attr?
HTML
<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
<tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>
JavaScript (jQuery 1.6.2+)
var $changeMe = $('#changeMe');
var $log = $('#log');
var logger;
(logger = function(setter, getter, note) {
note = note || '';
eval('$changeMe' + setter);
var result = eval('$changeMe' + getter);
$log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");
$('#changeData').click(function() {
// set data-key to new value
logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
// try and set data-key via .attr and get via some methods
logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");
// bonus points
logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");
return false;
});
$('#changeData').click();
Original answer
For this HTML:
<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>
and this JavaScript (with jQuery 1.6.2)
console.log($('#foo').data('helptext'));
$('#changeData').click(function() {
$('#foo').data('helptext', 'Testing 123');
// $('#foo').attr('data-helptext', 'Testing 123');
console.log($('#foo').data('data-helptext'));
return false;
});
Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123');
does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123');
does.
@liquide's answer works great.
System.IO.File.Copy(inputFilePath, printerPath);
Which I found from the Zebra's ZPL Programmer's Guide Volume 1 (2005)
hittest.js; detect two transparent PNG images (pixel) colliding.
<img id="png-object-1" src="images/object1.png" />
<img id="png-object-2" src="images/object2.png" />
var pngObject1Element = document.getElementById( "png-object-1" );
var pngObject2Element = document.getElementById( "png-object-2" );
var object1HitTest = new HitTest( pngObject1Element );
if( object1HitTest.toObject( pngObject2Element ) ) {
// Collision detected
}
This is usually what I use for counting the number of fields:
head -n 1 file.name | awk -F'|' '{print NF; exit}'
You will probably load the os module anyway, so another suggestion would be:
import os
myhost = os.uname()[1]
set OPENSSL_CONF=c:/{path to openSSL}/bin/openssl.cfg
take care of the right extension (openssl.cfg not cnf)!
I have installed OpenSSL from here: http://slproweb.com/products/Win32OpenSSL.html
I am new to retrofit and I am enjoying it. So here is a simple way to understand it for those that might want to query with more than one query: The ? and & are automatically added for you.
Interface:
public interface IService {
String BASE_URL = "https://api.test.com/";
String API_KEY = "SFSDF24242353434";
@GET("Search") //i.e https://api.test.com/Search?
Call<Products> getProducts(@Query("one") String one, @Query("two") String two,
@Query("key") String key)
}
It will be called this way. Considering you did the rest of the code already.
Call<Results> call = service.productList("Whatever", "here", IService.API_KEY);
For example, when a query is returned, it will look like this.
//-> https://api.test.com/Search?one=Whatever&two=here&key=SFSDF24242353434
Link to full project: Please star etc: https://github.com/Cosmos-it/ILoveZappos
If you found this useful, don't forget to star it please. :)
my table name is buyers which has a unique constraint column emp_id now iam going to drop the emp_id
step 1: exec sp_helpindex buyers, see the image file
step 2: copy the index address
step3: alter table buyers drop constraint [UQ__buyers__1299A860D9793F2E] alter table buyers drop column emp_id
note:
Blockquote
instead of buyers change it to your table name :)
Blockquote
thats all column name emp_id with constraints is dropped!
Dir
takes wild cards so you could make a big difference adding the filter for test
up front and avoiding testing each file
Sub LoopThroughFiles()
Dim StrFile As String
StrFile = Dir("c:\testfolder\*test*")
Do While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
Loop
End Sub
Use the keys CtrlK,C to comment out the line and CtrlK,U to uncomment the line.
If you just want the date:
SELECT MIN(date) as EarliestDate
FROM YourTable
WHERE id = 2
If you want all of the information:
SELECT TOP 1 id, name, score, date
FROM YourTable
WHERE id = 2
ORDER BY Date
Prevent loops when you can. Loops often lead to cursors, and cursors are almost never necessary and very often really inefficient.
In perl 5.10, there's the close-to-magic ~~ operator:
sub invite_in {
my $vampires = [ qw(Angel Darla Spike Drusilla) ];
return ($_[0] ~~ $vampires) ? 0 : 1 ;
}
See here: http://dev.perl.org/perl5/news/2007/perl-5.10.0.html
Do you mean you want Class C to be the base class for A & B in that case.
public abstract class C
{
public abstract void Method1();
public abstract void Method2();
}
public class A : C
{
public override void Method1()
{
throw new NotImplementedException();
}
public override void Method2()
{
throw new NotImplementedException();
}
}
public class B : C
{
public override void Method1()
{
throw new NotImplementedException();
}
public override void Method2()
{
throw new NotImplementedException();
}
}
Try this
in view:
<form name="formName" ng-submit="submitForm(formName)">
<!-- fields -->
</form>
in controller:
$scope.submitForm = function(form){
if(form.$valid) {
// Code here if valid
}
};
or
in view:
<form name="formName" ng-submit="submitForm(formName.$valid)">
<!-- fields -->
</form>
in controller:
$scope.submitForm = function(formValid){
if(formValid) {
// Code here if valid
}
};
if you are opening page on JavaScript popup then
Response.Write("<script>javascript:window.close();</script>");
will do the job
From Managing Projects with GNU Make, 3rd Edition, p. 16 (it's under GNU Free Documentation License):
Automatic variables are set by
make
after a rule is matched. They provide access to elements from the target and prerequisite lists so you don’t have to explicitly specify any filenames. They are very useful for avoiding code duplication, but are critical when defining more general pattern rules.There are seven “core” automatic variables:
$@
: The filename representing the target.
$%
: The filename element of an archive member specification.
$<
: The filename of the first prerequisite.
$?
: The names of all prerequisites that are newer than the target, separated by spaces.
$^
: The filenames of all the prerequisites, separated by spaces. This list has duplicate filenames removed since for most uses, such as compiling, copying, etc., duplicates are not wanted.
$+
: Similar to$^
, this is the names of all the prerequisites separated by spaces, except that$+
includes duplicates. This variable was created for specific situations such as arguments to linkers where duplicate values have meaning.
$*
: The stem of the target filename. A stem is typically a filename without its suffix. Its use outside of pattern rules is discouraged.In addition, each of the above variables has two variants for compatibility with other makes. One variant returns only the directory portion of the value. This is indicated by appending a “D” to the symbol,
$(@D)
,$(<D)
, etc. The other variant returns only the file portion of the value. This is indicated by appending an “F” to the symbol,$(@F)
,$(<F)
, etc. Note that these variant names are more than one character long and so must be enclosed in parentheses. GNU make provides a more readable alternative with the dir and notdir functions.
I wrote up a HOWTO for VST development on C++ with Visual Studio awhile back which details the steps necessary to create a basic plugin for the Windows platform (the Mac version of this article is forthcoming). On Windows, a VST plugin is just a normal DLL, but there are a number of "gotchas", and you need to build the plugin using some specific compiler/linker switches or else it won't be recognized by some hosts.
As for the Mac, a VST plugin is just a bundle with the .vst extension, though there are also a few settings which must be configured correctly in order to generate a valid plugin. You can also download a set of Xcode VST plugin project templates I made awhile back which can help you to write a working plugin on that platform.
As for AudioUnits, Apple has provided their own project templates which are included with Xcode. Apple also has very good tutorials and documentation online:
I would also highly recommend checking out the Juce Framework, which has excellent support for creating cross-platform VST/AU plugins. If you're going open-source, then Juce is a no-brainer, but you will need to pay licensing fees for it if you plan on releasing your work without source code.
Working Solution
Step 1: Create Cors middleware
php artisan make:middleware Cors
Step 2: Set header in Cors middleware inside handle function
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
Step 3: Add Cors class in app/Http/Kernel.php
protected $routeMiddleware = [
....
'cors' => \App\Http\Middleware\Cors::class,
];
Step 4: Replace mapApiRoutes in app/providers/routeServiceProvider.php
Route::prefix('api')
->middleware(['api', 'cors'])
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Step 5: Add your routes in routes/api.php
Route::post('example', 'controllerName@functionName')->name('example');
You can do it like this,
<input type="text" name="name" value="<?php echo $name;?>" />
But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.
<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />
To answer the second part of your question, to convert to binary you can use a format string and the ord
function:
>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'
Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.
I think there is an easier way
import pandas as pd
dataset = pd.read_csv('table1.csv')
ftCol = dataset.iloc[:, 0].values
So in here iloc[:, 0]
, :
means all values, 0
means the position of the column.
in the example below ID
will be selected
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
for my case i have two localized file , ja and en
and i would like to force it to en if the preferred language in the system neither en or ja
i'm going to edit the main.m file
i 'll check whether the first preferred is en or ja , if not then i 'll change the second preferred language to en.
int main(int argc, char *argv[])
{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *lang = [[NSLocale preferredLanguages] objectAtIndex:0];
if (![lang isEqualToString:@"en"] && ![lang isEqualToString:@"ja"]){
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[NSLocale preferredLanguages]];
[array replaceObjectAtIndex:1 withObject:@"en"];
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
i already have your problem and i solved it by the following code .. that accept only numbers
$('#<%= mobileTextBox.ClientID %>').keydown(function(e) {
///// e.which Values
// 8 : BackSpace , 46 : Delete , 37 : Left , 39 : Rigth , 144: Num Lock
if (e.which != 8 && e.which != 46 && e.which != 37 && e.which != 39 && e.which != 144
&& (e.which < 96 || e.which > 105 )) {
return false;
}
});
you can detect Ctrl id e.which == 17
If you have control over the proxy server or can convince your IT admins you could try to explicitly exclude registry.npmjs.org from SSL inspection. This should avoid users of the proxy server from having to either disable strict-ssl checking or installing a new root CA.
Fur future readers, if you are using Angular 1.6, you also need to change the hashPrefix
:
appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('');
}]);
Don't forget to set the base in your HTML <head>
:
<head>
<base href="/">
...
</head>
More info about the changelog here.
You can't do this using forms the normal way. Instead, you want to use AJAX.
A sample function that will submit the data and alert the page response.
function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "<<whereverTheFormIsGoing>>", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
So this is a stupid error message because it doesn't tell you what file it can't find.
Run the command again with the verbose flag gcc -v
to see what gcc is up to.
In my case, it happened it was trying to call cc1plus
. I checked, I don't have that. Installed mingw's C++ compiler and then I did.
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
An Essay way :
public class CharToInt{
public static void main(String[] poo){
String ss="toyota";
for(int i=0;i<ss.length();i++)
{
char c = ss.charAt(i);
// int a=c;
System.out.println(c); } }
}
For Output see this link: Click here
Thanks :-)
The below code working for me on array coming from ajax call .
$form = $request->input('form');
$rules = array(
'facebook_account' => 'url',
'youtube_account' => 'url',
'twitter_account' => 'url',
'instagram_account' => 'url',
'snapchat_account' => 'url',
'website' => 'url',
);
$validation = Validator::make($form, $rules);
if ($validation->fails()) {
return Response::make(['error' => $validation->errors()], 400);
}
You're comparing the message with the empty string using ==
.
First, your comparison is wrong because the message will be null (and not the empty string).
Second, it's wrong because Objects must be compared with equals()
and not with ==
.
Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:
<c:id test="${!empty message}">
<c:out value="${message}"/>
</c:if>
These two settings worked for me to upload 1GB mp4 videos.
<system.web>
<httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
A good option is to avoid conversion from int
to enum
: for example, if you need the maximal value, you may compare x.ordinal() to y.ordinal() and return x or y correspondingly. (You may need to re-order you values to make such comparison meaningful.)
If that is not possible, I would store MyEnum.values()
into a static array.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
The second. The first is invalid.
A browser will handle it like so:
<p>tetxtextextete
<!-- Start of paragraph -->
<ol>
<!-- Start of ordered list. Paragraphs cannot contain lists. Insert </p> -->
<li>first element</li></ol>
<!-- A list item element. End of list -->
</p>
<!-- End of paragraph, but not inside paragraph, discard this tag to recover from the error -->
<p>other textetxet</p>
<!-- Another paragraph -->
This method may avoid the need to hard code or configure proxy credentials, which may be desirable.
Put this in your application configuration file - probably app.config. Visual Studio will rename it to yourappname.exe.config on build, and it will end up next to your executable. If you don't have an application configuration file, just add one using Add New Item in Visual Studio.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
</configuration>
One more for the road that's a bit more flexible for matching specific filenames because it uses wildcard globbing. In a functional style this could resemble:
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import static java.nio.file.FileSystems.getDefault;
import static java.nio.file.FileSystems.newFileSystem;
import static java.util.Collections.emptyMap;
/**
* Responsible for finding file resources.
*/
public class ResourceWalker {
/**
* Globbing pattern to match font names.
*/
public static final String GLOB_FONTS = "**.{ttf,otf}";
/**
* @param directory The root directory to scan for files matching the glob.
* @param c The consumer function to call for each matching path
* found.
* @throws URISyntaxException Could not convert the resource to a URI.
* @throws IOException Could not walk the tree.
*/
public static void walk(
final String directory, final String glob, final Consumer<Path> c )
throws URISyntaxException, IOException {
final var resource = ResourceWalker.class.getResource( directory );
final var matcher = getDefault().getPathMatcher( "glob:" + glob );
if( resource != null ) {
final var uri = resource.toURI();
final Path path;
FileSystem fs = null;
if( "jar".equals( uri.getScheme() ) ) {
fs = newFileSystem( uri, emptyMap() );
path = fs.getPath( directory );
}
else {
path = Paths.get( uri );
}
try( final var walk = Files.walk( path, 10 ) ) {
for( final var it = walk.iterator(); it.hasNext(); ) {
final Path p = it.next();
if( matcher.matches( p ) ) {
c.accept( p );
}
}
} finally {
if( fs != null ) { fs.close(); }
}
}
}
}
Consider parameterizing the file extensions, left an exercise for the reader.
Be careful with Files.walk
. According to the documentation:
This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.
Likewise, newFileSystem
must be closed, but not before the walker has had a chance to visit the file system paths.
If the file is placed under target/classes after compiling, then it is already in a directory that is part of the build path. The directory src/main/resources is the Maven default directory for such resources, and it is automatically placed to the build path by the Eclipse Maven plugin (M2E). So, there is no need to move your properties file.
The other topic is, how to retrieve such resources. Resources in the build path are automatically in the class path of the running Java program. Considering this, you should always load such resources with a class loader. Example code:
String resourceName = "myconf.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
props.load(resourceStream);
}
// use props here ...
.py
: This is normally the input source code that you've written..pyc
: This is the compiled bytecode. If you import a module, python will build a *.pyc
file that contains the bytecode to make importing it again later easier (and faster)..pyo
: This was a file format used before Python 3.5 for *.pyc
files that were created with optimizations (-O
) flag. (see the note below).pyd
: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dllAlso for some further discussion on .pyc
vs .pyo
, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)
- When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
- Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only
__doc__
strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.- A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
- When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.
Note:
On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo
files.
This means that .pyc
files represent both unoptimized and optimized bytecode.
You can also use this script , just change the height and width
<canvas id="Canvas01" width="500" height="400" style="border:2px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas>
<script>
var canvas = document.getElementById("Canvas01");
var ctx = canvas.getContext("2d");
Wow, I can't believe how many answers there are for this question. I can't say I've tried them all but I've tried the top 3 or 4 and none of them work for me. What did work for me was an answer located in one of the comment written by a user called doug. Since I found it so helpful, I decided to restate in an answer.
Install xcopy utility and when you're in the Terminal, input:
Copy
Thing_you_want_to_copy|xclip -selection c
Paste
myvariable=$(xclip -selection clipboard -o)
I noticed alot of answers recommended pbpaste and pbcopy. If you're into those utilities but for some reason they are not available on your repo, you can always make an alias for the xcopy commands and call them pbpaste and pbcopy.
alias pbcopy="xclip -selection c"
alias pbpaste="xclip -selection clipboard -o"
So then it would look like this:
Thing_you_want_to_copy|pbcopy
myvariable=$(pbpaste)
State machines are very simple in C if you use function pointers.
Basically you need 2 arrays - one for state function pointers and one for state transition rules. Every state function returns the code, you lookup state transition table by state and return code to find the next state and then just execute it.
int entry_state(void);
int foo_state(void);
int bar_state(void);
int exit_state(void);
/* array and enum below must be in sync! */
int (* state[])(void) = { entry_state, foo_state, bar_state, exit_state};
enum state_codes { entry, foo, bar, end};
enum ret_codes { ok, fail, repeat};
struct transition {
enum state_codes src_state;
enum ret_codes ret_code;
enum state_codes dst_state;
};
/* transitions from end state aren't needed */
struct transition state_transitions[] = {
{entry, ok, foo},
{entry, fail, end},
{foo, ok, bar},
{foo, fail, end},
{foo, repeat, foo},
{bar, ok, end},
{bar, fail, end},
{bar, repeat, foo}};
#define EXIT_STATE end
#define ENTRY_STATE entry
int main(int argc, char *argv[]) {
enum state_codes cur_state = ENTRY_STATE;
enum ret_codes rc;
int (* state_fun)(void);
for (;;) {
state_fun = state[cur_state];
rc = state_fun();
if (EXIT_STATE == cur_state)
break;
cur_state = lookup_transitions(cur_state, rc);
}
return EXIT_SUCCESS;
}
I don't put lookup_transitions()
function as it is trivial.
That's the way I do state machines for years.
SELECT num, UserName FROM
(SELECT UserName, ROW_NUMBER() OVER(ORDER BY UserId) AS num
From Users) AS numbered
WHERE UserName='Joe'
One more option that I saw is missing here:
const string APP_CONFIG_FILE = "APP_CONFIG_FILE";
string defaultSysConfigFilePath = (string)AppDomain.CurrentDomain.GetData(APP_CONFIG_FILE);
The only one that worked for me was a mix of all the answers:
convert in.png -background white -alpha remove -flatten -alpha off out.png
This one worked
Setting up Go development environment on Ubuntu, and how to fix $GOPATH / $GOROOT
Steps
mkdir ~/go
Set $GOPATH in .bashrc,
export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin
I was trying use the audio players flutter package. Once I added it to pubspec.yaml and tried to import it to main.dart, I got the same error.
I tried to restart my IDE but that didn't help so i tried running
flutter packages pub cache repair
and it worked.
A few great suggestions are already mentioned. Using GSON is really handy indeed, and to make life even easier you can try this website It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project. You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
puts 'abcdefg'.start_with?('abc') #=> true
[edit] This is something I didn't know before this question: start_with
takes multiple arguments.
'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
Here is my proposition in C++
I tried to impose as little restriction on the iterator type as i could so this solution assumes just forward iterator, and it can be a const_iterator. This should work with any standard container. In cases where arguments don't make sense it throws std::invalid_argumnent
#include <vector>
#include <stdexcept>
template <typename Fci> // Fci - forward const iterator
std::vector<std::vector<Fci> >
enumerate_combinations(Fci begin, Fci end, unsigned int combination_size)
{
if(begin == end && combination_size > 0u)
throw std::invalid_argument("empty set and positive combination size!");
std::vector<std::vector<Fci> > result; // empty set of combinations
if(combination_size == 0u) return result; // there is exactly one combination of
// size 0 - emty set
std::vector<Fci> current_combination;
current_combination.reserve(combination_size + 1u); // I reserve one aditional slot
// in my vector to store
// the end sentinel there.
// The code is cleaner thanks to that
for(unsigned int i = 0u; i < combination_size && begin != end; ++i, ++begin)
{
current_combination.push_back(begin); // Construction of the first combination
}
// Since I assume the itarators support only incrementing, I have to iterate over
// the set to get its size, which is expensive. Here I had to itrate anyway to
// produce the first cobination, so I use the loop to also check the size.
if(current_combination.size() < combination_size)
throw std::invalid_argument("combination size > set size!");
result.push_back(current_combination); // Store the first combination in the results set
current_combination.push_back(end); // Here I add mentioned earlier sentinel to
// simplyfy rest of the code. If I did it
// earlier, previous statement would get ugly.
while(true)
{
unsigned int i = combination_size;
Fci tmp; // Thanks to the sentinel I can find first
do // iterator to change, simply by scaning
{ // from right to left and looking for the
tmp = current_combination[--i]; // first "bubble". The fact, that it's
++tmp; // a forward iterator makes it ugly but I
} // can't help it.
while(i > 0u && tmp == current_combination[i + 1u]);
// Here is probably my most obfuscated expression.
// Loop above looks for a "bubble". If there is no "bubble", that means, that
// current_combination is the last combination, Expression in the if statement
// below evaluates to true and the function exits returning result.
// If the "bubble" is found however, the ststement below has a sideeffect of
// incrementing the first iterator to the left of the "bubble".
if(++current_combination[i] == current_combination[i + 1u])
return result;
// Rest of the code sets posiotons of the rest of the iterstors
// (if there are any), that are to the right of the incremented one,
// to form next combination
while(++i < combination_size)
{
current_combination[i] = current_combination[i - 1u];
++current_combination[i];
}
// Below is the ugly side of using the sentinel. Well it had to haave some
// disadvantage. Try without it.
result.push_back(std::vector<Fci>(current_combination.begin(),
current_combination.end() - 1));
}
}
please close the android studio and remove the file
.gradle
and
.idea
file form your project .Hope so it is helpful
Location:Go to Android studio projects->your project ->see both file remove (.gradle
& .idea
)
A merge conflict occurs when two branches you're trying to merge both changed the same part of the same file. You can generate a list of conflicts with git status
.
When the conflicted line is encountered, Git will edit the content of the affected files with visual indicators that mark both sides of the conflicting content.
<<<<<<< HEAD
conflicted text from HEAD
=======
conflicted text from merging_branch
>>>>>>> merging_branch
When you fix your conflicted files and you are ready to merge, all you have to do is run git add
and git commit
to generate the merge commit. Once the commit was made ,git push
the changes to the branch.
Reference article: Git merge.
I made quite easy, Django style JSP Template inheritance tag library. https://github.com/kwon37xi/jsp-template-inheritance
I think it make easy to manage layouts without learning curve.
example code :
base.jsp : layout
<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://kwonnam.pe.kr/jsp/template-inheritance" prefix="layout"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>JSP Template Inheritance</title>
</head>
<h1>Head</h1>
<div>
<layout:block name="header">
header
</layout:block>
</div>
<h1>Contents</h1>
<div>
<p>
<layout:block name="contents">
<h2>Contents will be placed under this h2</h2>
</layout:block>
</p>
</div>
<div class="footer">
<hr />
<a href="https://github.com/kwon37xi/jsp-template-inheritance">jsp template inheritance example</a>
</div>
</html>
view.jsp : contents
<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://kwonnam.pe.kr/jsp/template-inheritance" prefix="layout"%>
<layout:extends name="base.jsp">
<layout:put name="header" type="REPLACE">
<h2>This is an example about layout management with JSP Template Inheritance</h2>
</layout:put>
<layout:put name="contents">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin porta,
augue ut ornare sagittis, diam libero facilisis augue, quis accumsan enim velit a mauris.
</layout:put>
</layout:extends>
It's according to spec.
12.5 The if Statement ..... 2. If ToBoolean(GetValue(exprRef)) is true, then a. Return the result of evaluating the first Statement. 3. Else, ....
ToBoolean, according to the spec, is
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
And that table says this about strings:
The result is false if the argument is the empty String (its length is zero); otherwise the result is true
Now, to explain why "0" == false
you should read the equality operator, which states it gets its value from the abstract operation GetValue(lref)
matches the same for the right-side.
Which describes this relevant part as:
if IsPropertyReference(V), then a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get be the special [[Get]] internal method defined below. b. Return the result of calling the get internal method using base as its this value, and passing GetReferencedName(V) for the argument
Or in other words, a string has a primitive base, which calls back the internal get method and ends up looking false.
If you want to evaluate things using the GetValue operation use ==
, if you want to evaluate using the ToBoolean
, use ===
(also known as the "strict" equality operator)
It is bug in the Android installer. Download the latest installer and try it. Then it will work.
Copy and paste this format yyyy-mm-dd hh:MM:ss in format cells by clicking customs category under Type
You can try this.
but before you need to install psutil using sudo pip install psutil
import psutil
for proc in psutil.process_iter(attrs=['pid', 'name']):
if 'ichat' in proc.info['name']:
proc.kill()
An open source application called "Startup Creator" configures Windows Startup by creating a script while giving an easy to use interface. Utilizing powerful VBScript, it allows applications or services to start up at timed delay intervals, always in the same order. These scripts are automatically placed in your startup folder, and can be opened back up to allow modifications in the future.
String strWebData="html...." //**Your html string**
WebView webDetail=(WebView) findViewById(R.id.webView1);
WebSettings websetting = webDetail.getSettings();
websetting.setDefaultTextEncodingName("utf-8");
webDetail.loadData(strWebData, "text/html; charset=utf-8", null);
If you using Spring mark the class as @Transactional, then Spring will handle session management.
@Transactional
public class MyClass {
...
}
By using @Transactional
, many important aspects such as transaction propagation are handled automatically. In this case if another transactional method is called the method will have the option of joining the ongoing transaction avoiding the "no session" exception.
WARNING If you do use @Transactional
, please be aware of the resulting behavior. See this article for common pitfalls. For example, updates to entities are persisted even if you don't explicitly call save
I recently had the same issue while trying to access domains using CloudFlare Origin CA.
The only way I found to workaround/avoid HSTS cert exception on Chrome (Windows build) was following the short instructions in https://support.opendns.com/entries/66657664.
The workaround:
Add to Chrome shortcut the flag --ignore-certificate-errors
, then reopen it and surf to your website.
Reminder:
Use it only for development purposes.
You can use the sort
keyword like this:
sort(unique(c))[1:N]
Example:
c <- c(4,2,44,2,1,45,34,2,4,22,244)
sort(unique(c), decreasing = TRUE)[1:5]
will give the first 5 max numbers.
The syntax is almost the same as printf
. With printf
you give the string format and its contents ie:
printf("my %s has %d chars\n", "string format", 30);
With fprintf
it is the same, except now you are also specifying the place to print to:
File *myFile;
...
fprintf( myFile, "my %s has %d chars\n", "string format", 30);
Or in your case:
fprintf( stderr, "my %s has %d chars\n", "string format", 30);
here is a neat and clean code to understand AES 256 algorithm implemented in C#
call Encrypt function as encryptedstring = cryptObj.Encrypt(username, "AGARAMUDHALA", "EZHUTHELLAM", "SHA1", 3, "@1B2c3D4e5F6g7H8", 256);
public class Crypt
{
public string Encrypt(string passtext, string passPhrase, string saltV, string hashstring, int Iterations, string initVect, int keysize)
{
string functionReturnValue = null;
// Convert strings into byte arrays.
// Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = null;
initVectorBytes = Encoding.ASCII.GetBytes(initVect);
byte[] saltValueBytes = null;
saltValueBytes = Encoding.ASCII.GetBytes(saltV);
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
byte[] plainTextBytes = null;
plainTextBytes = Encoding.UTF8.GetBytes(passtext);
// First, we must create a password, from which the key will be derived.
// This password will be generated from the specified passphrase and
// salt value. The password will be created using the specified hash
// algorithm. Password creation can be done in several iterations.
PasswordDeriveBytes password = default(PasswordDeriveBytes);
password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashstring, Iterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = null;
keyBytes = password.GetBytes(keysize/8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = default(RijndaelManaged);
symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate encryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform encryptor = default(ICryptoTransform);
encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = default(MemoryStream);
memoryStream = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cryptoStream = default(CryptoStream);
cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = null;
cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
string cipherText = null;
cipherText = Convert.ToBase64String(cipherTextBytes);
functionReturnValue = cipherText;
return functionReturnValue;
}
public string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
{
string functionReturnValue = null;
// Convert strings defining encryption key characteristics into byte
// arrays. Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = null;
initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = null;
saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = null;
cipherTextBytes = Convert.FromBase64String(cipherText);
// First, we must create a password, from which the key will be
// derived. This password will be generated from the specified
// passphrase and salt value. The password will be created using
// the specified hash algorithm. Password creation can be done in
// several iterations.
PasswordDeriveBytes password = default(PasswordDeriveBytes);
password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = null;
keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = default(RijndaelManaged);
symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate decryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform decryptor = default(ICryptoTransform);
decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = default(MemoryStream);
memoryStream = new MemoryStream(cipherTextBytes);
// Define memory stream which will be used to hold encrypted data.
CryptoStream cryptoStream = default(CryptoStream);
cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
// Since at this point we don't know what the size of decrypted data
// will be, allocate the buffer long enough to hold ciphertext;
// plaintext is never longer than ciphertext.
byte[] plainTextBytes = null;
plainTextBytes = new byte[cipherTextBytes.Length + 1];
// Start decrypting.
int decryptedByteCount = 0;
decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
// Let us assume that the original plaintext string was UTF8-encoded.
string plainText = null;
plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
// Return decrypted string.
functionReturnValue = plainText;
return functionReturnValue;
}
}
Update: In Rails 5, this command will be accessible through this command:
rails db:purge db:create db:migrate RAILS_ENV=test
As of the newest rails 4.2 release you can now run:
rake db:purge
Source: commit
# desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
task :purge => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.purge_current
end
It can be used together like mentioned above:
rake db:purge db:create db:migrate RAILS_ENV=test
There are several other ways, besides using the in
operator (easiest):
index()
>>> try:
... "xxxxABCDyyyy".index("test")
... except ValueError:
... print "not found"
... else:
... print "found"
...
not found
find()
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
... print "found"
...
found
re
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
... print "found"
...
found
<UserControl x:Class="Elections.Server.Handler.Views.LoginView"_x000D_
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"_x000D_
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"_x000D_
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" _x000D_
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"_x000D_
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"_x000D_
xmlns:cal="http://www.caliburnproject.org"_x000D_
mc:Ignorable="d" _x000D_
Height="531" Width="1096">_x000D_
<ContentControl>_x000D_
<ContentControl.Background>_x000D_
<ImageBrush/>_x000D_
</ContentControl.Background>_x000D_
<Grid >_x000D_
<Border BorderBrush="#FFABADB3" BorderThickness="1" HorizontalAlignment="Left" Height="23" Margin="900,100,0,0" VerticalAlignment="Top" Width="160">_x000D_
<TextBox TextWrapping="Wrap"/>_x000D_
</Border>_x000D_
<Border BorderBrush="#FFABADB3" BorderThickness="1" HorizontalAlignment="Left" Height="23" Margin="900,150,0,0" VerticalAlignment="Top" Width="160">_x000D_
<PasswordBox x:Name="PasswordBox"/>_x000D_
</Border>_x000D_
<Button Content="Login" HorizontalAlignment="Left" Margin="985,200,0,0" VerticalAlignment="Top" Width="75">_x000D_
<i:Interaction.Triggers>_x000D_
<i:EventTrigger EventName="Click">_x000D_
<cal:ActionMessage MethodName="Login">_x000D_
<cal:Parameter Value="{Binding ElementName=PasswordBox}" />_x000D_
</cal:ActionMessage>_x000D_
</i:EventTrigger>_x000D_
</i:Interaction.Triggers>_x000D_
</Button>_x000D_
_x000D_
</Grid>_x000D_
</ContentControl>_x000D_
</UserControl>
_x000D_
using System;_x000D_
using System.Windows;_x000D_
using System.Windows.Controls;_x000D_
using Caliburn.Micro;_x000D_
_x000D_
namespace Elections.Server.Handler.ViewModels_x000D_
{_x000D_
public class LoginViewModel : PropertyChangedBase_x000D_
{_x000D_
MainViewModel _mainViewModel;_x000D_
public void SetMain(MainViewModel mainViewModel)_x000D_
{_x000D_
_mainViewModel = mainViewModel;_x000D_
}_x000D_
_x000D_
public void Login(Object password)_x000D_
{_x000D_
var pass = (PasswordBox) password;_x000D_
MessageBox.Show(pass.Password);_x000D_
_x000D_
//_mainViewModel.ScreenView = _mainViewModel.ControlPanelView;_x000D_
//_mainViewModel.TitleWindow = "Panel de Control";_x000D_
//HandlerBootstrapper.Title(_mainViewModel.TitleWindow);_x000D_
}_x000D_
}_x000D_
}
_x000D_
;) easy!
Here git-update-index - Register file contents in the working tree to the index.
git update-index --assume-unchanged <PATH_OF_THE_FILE>
Example:-
git update-index --assume-unchanged somelocation/pom.xml
As mentioned in the github issue originally linked by @peter in the comments:
const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);
SOLVED:
The above did not help. Then I simply installed sklearn from within Jypyter-lab, even though sklearn 0.0 shows in 'pip list':
!pip install sklearn
import sklearn
What I learned later is that pip installs, in my case, packages in a different folder than Jupyter. This can be seen by executing:
import sys
print(sys.path)
Once from within Jupyter_lab notebook, and once from the command line using 'py notebook.py'.
In my case Jupyter list of paths where subfolders of 'anaconda' whereas Python list where subfolders of c:\users[username]...
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
The data structure of shape (n,) is called a rank 1 array. It doesn't behave consistently as a row vector or a column vector which makes some of its operations and effects non intuitive. If you take the transpose of this (n,) data structure, it'll look exactly same and the dot product will give you a number and not a matrix. The vectors of shape (n,1) or (1,n) row or column vectors are much more intuitive and consistent.
It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.
#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl <-- perl script
#!/usr/bin/php <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.
Most scripting languages tend to interpret a line starting with #
as comment and will ignore the following !/usr/bin/whatever
portion, which might otherwise cause a syntax error in the interpreted language.
Here is a little BASH function you can add to your .bashrc or .profile on a UNIX based system. Once added and the shell is either restarted or the file is reloaded via a call to source ~/.profile
or source ~/.bashrc
.
function gitToBare() {
if [ -d ".git" ]; then
DIR="`pwd`"
mv .git ..
rm -fr *
mv ../.git .
mv .git/* .
rmdir .git
git config --bool core.bare true
cd ..
mv "${DIR}" "${DIR}.git"
printf "[\x1b[32mSUCCESS\x1b[0m] Git repository converted to "
printf "bare and renamed to\n ${DIR}.git\n"
cd "${DIR}.git"
else
printf "[\x1b[31mFAILURE\x1b[0m] Cannot find a .git directory\n"
fi
}
Once called within a directory containing a .git directory, it will make the appropriate changes to convert the repository. If there is no .git directory present when called, a FAILURE message will appear and no file system changes will happen.