If you need to update from bundler v1 to v2 follow this official guide.
For a fast solution:
In root fo your application run bundle config set path "/bundle"
to add a custom path for bundler use, in this case I set /bundle
, you can use whatever.
1.2 [Alternative solution] You can use a bundler file (~/.bundle/config
) also, to use this I recommend set bundler folders in environment, like a Docker image, for example. Here the official guide.
You don't need to delete your Gemfile.lock
, It's a bad practice and this can cause other future problems. Commit Gemfile.lock normaly, sometimes you need to update your bundle with bundle install
or install individual gem.
You can see all the configs for bundler version 2 here.
need order
NSArray *yourarray = @[@"a",@"b",@"c"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourarray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
NSLog(@"%@",arrayWithoutDuplicates);
or don't need order
NSSet *set = [NSSet setWithArray:yourarray];
NSArray *arrayWithoutOrder = [set allObjects];
NSLog(@"%@",arrayWithoutOrder);
In Bootstrap 3 I've added a table-no-border class
.table-no-border>thead>tr>th,
.table-no-border>tbody>tr>th,
.table-no-border>tfoot>tr>th,
.table-no-border>thead>tr>td,
.table-no-border>tbody>tr>td,
.table-no-border>tfoot>tr>td {
border-top: none;
}
(sorry, this was a more generic answer about SQL backends--I hadn't read the answer about SQL Server 2005's WebServices feature. Although, this feature is still run over HTTP rather than more directly via sockets, so essentially they've built a mini web server into the database server, so this answer is still another route you could take.)
You can also connect directly using sockets (google "javascript sockets") and by directly at this point I mean using a Flash file for this purpose, although HTML5 has Web Sockets as part of the spec which I believe let you do the same thing.
Some people cite security issues, but if you designed your database permissions correctly you should theoretically be able to access the database from any front end, including OSQL, and not have a security breach. The security issue, then, would be if you weren't connecting via SSL.
Finally, though, I'm pretty sure this is all theoretical because I don't believe any JavaScript libraries exist for handling the communications protocols for SSL or SQL Server, so unless you're willing to figure these things out yourself it'd be better to go the route of having a web server and server-side scripting language in between the browser and the database.
I would say the answer is: you can't. (or at least: you shouldn't). This is not what Webpack is supposed to do. Webpack is a bundler, and it should not be used for other tasks (in this case: copying static files is another task). You should use a tool like Grunt or Gulp to do such tasks. It is very common to integrate Webpack as a Grunt task or as a Gulp task. They both have other tasks useful for copying files like you described, for example, grunt-contrib-copy or gulp-copy.
For other assets (not the index.html
), you can just bundle them in with Webpack (that is exactly what Webpack is for). For example, var image = require('assets/my_image.png');
. But I assume your index.html
needs to not be a part of the bundle, and therefore it is not a job for the bundler.
To add bold, italic and underline, just add the following to the font argument:
font=("Arial", 8, 'normal', 'bold', 'italic', 'underline')
Hash your objects yourself manually, and use the resulting strings as keys for a regular JavaScript dictionary. After all, you are in the best position to know what makes your objects unique. That's what I do.
Example:
var key = function(obj){
// Some unique object-dependent key
return obj.totallyUniqueEmployeeIdKey; // Just an example
};
var dict = {};
dict[key(obj1)] = obj1;
dict[key(obj2)] = obj2;
This way you can control indexing done by JavaScript without heavy lifting of memory allocation, and overflow handling.
Of course, if you truly want the "industrial-grade solution", you can build a class parameterized by the key function, and with all the necessary API of the container, but … we use JavaScript, and trying to be simple and lightweight, so this functional solution is simple and fast.
The key function can be as simple as selecting right attributes of the object, e.g., a key, or a set of keys, which are already unique, a combination of keys, which are unique together, or as complex as using some cryptographic hashes like in DojoX encoding, or DojoX UUID. While the latter solutions may produce unique keys, personally I try to avoid them at all costs, especially, if I know what makes my objects unique.
Update in 2014: Answered back in 2008 this simple solution still requires more explanations. Let me clarify the idea in a Q&A form.
Your solution doesn't have a real hash. Where is it???
JavaScript is a high-level language. Its basic primitive (Object) includes a hash table to keep properties. This hash table is usually written in a low-level language for efficiency. Using a simple object with string keys we use an efficiently implemented hash table without any efforts on our part.
How do you know they use a hash?
There are three major ways to keep a collection of objects addressable by a key:
Obviously JavaScript objects use hash tables in some form to handle general cases.
Do browser vendors really use hash tables???
Really.
Do they handle collisions?
Yes. See above. If you found a collision on unequal strings, please do not hesitate to file a bug with a vendor.
So what is your idea?
If you want to hash an object, find what makes it unique and use it as a key. Do not try to calculate a real hash or emulate hash tables — it is already efficiently handled by the underlying JavaScript object.
Use this key with JavaScript's Object
to leverage its built-in hash table while steering clear of possible clashes with default properties.
Examples to get you started:
I used your suggestion and cached all objects using a user name. But some wise guy is named "toString", which is a built-in property! What should I do now?
Obviously, if it is even remotely possible that the resulting key will exclusively consists of Latin characters, you should do something about it. For example, add any non-Latin Unicode character you like at the beginning or at the end to un-clash with default properties: "#toString", "#MarySmith". If a composite key is used, separate key components using some kind of non-Latin delimiter: "name,city,state".
In general, this is the place where we have to be creative and select the easiest keys with given limitations (uniqueness, potential clashes with default properties).
Note: unique keys do not clash by definition, while potential hash clashes will be handled by the underlying Object
.
Why don't you like industrial solutions?
IMHO, the best code is no code at all: it has no errors, requires no maintenance, easy to understand, and executes instantaneously. All "hash tables in JavaScript" I saw were >100 lines of code, and involved multiple objects. Compare it with: dict[key] = value
.
Another point: is it even possible to beat a performance of a primordial object written in a low-level language, using JavaScript and the very same primordial objects to implement what is already implemented?
I still want to hash my objects without any keys!
We are in luck: ECMAScript 6 (released in June 2015) defines map and set.
Judging by the definition, they can use an object's address as a key, which makes objects instantly distinct without artificial keys. OTOH, two different, yet identical objects, will be mapped as distinct.
Comparison breakdown from MDN:
Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Objects have been used as Maps historically; however, there are important differences that make using a Map preferable in certain cases:
- The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
- The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion.
- You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
- A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
- An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.
- A Map may perform better in scenarios involving frequent addition and removal of key pairs.
A good question! I think DATA ENCODING (sometimes a CHARSET also involved) is a MEMORY EXPRESSION MECHANISM in order to save data to a file or transfer data via a network, so I answer this question as:
1. When should I use std::wstring over std::string?
If the programming platform or API function is a single-byte one, and we want to process or parse some Unicode data, e.g read from Windows'.REG file or network 2-byte stream, we should declare std::wstring variable to easily process them. e.g.: wstring ws=L"??a"(6 octets memory: 0x4E2D 0x56FD 0x0061), we can use ws[0] to get character '?' and ws[1] to get character '?' and ws[2] to get character 'a', etc.
2. Can std::string hold the entire ASCII character set, including the special characters?
Yes. But notice: American ASCII, means each 0x00~0xFF octet stands for one character, including printable text such as "123abc&*_&" and you said special one, mostly print it as a '.' avoid confusing editors or terminals. And some other countries extend their own "ASCII" charset, e.g. Chinese, use 2 octets to stand for one character.
3.Is std::wstring supported by all popular C++ compilers?
Maybe, or mostly. I have used: VC++6 and GCC 3.3, YES
4. What is exactly a "wide character"?
a wide character mostly indicates using 2 octets or 4 octets to hold all countries' characters. 2 octet UCS2 is a representative sample, and further e.g. English 'a', its memory is 2 octet of 0x0061(vs in ASCII 'a's memory is 1 octet 0x61)
In my case I was needed update the std=c++
I mean in my gradle file was this
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags "-std=c++11", "-Wall"
arguments "-DANDROID_STL=c++_static",
"-DARCORE_LIBPATH=${arcore_libpath}/jni",
"-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
}
}
....
}
I changed this line
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags "-std=c++17", "-Wall" <-- this number from 11 to 17 (or 14)
arguments "-DANDROID_STL=c++_static",
"-DARCORE_LIBPATH=${arcore_libpath}/jni",
"-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
}
}
....
}
That's it...
LDAPService should contain method like LDAPService.isExists(String userName)
use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..
Like this:
#include <vector>
// ...
std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));
(Pre-C++11 you need to leave whitespace between the angled brackets.)
This one's already accepted, but if there are any other dummies out there (like me) that didn't immediately get it from the presently accepted answer, here's a bit more detail.
The model class referenced by the ForeignKey
needs to have a __unicode__
method within it, like here:
class Category(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
That made the difference for me, and should apply to the above scenario. This works on Django 1.0.2.
Does the DB know the connection has dropped, or is the session still listed in v$session? That would indicate, I think, that it's being dropped by the network. Do you know how long it can stay idle before encountering the problem, and if that bears any resemblance to the TCP idle values (net.ipv4.tcp_keepalive_time, tcp_keepalive_probes and tcp_keepalive_interval from sysctl if I recall correctly)? Can't remember whether sysctl changes persist by default, but that might be something that was modified and then reset by the reboot.
Also you might be able to reset your JDBC connections without bouncing the whole server; certainly can in WebLogic, which I realise doesn't help much, but I'm not familiar with the Tomcat equivalents.
Note that these solutions use the Code Igniter Active Records Class
This method uses sub queries like you wish but you should sanitize $countryId
yourself!
$this->db->select('username')
->from('user')
->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
->get();
Or this method would do it using joins and will sanitize the data for you (recommended)!
$this->db->select('username')
->from('users')
->join('locations', 'users.locationid = locations.locationid', 'inner')
->where('countryid', $countryId)
->get();
Most likely JDK configuration is not valid, try to remove and add the JDK again as I've described in the related question here.
To answer your question directly, when you call console.log("something")
from the background, this message is logged, to the background page's console. To view it, you may go to chrome://extensions/
and click on that inspect view
under your extension.
When you click the popup, it's loaded into the current page, thus the console.log should show log message in the current page.
This isn't possible in JPA.
Here's what you can do with the Column annotation: http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html
You will be able to get the time using below query:
select left((convert(time(0), GETDATE ())),5)
Using SQL Server 2008
declare @Seconds as int = 3600;
SELECT CONVERT(time(0), DATEADD(SECOND, @Seconds, 0)) as 'hh:mm:ss'
Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range
Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)
Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
strFirstAddress = rngFindValue.Address
Do
Set rngFindValue = search.FindNext(rngFindValue)
Loop Until rngFindValue.Address = strFirstAddress
It may be stupid but it happened to us:
If you are using bitbucket and Sourcetree and you just copy paste the clone URL to the new repo dialog it will show the same error when pulling or pushing.
Make sure you delete the 'git clone' stuff before the URL.
To refresh the whole page, but it works normally:
Response.Redirect(url,bool)
The short answer: there is no difference.
The long answer: CHARACTER VARYING
is the official type name from the ANSI SQL standard, which all compliant databases are required to support. VARCHAR
is a shorter alias which all modern databases also support. I prefer VARCHAR
because it's shorter and because the longer name feels pedantic. However, postgres tools like pg_dump
and \d
will output character varying
.
You can try ExtUtils-Installed, but that only looks in .packlist
s, so it may miss modules that people moved things into @INC
by hand.
I wrote App-Module-Lister for a friend who wanted to do this as a CGI script on a non-shell web hosting account. You simple take the module file and upload it as a filename that your server will treat as a CGI script. It has no dependencies outside of the Standard Library. Use it as is or steal the code.
It outputs a list of the modules and their versions:
Tie::Cycle 1.15 Tie::IxHash 1.21 Tie::Toggle 1.07 Tie::ToObject 0.03 Time::CTime 99.062201 Time::DaysInMonth 99.1117 Time::Epoch 0.02 Time::Fuzzy 0.34 Time::JulianDay 2003.1125 Time::ParseDate 2006.0814 Time::Timezone 2006.0814
I've been meaning to add this as a feature to the cpan
tool, so I'll do that too. [Time passes] And, now I have a -l
switch in cpan
. I have a few other things to do with it before I make a release, but it's in github. If you don't want to wait for that, you could just try the -a
switch to create an autobundle, although that puts some Pod around the list.
Good luck;
Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)
using MODI;
static void Main(string[] args)
{
DocumentClass myDoc = new DocumentClass();
myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);
foreach (Image anImage in myDoc.Images)
{
Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
}
}
The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));
for(int i=0 ; i<16 ; i++){
JButton btn = new JButton(String.valueOf(i));
btn.setPreferredSize(new Dimension(40, 40));
panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.
Edit
I've modified the provided code and I believe it now conforms to what is desired:
JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(100, 100));
firstPanel.add(btn);
}
}
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
for (int j=1; j<=13; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(40, 40));
secondPanel.add(btn);
}
}
mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);
frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);
Basically I now set the preferred size of the panels and a minimum size for the frame.
Actually, you can try WindowManager.LayoutParams.TYPE_SYSTEM_ERROR instead of TYPE_SYSTEM_OVERLAY. It may sound like a hack, but it let you display view on top of everything and still get touch events.
Thanks loads for the answers above. I'm adding an answer for a specific use-case...
On a project with two target architectures each with its own build configuration (the main target is an embedded AVR platform; the second target is my local Linux PC for running unit tests) I found it necessary to set Preferences -> C/C++ -> Indexer -> Use active build configuration
as well as to add /usr/include/c++/4.7
, /usr/include
and /usr/include/c++/4.7/x86_64-linux-gnu
to Project Properties -> C/C++ General -> Paths and Symbols
and then to rebuild the index.
Example from google
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
You need to check the return value against EOF
, not against 1
.
Note that in your example, you also used two different variable names, words
and word
, only declared words
, and didn't declare its length, which should be 16 to fit the 15 characters read in plus a NUL
character.
contentType
is the type of data you're sending, so application/json; charset=utf-8
is a common one, as is application/x-www-form-urlencoded; charset=UTF-8
, which is the default.
dataType
is what you're expecting back from the server: json
, html
, text
, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
alert(result.success); // result is an object which is created from the returned JSON
},
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
dataType : "html",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
One more - if you want to post:
name=John&age=34
Then don't stringify
the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
dataType : "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
data : data,
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
Anything using the managed environment (which includes anything written in C# and VB.NET) requires the .NET framework. You can simply redistribute your .EXE in that scenario, but they'll need to install the appropriate framework if they don't already have it.
select distinct(t1.sal)
from emp t1
where &n=(select count(distinct(t2.sal)) from emp t2 where t1.sal<=t2.sal);
Output: Enter value for n: if you want 2nd highest ,enter 2; if you want 5,enter n=3
In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.
query user /server:$SERVER
You want huge?
Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));
insert into foo(crap) values ('');
-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;
run it twenty more times, you have over a million rows to play with.
Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)
Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".
Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.
Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.
Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.
For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.
Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.
By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.
If order is not the matter:
>>> foo='mppmt'
>>> ''.join(set(foo))
'pmt'
To keep the order:
>>> foo='mppmt'
>>> ''.join([j for i,j in enumerate(foo) if j not in foo[:i]])
'mpt'
Because it's unnecessary¹. There's very few situations where a dev would need it.
A) When you have a very simple loop, say a 1- or 2-liner, then you can just turn the loop condition around and it's still plenty readable.
B) When you're writing simple procedural code (aka. how we wrote code in the last century), you should also be applying structured programming (aka. how we wrote better code in the last century)
C) If you're writing object-oriented code, your loop body should consist of no more than one or two method calls unless it can be expressed in a one- or two-liner (in which case, see A)
D) If you're writing functional code, just return a plain tail-call for the next iteration.
The only case when you'd want to use a continue
keyword is if you want to code Lua like it's python, which it just isn't.²
Unless A) applies, in which case there's no need for any workarounds, you should be doing Structured, Object-Oriented or Functional programming. Those are the paradigms that Lua was built for, so you'd be fighting against the language if you go out of your way to avoid their patterns.³
Some clarification:
¹ Lua is a very minimalistic language. It tries to have as few features as it can get away with, and a continue
statement isn't an essential feature in that sense.
I think this philosophy of minimalism is captured well by Roberto Ierusalimschy in this 2019 interview:
add that and that and that, put that out, and in the end we understand the final conclusion will not satisfy most people and we will not put all the options everybody wants, so we don’t put anything. In the end, strict mode is a reasonable compromise.
² There seems to be a large ammount of programmers coming to Lua from other languages because whatever program they're trying to script for happens to use it, and many of them want don't seem to want to write anything other than their language of choice, which leads to many questions like "Why doesn't Lua have X feature?"
Matz described a similar situation with Ruby in a recent interview:
The most popular question is: "I’m from the language X community; can’t you introduce a feature from the language X to Ruby?", or something like that. And my usual answer to these requests is… "no, I wouldn’t do that", because we have different language design and different language development policies.
³ There's a few ways to hack your way around this; some users have suggested using goto
, which is a good enough aproximation in most cases, but gets very ugly very quickly and breaks completely with nested loops. Using goto
s also puts you in danger of having a copy of SICP thrown at you whenever you show your code to anybody else.
select tableA.id from tableA left outer join tableB on (tableA.id = tableB.id)
where tableB.id is null
order by tableA.id desc
If your db knows how to do index intersections, this will only touch the primary key index
Try these to clarify the issue of right alignment in float point printing
printf(" 4|%4.1lf\n", 8.9);
printf("04|%04.1lf\n", 8.9);
the output is
4| 8.9
04|08.9
I thought I will share how I resolved the same issue "Error Could not open lib\amd64\jvm.cfg". I found the Java run time Jre7 is missing amd64 folder under lib. However, I have 1.7.0_25 JDK which is having jre folder and also having amd64.
I moved the original contents of jre7 folder to a backup file and copied everything from 1.7.0_25\jre.
Now I am not getting this error anymore and able to proceed with scene builder.
To run one project at a time in same solution
Open Solution explorer window -> Open Solution for Project -> Right click on it -> Select Properties from drop down list (Alt+Enter)-> Common Properties -> select Startup Project you will see "current selection,single selection and multiple selection from that select "Current Selection" this will help you to run one project at a time in same solution workspace having different coding.
I was able to get past this by making sure all my SDKs were up to date. (Mac OS 10.13.3, Android Studio 3.0.1). I went to Android Studio -> Check for Updates... and let it run. Once my Android 5.0/5.1 (API level 21/22) SDKs were updated to revision 2:
After doing this update, I was able to run the emulator without crashing out immediately with a "Emulator: Process finished with exit code 0" error.
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
Read this documentation of moment.js here. See below example and output where I convert GMT time to local time (my zone is IST) and then I convert local time to GMT.
// convert GMT to local time
console.log('Server time:' + data[i].locationServerTime)
let serv_utc = moment.utc(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
console.log('serv_utc:' + serv_utc)
data[i].locationServerTime = moment(serv_utc,"YYYY-MM-DD HH:mm:ss").tz(self.zone_name).format("YYYY-MM-DD HH:mm:ss");
console.log('Converted to local time:' + data[i].locationServerTime)
// convert local time to GMT
console.log('local time:' + data[i].locationServerTime)
let serv_utc = moment(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
console.log('serv_utc:' + serv_utc)
data[i].locationServerTime = moment.utc(serv_utc,"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
console.log('Converted to server time:' + data[i].locationServerTime)
Output is
Server time:2019-12-19 09:28:13
serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
Converted to local time:2019-12-19 14:58:13
local time:2019-12-19 14:58:13
serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
Converted to server time:2019-12-19 09:28:13
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
Return value:
READ_COMMITTED_SNAPSHOT
option is ON. Read operations under the READ COMMITTED
isolation level are based on snapshot scans and do not acquire locks.READ_COMMITTED_SNAPSHOT
option is OFF. Read operations under the READ COMMITTED
isolation level use Shared (S) locks.I just wrote a script that lets you achieve this. It gives you two global functions: hasEvent(Node elm, String event)
and getEvents(Node elm)
which you can utilize. Be aware that it modifies the EventTarget
prototype method add/RemoveEventListener
, and does not work for events added through HTML markup or javascript syntax of elm.on_event = ...
Script:
var hasEvent,getEvents;!function(){function b(a,b,c){c?a.dataset.events+=","+b:a.dataset.events=a.dataset.events.replace(new RegExp(b),"")}function c(a,c){var d=EventTarget.prototype[a+"EventListener"];return function(a,e,f,g,h){this.dataset.events||(this.dataset.events="");var i=hasEvent(this,a);return c&&i||!c&&!i?(h&&h(),!1):(d.call(this,a,e,f),b(this,a,c),g&&g(),!0)}}hasEvent=function(a,b){var c=a.dataset.events;return c?new RegExp(b).test(c):!1},getEvents=function(a){return a.dataset.events.replace(/(^,+)|(,+$)/g,"").split(",").filter(function(a){return""!==a})},EventTarget.prototype.addEventListener=c("add",!0),EventTarget.prototype.removeEventListener=c("remove",!1)}();
You cannot use function calls in a class construction, you should initialize that value in the constructor function.
From the PHP Manual on class properties:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
A working code sample:
<?php
class UserDatabaseConnection
{
public $connection;
public function __construct()
{
$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
public function lookupUser($username)
{
// rest of my code...
// example usage (procedural way):
$query = sqlite_exec($this->connection, "SELECT ...", $error);
// object oriented way:
$query = $this->connection->queryExec("SELECT ...", $error);
}
}
$udb = new UserDatabaseConnection;
?>
Depending on your needs, protected
or private
might be a better choice for $connection
. That protects you from accidentally closing or messing with the connection.
An excellent and very fast file search utility, Agent Ransack, supports regular expression searching. It's primarily a GUI utility, but a command-line interface is also available.
I use
barbeque
, it's great, and supports a very wide range of different barcode formats.
See if you like
its API
.
Sample API:
public static Barcode createCode128(java.lang.String data) throws BarcodeException
Creates a Code 128 barcode that dynamically switches between character sets to give the smallest possible encoding. This will encode all numeric characters, upper and lower case alpha characters and control characters from the standard ASCII character set. The size of the barcode created will be the smallest possible for the given data, and use of this "optimal" encoding will generally give smaller barcodes than any of the other 3 "vanilla" encodings.
I have had co-workers that have used Burp ("an interactive HTTP/S proxy server for attacking and testing web applications") for this. You also may be able to use Fiddler ("a HTTP Debugging Proxy").
In my case, i have to set the theme on the runtime in java based on some conditions. So I created one theme in style (similar to other answers):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>
Then in Java I applied it to my activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
String email = getIntent().getStringExtra(AppConstants.REGISTER_EMAIL_INTENT_KEY);
if (email != null && !email.isEmpty()) {
// We have the valid email ID, no need to take it from user,
// prepare transparent activity just to perform bg tasks required for login
setTheme(R.style.Theme_Transparent);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
} else
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy);
}
Remember one Important point here: You must call the setTheme()
function before super.onCreate(savedInstanceState);
. I missed this point and stucked for 2 hours, thinking why my theme is not reflected at run time.
Use 'index'.
def GetMorseCode(letter):
index = letterList.index(letter)
code = codeList[index]
return code
Of course, you'll want to validate your input letter (convert its case as necessary, make sure it's in the list in the first place by checking that index != -1), but that should get you down the path.
There's a distinction to me that scp
is always encrypted with ssh (secure shell), while rsync
isn't necessarily encrypted. More specifically, rsync
doesn't perform any encryption by itself; it's still capable of using other mechanisms (ssh for example) to perform encryption.
In addition to security, encryption also has a major impact on your transfer speed, as well as the CPU overhead. (My experience is that rsync
can be significantly faster than scp
.)
Check out this post for when rsync
has encryption on.
I use this piece of code, its quite nice :)
<script language="javascript" src="http://code.jquery.com/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function(){
$(".div_container").mousemove(function(e){
var parentOffset = $(this).parent().offset();
var relativeXPosition = (e.pageX - parentOffset.left); //offset -> method allows you to retrieve the current position of an element 'relative' to the document
var relativeYPosition = (e.pageY - parentOffset.top);
$("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
}).mouseout(function(){
$("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
});
});
</script>
Functions are not allowed to have side-effects such as altering table contents.
Stored Procedures are.
If a function called a stored procedure, the function would become able to have side-effects.
So, sorry, but no, you can't call a stored procedure from a function.
This seems like the best choice to me:
val1, val2, ignored1, ignored2 = some_function()
It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.
I've get closer to VisualStudio-like behaviour by setting the "Autocomplete Trigger for Java" to
.(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
and setting delay to 0.
Now I'd like to realize how to make it autocomplete method name when I press ( as VS's Intellisense does.
The code helped me to fulfill my requirement.
I have made some modifications and using a form I completed this. Here is my code-
Need a 'target' attribute for 'form' -- that's it!
Form
<form id="view_form" name="view_form" method="post" action="view_report.php" target="Map" >
<input type="text" value="<?php echo $sale->myvalue1; ?>" name="my_value1"/>
<input type="text" value="<?php echo $sale->myvalue2; ?>" name="my_value2"/>
<input type="button" id="download" name="download" value="View report" onclick="view_my_report();" />
</form>
JavaScript
function view_my_report() {
var mapForm = document.getElementById("view_form");
map=window.open("","Map","status=0,title=0,height=600,width=800,scrollbars=1");
if (map) {
mapForm.submit();
} else {
alert('You must allow popups for this map to work.');
}
}
Full code is explained showing normal form and form elements.
Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...
PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));
So it will return false when the method is called in same test case and then it will return false again and lastly true.
You can look into Windows installed folder from here of your pc path:
C:\Program Files (x86)\Microsoft ASP.NET
View of Opened file where showing installed MVC 3, MVC 4
I was having the same problem, I had a ComboBox followed by a ListBox in a StackPanel and the scroll bar for the ListBox was not showing up. I solved this by putting the two in a DockPanel instead. I set the ComboBox DockPanel.Dock="Top" and let the ListBox fill the remaining space.
I have gone through the same problem when I was using
myApp.controller('mainController', ['$scope', function($scope,) {
//$http was not working in this
}]);
I have changed the above code to given below. Remember to include $http(2 times) as given below.
myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
//$http is working in this
}]);
and It has worked well.
It means that you compiled your classes under a specific JDK, but then try to run them under older version of JDK.
The following works for all tables
CREATE TABLE `noDup` LIKE `Dup` ;
INSERT `noDup` SELECT DISTINCT * FROM `Dup` ;
DROP TABLE `Dup` ;
ALTER TABLE `noDup` RENAME `Dup` ;
This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.
public static class ReflectiveEnumerator
{
static ReflectiveEnumerator() { }
public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
{
List<T> objects = new List<T>();
foreach (Type type in
Assembly.GetAssembly(typeof(T)).GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
{
objects.Add((T)Activator.CreateInstance(type, constructorArgs));
}
objects.Sort();
return objects;
}
}
A few notes:
Assembly.GetAssembly(typeof(T))
because your base class might be in a different assembly. type.IsClass
and !type.IsAbstract
because it'll throw an exception if you try to instantiate an interface or abstract class.IComparable
so that they can be sorted.You can use this variable to retrieve response headers after file_get_contents()
function.
Code:
file_get_contents("http://example.com");
var_dump($http_response_header);
Output:
array(9) {
[0]=>
string(15) "HTTP/1.1 200 OK"
[1]=>
string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
[2]=>
string(29) "Server: Apache/2.2.3 (CentOS)"
[3]=>
string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
[4]=>
string(27) "ETag: "280100-1b6-80bfd280""
[5]=>
string(20) "Accept-Ranges: bytes"
[6]=>
string(19) "Content-Length: 438"
[7]=>
string(17) "Connection: close"
[8]=>
string(38) "Content-Type: text/html; charset=UTF-8"
}
Here is a updated version of the code provided by @theprtk. It is a cleaned up a little to show the generalized version whilst having an example.
Note: I'd add this as a comment to his post but I don't have enough reputation yet
/**
* @see http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html
* @description functions that transform reducing functions
*/
const transduce = {
/** a generic map() that can take a reducing() & return another reducing() */
map: changeInput => reducing => (acc, input) =>
reducing(acc, changeInput(input)),
/** a generic filter() that can take a reducing() & return */
filter: predicate => reducing => (acc, input) =>
predicate(input) ? reducing(acc, input) : acc,
/**
* a composing() that can take an infinite # transducers to operate on
* reducing functions to compose a computed accumulator without ever creating
* that intermediate array
*/
compose: (...args) => x => {
const fns = args;
var i = fns.length;
while (i--) x = fns[i].call(this, x);
return x;
},
};
const example = {
data: [{ src: 'file.html' }, { src: 'file.txt' }, { src: 'file.json' }],
/** note: `[1,2,3].reduce(concat, [])` -> `[1,2,3]` */
concat: (acc, input) => acc.concat([input]),
getSrc: x => x.src,
filterJson: x => x.src.split('.').pop() !== 'json',
};
/** step 1: create a reducing() that can be passed into `reduce` */
const reduceFn = example.concat;
/** step 2: transforming your reducing function by mapping */
const mapFn = transduce.map(example.getSrc);
/** step 3: create your filter() that operates on an input */
const filterFn = transduce.filter(example.filterJson);
/** step 4: aggregate your transformations */
const composeFn = transduce.compose(
filterFn,
mapFn,
transduce.map(x => x.toUpperCase() + '!'), // new mapping()
);
/**
* Expected example output
* Note: each is wrapped in `example.data.reduce(x, [])`
* 1: ['file.html', 'file.txt', 'file.json']
* 2: ['file.html', 'file.txt']
* 3: ['FILE.HTML!', 'FILE.TXT!']
*/
const exampleFns = {
transducers: [
mapFn(reduceFn),
filterFn(mapFn(reduceFn)),
composeFn(reduceFn),
],
raw: [
(acc, x) => acc.concat([x.src]),
(acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src] : []),
(acc, x) => acc.concat(x.src.split('.').pop() !== 'json' ? [x.src.toUpperCase() + '!'] : []),
],
};
const execExample = (currentValue, index) =>
console.log('Example ' + index, example.data.reduce(currentValue, []));
exampleFns.raw.forEach(execExample);
exampleFns.transducers.forEach(execExample);
I did it a different way to what I was wanting to do...gave me the result I needed. I chose not to submit the form, rather just get the value of the text field and use it in the javascript and then reset the text field. Sorry if I bothered anyone with this question.
Basically just did this:
var search = document.getElementById('search').value;
document.getElementById('search').value = "";
I use this simple code:
//reset form
$("#mybutton").click(function(){
$("#myform").find('input:text, input:password, input:file, select, textarea').val('');
$("#myform").find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
});
For the datatype Double
to int
, you can use the following:
Double double = 5.00;
int integer = double.intValue();
git-subtree
is a script designed for exactly this use case of merging multiple repositories into one while preserving history (and/or splitting history of subtrees, though that seems to be irrelevant to this question). It is distributed as part of the git tree since release 1.7.11.
To merge a repository <repo>
at revision <rev>
as subdirectory <prefix>
, use git subtree add
as follows:
git subtree add -P <prefix> <repo> <rev>
git-subtree implements the subtree merge strategy in a more user friendly manner.
For your case, inside repository YYY, you would run:
git subtree add -P ZZZ /path/to/XXX.git master
The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a
will show you all the changes (if any) except those in the merged history. You can do:
git log --follow -- a
but that won't show the changes other then in the merged history.
In other words, if you don't change ZZZ
's files in repository XXX
, then you need to specify --follow
and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.
More on it here.
Two divs, one for header, one for data. Make the data div scrollable, and use JavaScript to set the width of the columns in the header to be the same as the widths in the data. I think the data columns widths need to be fixed rather than dynamic.
For SQL Server before 2012 which does not include the FORMAT function, create this function:
CREATE FUNCTION FormatCurrency(@value numeric(30,2))
RETURNS varchar(50)
AS
BEGIN
DECLARE @NumAsChar VARCHAR(50)
SET @NumAsChar = '$' + CONVERT(varchar(50), CAST(@Value AS money),1)
RETURN @NumAsChar
END
select dbo.FormatCurrency(12345678) returns $12,345,678.00
Drop the $ if you just want commas.
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
There are some good answers here but also some misunderstandings. I support the following settings for modern browsers when styling for dimensions in web pages:
html {
height: 100%; /* fallback for IE and older browsers */
height: 100vh;
}
body {
height: auto; /* required to allow content to expand vertically without overflow */
width: auto;
min-height: 100%; /* fallback for IE and older browsers */
min-height: 100vh;
margin: 0;
padding: 0;
}
For starters, the new viewport units ("vh") are redundant and not necessary as long as you have set html
to a height of 100%
. The reason is the body
derives its values from the html
parent. You can still use "vh" units in body
to bypass the parent and get its property dimensions directly from the viewport. But its optional if html
has 100%
height.
Notice I've set body
to height:auto
. You do NOT want to set body
height
and width
to 100%
, or specific values as that limits content to the viewport's dimensions and there will be overflow. height:auto
is your best friend in CSS! Using overflow:auto
properties are not needed if you set height:auto
on the body
. That tells the page to let content expand height to any dimension necessary, even that beyond the viewport's height, if it needs to. It will not break out of the body
dimensions. And it does allow scrolling as needed. auto
also allows you to have margins and still support pages that fill the viewport using min-height
. I believe height:auto
is the default on body in most UA browser style sheets, anyway.
Adding min-height:100%
then gives you the default height you want body
to have and then allows the page dimensions to fill the viewport without content breaking out of the body. This works only because html
has derived its height:100%
based on the viewport.
The two CRITICAL pieces here are not the units, like %
or vh
, but making sure the root element, or html
, is set to 100% of the viewport height. Second, its important that body have a min-height:100%
or min-height:100vh
so it starts out filling the viewport height, whatever that may be. Nothing else beyond that is needed. Notice I have added "fallback" properties for min-height, as many browsers post-2010 do not support "vh" units. Its fun to pretend everyone in the web world uses the latest and greatest but the reality is many legacy browsers are still around today in big corporate networks still use antiquated browsers that do not understand those new units.
STYLING HEIGHT FOR LEGACY BROWSERS
One of the things we forget is many very old browsers do not know how to fill the the viewport height correctly. Sadly, those legacy browsers simply had to have height:100%
on both the html
element and the body
. If you did not do that, browser background colors and other weird visuals would flow up under content that did not fill the viewport. We solved that by delivering these 100% values only to older user-agents. If you are testing on a legacy browser, keep that in mind.
html {
height:100%;
}
body {
height:100%;
width:auto;
margin:0;
padding:0;
}
The command line utility nmap can do this too:
nmap -sP 192.168.1.*
add display: block;
a-tag is an inline element so your height and width are ignored.
#header div#snav div a{
display:block;
width:150px;
height:77px;
}
I think that moving last operator to the beginning of the next line is a good practice. That way you know right away the purpose of the second line, even it doesn't start with an operator. I also recommend 2 indentation spaces (2 tabs) for a previously broken tab, to differ it from the normal indentation. That is immediately visible as continuing previous line. Therefore I suggest this:
private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper
= new HashMap<Class<? extends Persistent>, PersistentHelper>();
I am using remove and replace both for refreshing content of Fragment like
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.remove(resetFragment).commit();
fragmentTransaction.replace(R.id.frame_container,resetFragment).commit();
Louis' answer is great, but I thought I would try to sum it up succinctly:
The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".
Minimal runnable example
glOrtho
: 2D games, objects close and far appear the same size:
glFrustrum
: more real-life like 3D, identical objects further away appear smaller:
main.c
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
static int ortho = 0;
static void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
if (ortho) {
} else {
/* This only rotates and translates the world around to look like the camera moved. */
gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
glColor3f(1.0f, 1.0f, 1.0f);
glutWireCube(2);
glFlush();
}
static void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (ortho) {
glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
} else {
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
}
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
if (argc > 1) {
ortho = 1;
}
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return EXIT_SUCCESS;
}
Compile:
gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut
Run with glOrtho
:
./main 1
Run with glFrustrum
:
./main
Tested on Ubuntu 18.10.
Schema
Ortho: camera is a plane, visible volume a rectangle:
Frustrum: camera is a point,visible volume a slice of a pyramid:
Parameters
We are always looking from +z to -z with +y upwards:
glOrtho(left, right, bottom, top, near, far)
left
: minimum x
we seeright
: maximum x
we seebottom
: minimum y
we seetop
: maximum y
we see-near
: minimum z
we see. Yes, this is -1
times near
. So a negative input means positive z
.-far
: maximum z
we see. Also negative.Schema:
How it works under the hood
In the end, OpenGL always "uses":
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
If we use neither glOrtho
nor glFrustrum
, that is what we get.
glOrtho
and glFrustrum
are just linear transformations (AKA matrix multiplication) such that:
glOrtho
: takes a given 3D rectangle into the default cubeglFrustrum
: takes a given pyramid section into the default cubeThis transformation is then applied to all vertexes. This is what I mean in 2D:
The final step after transformation is simple:
x
, y
and z
are in [-1, +1]
z
component and take only x
and y
, which now can be put into a 2D screenWith glOrtho
, z
is ignored, so you might as well always use 0
.
One reason you might want to use z != 0
is to make sprites hide the background with the depth buffer.
Deprecation
glOrtho
is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.
So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.
Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.
Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.
Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245
With an explicit GLfloat transform[]
it would look something like this:
glfw_transform.c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
"#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"layout (location = 1) in vec3 color;\n"
"out vec3 ourColor;\n"
"uniform mat4 transform;\n"
"void main() {\n"
" gl_Position = transform * vec4(position, 1.0f);\n"
" ourColor = color;\n"
"}\n";
static const GLchar* fragment_shader_source =
"#version 330 core\n"
"in vec3 ourColor;\n"
"out vec4 color;\n"
"void main() {\n"
" color = vec4(ourColor, 1.0f);\n"
"}\n";
static GLfloat vertices[] = {
/* Positions Colors */
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
const char *vertex_shader_source,
const char *fragment_shader_source
) {
GLchar *log = NULL;
GLint log_length, success;
GLuint fragment_shader, program, vertex_shader;
/* Vertex shader */
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
glCompileShader(vertex_shader);
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
log = malloc(log_length);
if (log_length > 0) {
glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
printf("vertex shader log:\n\n%s\n", log);
}
if (!success) {
printf("vertex shader compile error\n");
exit(EXIT_FAILURE);
}
/* Fragment shader */
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
glCompileShader(fragment_shader);
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0) {
log = realloc(log, log_length);
glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
printf("fragment shader log:\n\n%s\n", log);
}
if (!success) {
printf("fragment shader compile error\n");
exit(EXIT_FAILURE);
}
/* Link shaders */
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success);
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0) {
log = realloc(log, log_length);
glGetProgramInfoLog(program, log_length, NULL, log);
printf("shader link log:\n\n%s\n", log);
}
if (!success) {
printf("shader link error");
exit(EXIT_FAILURE);
}
/* Cleanup. */
free(log);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return program;
}
int main(void) {
GLint shader_program;
GLint transform_location;
GLuint vbo;
GLuint vao;
GLFWwindow* window;
double time;
glfwInit();
window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
glewInit();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glViewport(0, 0, WIDTH, HEIGHT);
shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
/* Position attribute */
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
/* Color attribute */
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shader_program);
transform_location = glGetUniformLocation(shader_program, "transform");
/* THIS is just a dummy transform. */
GLfloat transform[] = {
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
};
time = glfwGetTime();
transform[0] = 2.0f * sin(time);
transform[5] = 2.0f * cos(time);
glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glfwTerminate();
return EXIT_SUCCESS;
}
Compile and run:
gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out
Output:
The matrix for glOrtho
is really simple, composed only of scaling and translation:
scalex, 0, 0, translatex,
0, scaley, 0, translatey,
0, 0, scalez, translatez,
0, 0, 0, 1
as mentioned in the OpenGL 2 docs.
The glFrustum
matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho
, more info at: https://gamedev.stackexchange.com/a/118848/25171
The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho
and frustum
operations.
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
While this does not answer the question asked, it answers a related question that many people have had:
x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"
df <- data.frame(x,y)
names(df) <- c(x_name,y_name)
print(df)
cond rating
1 1 100
2 2 200
3 3 300
You could also use DateTime.FromFileTime(finishTime) where finishTme is a long containing the ticks of a time. Or FromFileTimeUtc.
Try this command:
Dism.exe /online /enable-feature /featurename:NetFX3 /Source:I:\Sources\sxs /LimitAccess
I:
partition of your Windows DVD.
To supplement the above answers into something a little more re-usable, I've come up with this, which continues to prompt the user if the input is considered invalid.
try:
input = raw_input
except NameError:
pass
def prompt(message, errormessage, isvalid):
"""Prompt for input given a message and return that value after verifying the input.
Keyword arguments:
message -- the message to display when asking the user for the value
errormessage -- the message to display when the value fails validation
isvalid -- a function that returns True if the value given by the user is valid
"""
res = None
while res is None:
res = input(str(message)+': ')
if not isvalid(res):
print str(errormessage)
res = None
return res
It can be used like this, with validation functions:
import re
import os.path
api_key = prompt(
message = "Enter the API key to use for uploading",
errormessage= "A valid API key must be provided. This key can be found in your user profile",
isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))
filename = prompt(
message = "Enter the path of the file to upload",
errormessage= "The file path you provided does not exist",
isvalid = lambda v : os.path.isfile(v))
dataset_name = prompt(
message = "Enter the name of the dataset you want to create",
errormessage= "The dataset must be named",
isvalid = lambda v : len(v) > 0)
private SpannableStringBuilder SpannableStringBuilder(final String text, final char afterChar, final float reduceBy) {
RelativeSizeSpan smallSizeText = new RelativeSizeSpan(reduceBy);
SpannableStringBuilder ssBuilder = new SpannableStringBuilder(text);
ssBuilder.setSpan(
smallSizeText,
text.indexOf(afterChar),
text.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
return ssBuilder;
}
------------------------
TextView textView =view.findViewById(R.id.textview);
String s= "123456.24";
textView.setText(SpannableStringBuilder(s, '.', 0.7f));
---------------- Result ---------------
12345.24
This configuration in httpd.conf work fine for me.
<Directory "c:/wamp/www/">
Options Indexes FollowSymLinks
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1 ::1
</Directory>
Two corrections:
You have to make an ArrayList
of People
objects:
ArrayList<People> preps = new ArrayList<People>();
After adding the objects to the preps, use:
Collections.sort(preps, new CompareId());
Also, add a CompareId
class as:
class CompareId implements Comparator {
public int compare(Object obj1, Object obj2) {
People t1 = (People)obj1;
People t2 = (People)obj2;
if (t1.marks > t2.marks)
return 1;
else
return -1;
}
}
Command EXPOSE
in your Dockerfile lets you bind container's port to some port on the host machine but it doesn't do anything else.
When running container, to bind ports specify -p
option.
So let's say you expose port 5000. After building the image when you run the container, run docker run -p 5000:5000 name
. This binds container's port 5000 to your laptop/computers port 5000 and that portforwarding lets container to receive outside requests.
This should do it.
If you don't want to modify the dataframe, you could use a custom formatter for that column.
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print df.to_string(formatters={'cost':'${:,.2f}'.format})
yields
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
I solved this error by installing the browser driver:
Reference: search YouTube.com for the error
Platform: macOS High Sierra 10.13.3
Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.
Location selected_location = new Location("locationA");
selected_location.setLatitude(17.372102);
selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
near_locations.setLatitude(17.375775);
near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);
here "distance" is distance between locationA & locationB (in Meters
)
select VALUE from TABLE1 where TIME =
(select max(TIME) from TABLE1 where DATE=
(select max(DATE) from TABLE1 where CRITERIA=CRITERIA))
Perhaps the error message is somewhat misleading, but the gist is that X_train
is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:
out_images = np.array(X_train)[indices.astype(int)]
you could put the style in container div menu with:
<div style="position:relative; z-index:10">
...
<!--html menu-->
...
</div>
before
after
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
I’ve been using ng cli lately, and it was really tough to find a good way to structure my code.
The most efficient one I've seen so far comes from mrholek repository (https://github.com/mrholek/CoreUI-Angular).
This folder structure allows you to keep your root project clean and structure your components, it avoids redundant (sometimes useless) naming convention of the official Style Guide.
Also it’s, this structure is useful to group import when it’s needed and avoid having 30 lines of import for a single file.
src
|
|___ app
|
| |___ components/shared
| | |___ header
| |
| |___ containers/layout
| | |___ layout1
| |
| |___ directives
| | |___ sidebar
| |
| |___ services
| | |___ *user.service.ts*
| |
| |___ guards
| | |___ *auth.guard.ts*
| |
| |___ views
| | |___ about
| |
| |___ *app.component.ts*
| |
| |___ *app.module.ts*
| |
| |___ *app.routing.ts*
|
|___ assets
|
|___ environments
|
|___ img
|
|___ scss
|
|___ *index.html*
|
|___ *main.ts*
If you remember which branch was checked out before (e.g. master
) you could simply
git checkout master
to get out of detached HEAD state.
Generally speaking: git checkout <branchname>
will get you out of that.
If you don't remember the last branch name, try
git checkout -
This also tries to check out your last checked out branch.
Alternatively:
if( jQuery('#elem').get(0) ) {}
http://jsfiddle.net/SebastianPataneMasuelli/rJxQC/
i just wrapped a div around them and made it align center. then you don't need any css on the buttons to center them.
<div class="buttonHolder">
<input value="Search" title="Search" type="submit" id="btn_s">
<input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit" id="btn_i">
</div>
.buttonHolder{ text-align: center; }
You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:
SELECT Name,
SUM(Value) AS "SUM(VALUE)",
SUM(Value) / totals.total AS "% of Total"
FROM table1,
(
SELECT Name,
SUM(Value) AS total
FROM table1
GROUP BY Name
) AS totals
WHERE table1.Name = totals.Name
AND Year BETWEEN 2000 AND 2001
GROUP BY Name;
Note that the subquery does not have the WHERE clause filtering the years.
Use TARGETDIR instead of INSTALLDIR. Note that the quote marks for TARGETDIR property are only around the path in the case of spaces.
msiexec /i "msi path" TARGETDIR="C:\myfolder" /qb
Your second example does not work because there is no operator +
for two string literals. Note that a string literal is not of type string
, but instead is of type const char *
. Your second example will work if you revise it like this:
const string message = string("Hello") + ",world" + exclam;
In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode
property to None
.
You can use $addToSet with the aggregation framework to count distinct objects.
For example:
db.collectionName.aggregate([{
$group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])
The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as
pip3 install hide_code
Visit https://github.com/kirbs-/hide_code/ for more info about this extension.
You could use RegEx:
Regex.IsMatch(hello, @"^[a-zA-Z]+$");
If you don't like that, you can use LINQ:
hello.All(Char.IsLetter);
Or, you can loop through the characters, and use isAlpha:
Char.IsLetter(character);
I was able to list all untracked files reported by svn st
in bash by doing:
echo $(svn st | grep -P "^\?" | cut -c 9-)
If you are feeling lucky, you could replace echo
with rm
to delete untracked files. Or copy the files you want to delete by hand, if you are feeling a less lucky.
(I used @abe-voelker 's answer to revert the remaining files: https://stackoverflow.com/a/6204601/1695680)
Drop root privileges after you bind to port 80 (or 443).
This allows port 80/443 to remain protected, while still preventing you from serving requests as root:
function drop_root() {
process.setgid('nobody');
process.setuid('nobody');
}
A full working example using the above function:
var process = require('process');
var http = require('http');
var server = http.createServer(function(req, res) {
res.write("Success!");
res.end();
});
server.listen(80, null, null, function() {
console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
drop_root();
console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
});
See more details at this full reference.
You can also use the Pivot Keyword if you are using SQL 2005 or above
SELECT *
FROM @Users
PIVOT (
COUNT(Position)
FOR Position
IN (Manager, CEO, Employee)
) as p
Test Data Set
DECLARE @Users TABLE (Position VARCHAR(10))
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('CEO')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
It really is an "it depends" kinda question. Some general points:
You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.
For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.
In Fragment
public int getArgument(){
return mPage;
{
public void update(){
}
In FragmentActivity
List<Fragment> fragments = getSupportFragmentManager().getFragments();
for(Fragment f:fragments){
if((f instanceof PageFragment)&&(!f.isDetached())){
PageFragment pf = (PageFragment)f;
if(pf.getArgument()==pager.getCurrentItem())pf.update();
}
}
I'm not a sqlite user, so take this with a grain of salt; most RDBM's support the ANSI standard of the INFORMATION_SCHEMA views. If you run the following query:
SELECT *
FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'your table'
You should get a table which lists all of the columns in your specified table. IT may take some tweaking to get the output you want, but hopefully its a start.
Open a command prompt as an Administrator.
Enter slmgr /upk
and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.
Enter slmgr /cpky
and wait for this to complete. This will remove the product key from the registry if it's still there.
Enter slmgr /rearm
and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.
This should put the system back to a pre-key state.
Hope this helps you out!
The exception is raised when you try to call not callable object. Callable objects are (functions, methods, objects with __call__
)
>>> f = 1
>>> callable(f)
False
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
"BypassTraverseChecking" means that you can directly access any deep-level subdirectory even if you don't have all the intermediary access privileges to directories in between, i.e. all directories above it towards root level .
I think I've figured this one out. I imported the new WWDR Certificate that expires in 2023, but I was still getting problems building and my developer certificates were still showing the invalid issuer error.
After deleting the expired certificate from the login and System keychains, I was able to build for Distribution again.
You can create a putty session, and auto load the script on the server, when starting the session:
putty -load "sessionName"
At remote command, point to the remote script.
I usually get "Attempted to read or write protected memory" when calling the "Show" method on some WinForms. I checked and there doesn't appear anything special about those forms. I don't know why this works (maybe someone can tell me) but usually moving the code that gets executed in the "Load" event of the form to the "Shown" event fixes it for me and I never see it again.
Here is the Kotlin version of the same problem:
fun capitalizeFirstLetterOfEveryWord(text: String): String
{
if (text.isEmpty() || text.isBlank())
{
return ""
}
if (text.length == 1)
{
return Character.toUpperCase(text[0]).toString()
}
val textArray = text.split(" ")
val stringBuilder = StringBuilder()
for ((index, item) in textArray.withIndex())
{
// If item is empty string, continue to next item
if (item.isEmpty())
{
continue
}
stringBuilder
.append(Character.toUpperCase(item[0]))
// If the item has only one character then continue to next item because we have already capitalized it.
if (item.length == 1)
{
continue
}
for (i in 1 until item.length)
{
stringBuilder
.append(Character.toLowerCase(item[i]))
}
if (index < textArray.lastIndex)
{
stringBuilder
.append(" ")
}
}
return stringBuilder.toString()
}
if you need to add a date-time to your backup file name (Centos7) use the following:
/usr/bin/mysqldump -u USER -pPASSWD DBNAME | gzip > ~/backups/db.$(date +%F.%H%M%S).sql.gz
this will create the file: db.2017-11-17.231537.sql.gz
If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin
Use document.location.href to change the page location, place it in the function on a successful ajax run.
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>
You have few problems with your code like using .
for concatenation
Try this -
$(function () {
$('input').on('click', function () {
var Status = $(this).val();
$.ajax({
url: 'Ajax/StatusUpdate.php',
data: {
text: $("textarea[name=Status]").val(),
Status: Status
},
dataType : 'json'
});
});
});
@Alex's answer is good, but doesn't work when replacing an element such as an integer with a dictionary, such as update({'foo':0},{'foo':{'bar':1}})
. This update addresses it:
import collections
def update(d, u):
for k, v in u.iteritems():
if isinstance(d, collections.Mapping):
if isinstance(v, collections.Mapping):
r = update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
else:
d = {k: u[k]}
return d
update({'k1': 1}, {'k1': {'k2': {'k3': 3}}})
Also don't miss TortoiseGit... https://tortoisegit.org/
You should be able to use join
, which joins on the index as default. Given your desired result, you must use outer
as the join type.
>>> df1.join(df2, how='outer')
V1 V2
A 1/1/2012 12 15
2/1/2012 14 NaN
3/1/2012 NaN 21
B 1/1/2012 15 24
2/1/2012 8 9
C 1/1/2012 17 NaN
2/1/2012 9 NaN
D 1/1/2012 NaN 7
2/1/2012 NaN 16
Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.
You cannot change the color of colorPrimary, but you can change the theme of your application by adding a new style with a different colorPrimary color
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>
<style name="AppTheme.NewTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorOne</item>
<item name="colorPrimaryDark">@color/colorOneDark</item>
</style>
and inside the activity set theme
setTheme(R.style.AppTheme_NewTheme);
setContentView(R.layout.activity_main);
What does your routeTemplate look like for this case?
You posted this url:
/offers/40D5E19D-0CD5-4FBD-92F8-43FDBB475333/prices/
In order for this to work I would expect a routing like this in your WebApiConfig
:
routeTemplate: {controller}/{offerId}/prices/
Other assumptions are:
- your controller is called OffersController
.
- the JSON object you are passing in the request body is of type OfferPriceParameters
(not any derived type)
- you don't have any other methods on the controller that could interfere with this one (if you do, try commenting them out and see what happens)
And as Filip mentioned it would help your questions if you started accepting some answers as 'accept rate of 0%' might make people think that they are wasting their time
If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Refer this post: Replacing a fragment with another fragment inside activity group
For me non of the above worked and I had to do as below, and it worked,
sudo -E add-apt-repository ppa:openjdk-r/ppa
and then,
sudo apt-get update
sudo apt-get install openjdk-8-jdk
Reference: https://askubuntu.com/questions/644188/updating-jdk-7-to-8-unable-to-locate-package
UPDATE
In Android Studio AVD:
If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.
If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.
While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:
makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer
(^ = allow batch command-line to wrap line)
This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).
The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.
Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:
certutil -user -addstore Root MyCA.cer
makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
-sky signature ^
-ic MyCA.cer -iv MyCA.pvk ^
-sv MySPC.pvk MySPC.cer
It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).
We'll also want to convert the certificate and key into a PFX file:
pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx
If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.
signtool sign /v /f MySPC.pfx ^
/t http://timestamp.url MyExecutable.exe
(See why timestamps may matter)
If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:
signtool sign /v /n "Me" /s SPC ^
/t http://timestamp.url MyExecutable.exe
Some possible timestamp URLs for signtool /t
are:
http://timestamp.verisign.com/scripts/timstamp.dll
http://timestamp.globalsign.com/scripts/timstamp.dll
http://timestamp.comodoca.com/authenticode
For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1
). Your mileage may vary.
MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).
You'll have to use an HttpServletRequestWrapper:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
@Override
public String getHeader(String name) {
final String value = request.getParameter(name);
if (value != null) {
return value;
}
return super.getHeader(name);
}
};
chain.doFilter(wrapper, response);
}
Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames
for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.
There are a couple ways to do this.
First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:
E:\> openssl x509 -pubkey -noout -in cert.pem > pubkey.pem
If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.
openssl> x509 -pubkey -noout -in cert.pem
Output will look something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----
You can't directly get an iterator for an array.
But you can use a List, backed by your array, and get an ierator on this list. For that, your array must be an Integer array (instead of an int array):
Integer[] arr={1,2,3};
List<Integer> arrAsList = Arrays.asList(arr);
Iterator<Integer> iter = arrAsList.iterator();
Note: it is only theory. You can get an iterator like this, but I discourage you to do so. Performances are not good compared to a direct iteration on the array with the "extended for syntax".
Note 2: a list construct with this method doesn't support all methods (since the list is backed by the array which have a fixed size). For example, "remove" method of your iterator will result in an exception.
My case is a bit different, since it is not a form but to return a view. Add method ->name('route')
.
MyView.blade.php
looks like this:
<a href="{{route('admin')}}">CATEGORIES</a>
And web.php
routes file is defined like this:
Route::view('admin', 'admin.index')->name('admin');
I was facing same issue. I tried everything possible for a day, but nothing worked. The dependency which was causing problem was using lower compile sdk, target sdk and min sdk. I created library module for the project, copied all the sources and matched the sdk versions with application sdk versions. And finally it worked like a charm.
os.system() returns some unix output, not the command output. So, if there is no error then exit code written as 0.
According to the Swift 2.2 Book published by apple:
“You indicate type methods by writing the static
keyword before the method’s func keyword. Classes may also use the class
keyword to allow subclasses to override the superclass’s implementation of that method.”
Taken from Microsoft Technet.
When a browser requests a page or program on your Web site, the Web server locates the page identified by the URL and returns it to the browser. When you move a page on your Web site, you can't always correct all of the links that refer to the old URL of the page. To make sure that browsers can find the page at the new URL, you can instruct the Web server to redirect the browser to the new URL.
You can redirect requests for files in one directory to a different directory, to a different Web site, or to another file in a different directory. When the browser requests the file at the original URL, the Web server instructs the browser to request the page by using the new URL.
Important
You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".
In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.
Click the Home Directory, Virtual Directory, or Directory tab.
Under The content for this source should come from, click A redirection to a URL.
In the Redirect to box, type the URL of the destination directory or Web site. For example, to redirect all requests for files in the Catalog directory to the NewCatalog directory, type /NewCatalog.
In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.
Click the Home Directory, Virtual Directory, or Directory tab.
Under The content for this source should come from, click A redirection to a URL.
In the Redirect to box, type the URL of the destination file.
Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.
You can use wildcards and redirect variables in the destination URL to precisely control how the original URL is translated into the destination URL.
You can also use the redirect method to redirect all requests for files in a particular directory to a program. Generally, you should pass any parameters from the original URL to the program, which you can do by using redirect variables.
In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.
Click the Home Directory, Virtual Directory, or Directory tab.
Under The content for this source should come from, click A redirection to a URL.
In the Redirect to box, type the URL of the program, including any redirect variables needed to pass parameters to the program. For example, to redirect all requests for scripts in a Scripts directory to a logging program that records the requested URL and any parameters passed with the URL, type /Scripts/Logger.exe?URL=$V+PARAMS=$P. $V and $P are redirect variables.
Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.
From the threading
module documentation
There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.
There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be
join()
ed. They are never deleted, since it is impossible to detect the termination of alien threads.
So, to catch those two cases when you are not interested in keeping a list of the threads you create:
import threading as thrd
def alter_data(data, index):
data[index] *= 2
data = [0, 2, 6, 20]
for i, value in enumerate(data):
thrd.Thread(target=alter_data, args=[data, i]).start()
for thread in thrd.enumerate():
if thread.daemon:
continue
try:
thread.join()
except RuntimeError as err:
if 'cannot join current thread' in err.args[0]:
# catchs main thread
continue
else:
raise
Whereupon:
>>> print(data)
[0, 4, 12, 40]
To encode an array that contains special characters, ISO 8859-1 to UTF8. (If utf8_encode & utf8_decode is not what is working for you, this might be an option)
Everything that is in ISO-8859-1 should be converted to UTF8:
$utf8 = utf8_encode('? ??? ??? ????!'); //contains UTF8 & ISO 8859-1 characters;
$iso88591 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$data = $iso88591;
Encode should work after this:
$encoded_data = json_encode($data);
I got this same error and managed to fix it by closing Skype and running XAMP as Administrator, works perfectly now. So right click THE XAMP icon and click run as admin.
EDIT: Updated broken link as of February, the 7th, 2017.
I think noone mentioned this:
At CERN they use a full reflection system for C++:
CERN Reflex. It seems to work very well.
It probably means that your MySQL server is only listening the localhost interface.
If you have lines like this :
bind-address = 127.0.0.1
In your my.cnf
configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.
sudo service mysql restart
Of course, to do this, you must be the administrator of the server.
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
Something a little simpler and more robust is to create an Aggregate target called "CommonCryptoModuleMap" with a Run Script phase to generate the module map automatically and with the correct Xcode/SDK path:
The Run Script phase should contain this bash:
# This if-statement means we'll only run the main script if the CommonCryptoModuleMap directory doesn't exist
# Because otherwise the rest of the script causes a full recompile for anything where CommonCrypto is a dependency
# Do a "Clean Build Folder" to remove this directory and trigger the rest of the script to run
if [ -d "${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap" ]; then
echo "${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap directory already exists, so skipping the rest of the script."
exit 0
fi
mkdir -p "${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap"
cat <<EOF > "${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap/module.modulemap"
module CommonCrypto [system] {
header "${SDKROOT}/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
EOF
Using shell code and ${SDKROOT}
means you don't have to hard code the Xcode.app path which can vary system-to-system, especially if you use xcode-select
to switch to a beta version, or are building on a CI server where multiple versions are installed in non-standard locations. You also don't need to hard code the SDK so this should work for iOS, macOS, etc. You also don't need to have anything sitting in your project's source directory.
After creating this target, make your library/framework depend on it with a Target Dependencies item:
This will ensure the module map is generated before your framework is built.
macOS note: If you're supporting macOS
as well, you'll need to add macosx
to the Supported Platforms
build setting on the new aggregate target you just created, otherwise it won't put the module map in the correct Debug
derived data folder with the rest of the framework products.
Next, add the module map's parent directory, ${BUILT_PRODUCTS_DIR}/CommonCryptoModuleMap
, to the "Import Paths" build setting under the Swift section (SWIFT_INCLUDE_PATHS
):
Remember to add a $(inherited)
line if you have search paths defined at the project or xcconfig level.
That's it, you should now be able to import CommonCrypto
Update for Xcode 10
Xcode 10 now ships with a CommonCrypto module map making this workaround unnecessary. If you would like to support both Xcode 9 and 10 you can do a check in the Run Script phase to see if the module map exists or not, e.g.
COMMON_CRYPTO_DIR="${SDKROOT}/usr/include/CommonCrypto"
if [ -f "${COMMON_CRYPTO_DIR}/module.modulemap" ]
then
echo "CommonCrypto already exists, skipping"
else
# generate the module map, using the original code above
fi
Example
<div ng-controller="ExampleController">
<form name="myform">
Name: <input type="text" ng-model="user.name" /><br>
Email: <input type="email" ng-model="user.email" /><br>
</form>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
//if form is not valid then return the form.
if(!$scope.myform.$valid) {
return;
}
}]);
</script>
You can use LINQ Union method:
dir.GetFiles("*.txt").Union(dir.GetFiles("*.jpg")).ToArray();
The measurements are nice, but you are going to get significantly different results depending on what you're doing exactly in your inner loop. Measure your own situation. If you're using multi-threading, that alone is a non-trivial activity.
an example
$ echo "something" | mailx -s "subject" [email protected]
to send attachment
$ uuencode file file | mailx -s "subject" [email protected]
and to send attachment AND write the message body
$ (echo "something\n" ; uuencode file file) | mailx -s "subject" [email protected]
You can use a simple regex like this:
public static string StripHTML(string input)
{
return Regex.Replace(input, "<.*?>", String.Empty);
}
Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)
Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?
On OSX 10.8 and on, the control for MySQL is available from the System Configs. Open System Preferences, click on Mysql (usually on the very bottom) and start/stop the service from that pane. https://dev.mysql.com/doc/refman/5.6/en/osx-installation-launchd.html
The plist file is now under /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
In addition to what Brian is suggesting you could use PIL's verify method to check if the file is broken.
im.verify()
Attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. This method only works on a newly opened image; if the image has already been loaded, the result is undefined. Also, if you need to load the image after using this method, you must reopen the image file. Attributes
Do this by either going to my computer and then right clicking the background for the context menu > "properties". On the left side open "advanced system settings" or just search for "env..." in start menu ([Win]+[s] keys).
Then click on environment variables
If you struggle with this step read this explanation.
D:\path\to\anaconda3
D:\path\to\anaconda3\Scripts
D:\path\to\anaconda3\Library\bin
D:\path\to\anaconda3
should be the folder where you have installed anaconda
Click [OK] on all opened windows.
If you did everything correctly, you can test a conda
command by opening a new powershell window.
conda --version
This should output something like: conda 4.8.2
Answer for macOS 11 (Big Sur) in 2021
After installing Anaconda, run:
source /opt/anaconda3/bin/activate
conda init zsh
then close and reopen the Terminal window. The shell prompt should have a (base)
prefix.
NOTE: I found many articles online saying to update the PATH variable, but Anaconda actually recommends against doing so and running the two commands above instead, which they state in their documentation.
The fundamental difference between include
and import
is that you must use import
to refer to declarations or definitions that are in a different target namespace and you must use include
to refer to declarations or definitions that are (or will be) in the same target namespace.
Source: https://web.archive.org/web/20070804031046/http://xsd.stylusstudio.com/2002Jun/post08016.htm
I find jackson fasterxml
is one good choice to serializing/deserializing
bean with XML.
You have an incompatibility between the version of ASM required by Hibernate (asm-1.5.3.jar) and the one required by Spring. But, actually, I wonder why you have asm-2.2.3.jar on your classpath (ASM is bundled in spring.jar and spring-core.jar to avoid such problems AFAIK). See HHH-2222.
Just do this:
private void setImg(ImageView mImageView, Bitmap bitmap) {
Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);
mImageView.setDrawable(mDrawable);
}
That is because you are only checking the current checkbox.
Change it to
function checkUncheck() {
$('.pChk').click(function() {
if ( $('.pChk:checked').length > 0) {
$("#ProjectListButton").show();
} else {
$("#ProjectListButton").hide();
}
});
}
to check if any of the checkboxes is checked (lots of checks in this line..).
reference: http://api.jquery.com/checked-selector/
In my opinion, the easiest way to do is adding padding to your tag.
td {
padding: 10px 0
}
Hope this will help you! Cheer!
"But the thing is I also want to be able to add textboxes etc in this popup window thru the form designer."
It's unclear from your description at what stage in the development process you're in. If you haven't already figured it out, to create a new Form you click on Project --> Add Windows Form, then type in a name for the form and hit the "Add" button. Now you can add controls to your form as you'd expect.
When it comes time to display it, follow the advice of the other posts to create an instance and call Show() or ShowDialog() as appropriate.
This question and answer helped me solve a specific problem with signing up new users in Parse.
Because the signUp( attrs, options ) function uses local storage to persist the session, if a user is in private browsing mode it throws the "QuotaExceededError: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota." exception and the success/error functions are never called.
In my case, because the error function is never called it initially appeared to be an issue with firing the click event on the submit or the redirect defined on success of sign up.
Including a warning for users resolved the issue.
Parse Javascript SDK Reference https://parse.com/docs/js/api/classes/Parse.User.html#methods_signUp
Signs up a new user with a username (or email) and password. This will create a new Parse.User on the server, and also persist the session in localStorage so that you can access the user using {@link #current}.
For free-dom:
import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
globkeys = globals().keys()
globkeys.append('globkeys') # because name 'globkeys' is now also in globals()
print 'globkeys==',globkeys
print
print "globals().keys()==",globals().keys()
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
del i
newnames = [ x for x in globals().keys() if x not in globkeys ]
print
print 'newnames==',newnames
print
print "globals().keys()==",globals().keys()
print
print '\n'.join(repr((u,globals()[u])) for u in newnames)
Result
globkeys== ['__builtins__', 'alphabet', 'random', '__package__', '__name__', '__doc__', 'globkeys']
globals().keys()== ['__builtins__', 'alphabet', 'random', '__package__', '__name__', 'globkeys', '__doc__']
newnames== ['fztkebyrdwcigsmulnoaph', 'umkfcvztleoij', 'kbutmzfgpcdqanrivwsxly', 'lxzmaysuornvdpjqfetbchgik', 'wznptbyermclfdghqxjvki', 'lwg', 'vsolxgkz', 'yobtlkqh']
globals().keys()== ['fztkebyrdwcigsmulnoaph', 'umkfcvztleoij', 'newnames', 'kbutmzfgpcdqanrivwsxly', '__builtins__', 'alphabet', 'random', 'lxzmaysuornvdpjqfetbchgik', '__package__', 'wznptbyermclfdghqxjvki', 'lwg', 'x', 'vsolxgkz', '__name__', 'globkeys', '__doc__', 'yobtlkqh']
('fztkebyrdwcigsmulnoaph', 't')
('umkfcvztleoij', 'p')
('kbutmzfgpcdqanrivwsxly', 'a')
('lxzmaysuornvdpjqfetbchgik', 'n')
('wznptbyermclfdghqxjvki', 't')
('lwg', 'j')
('vsolxgkz', 'w')
('yobtlkqh', 'c')
Another way:
import random
pool_of_names = []
for i in xrange(1000):
v = 'LXM'+str(random.randrange(10,100000))
if v not in globals():
pool_of_names.append(v)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
print 'globals().keys()==',globals().keys()
print
for j in xrange(8):
globals()[pool_of_names[j]] = random.choice(alphabet)
newnames = pool_of_names[0:j+1]
print
print 'globals().keys()==',globals().keys()
print
print '\n'.join(repr((u,globals()[u])) for u in newnames)
result:
globals().keys()== ['__builtins__', 'alphabet', 'random', '__package__', 'i', 'v', '__name__', '__doc__', 'pool_of_names']
globals().keys()== ['LXM7646', 'random', 'newnames', 'LXM95826', 'pool_of_names', 'LXM66380', 'alphabet', 'LXM84070', '__package__', 'LXM8644', '__doc__', 'LXM33579', '__builtins__', '__name__', 'LXM58418', 'i', 'j', 'LXM24703', 'v']
('LXM66380', 'v')
('LXM7646', 'a')
('LXM8644', 'm')
('LXM24703', 'r')
('LXM58418', 'g')
('LXM84070', 'c')
('LXM95826', 'e')
('LXM33579', 'j')
This has been possible since Java 7. The syntax for a multi-catch block is:
try {
...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
NoSuchFieldException e) {
someCode();
}
Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type.
Also note that you cannot catch both ExceptionA
and ExceptionB
in the same block if ExceptionB
is inherited, either directly or indirectly, from ExceptionA
. The compiler will complain:
Alternatives in a multi-catch statement cannot be related by subclassing
Alternative ExceptionB is a subclass of alternative ExceptionA
The fix for this is to only include the ancestor exception in the exception list, as it will also catch exceptions of the descendant type.
mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)
mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM tin3;
+----+------------+
| id | val |
+----+------------+
| 1 | 0000000012 |
| 2 | 0000000007 |
| 4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)
mysql>
mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
| 10 |
+-------------+
1 row in set (0.01 sec)
mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
| 8 |
+-------+
1 row in set (0.00 sec)
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
Perhaps this is the most complete? http://goffconcepts.com/techarticles/development/cpp/createprocess.html
Use children()
and each()
, you can optionally pass a selector to children
$('#mydiv').children('input').each(function () {
alert(this.value); // "this" is the current element in the loop
});
You could also just use the immediate child selector:
$('#mydiv > input').each(function () { /* ... */ });
I have noticed that your success function has the parameter "html", and you are trying to add "data" to your elements html()
... Change it so these both match:
$.ajax({
type:"POST",
url: "ajax.php",
data:"id="+id ,
success: function(data){
$("#response").html(data);
}
});
I am using the following script to
.
#!/bin/bash -xe
SRC_ENCODING="iso-8859-1"
DST_ENCODING="utf-8"
FILTER="*.java"
echo "Find all files that match the encoding $SRC_ENCODING and filter $FILTER"
FOUND_FILES=$(find . -iname "$FILTER" -exec file -i {} \; | grep "$SRC_ENCODING" | grep -Eo '^.*\.java')
for FILE in $FOUND_FILES ; do
ORIGINAL_FILE="$FILE.$SRC_ENCODING.bkp"
echo "Backup original file to $ORIGINAL_FILE"
mv "$FILE" "$ORIGINAL_FILE"
echo "converting $FILE from $SRC_ENCODING to $DST_ENCODING"
iconv -f "$SRC_ENCODING" -t "$DST_ENCODING" "$ORIGINAL_FILE" -o "$FILE"
done
echo "Deleting backups"
find . -iname "*.$SRC_ENCODING.bkp" -exec rm {} \;
You can simply call filter
multiple times:
query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
filter(User.lastname.like(searchVar2))
for example:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"
android:src="@drawable/icon"
/>
Add property android:scaleType="fitCenter"
and android:adjustViewBounds="true"
.
import datetime
begin = datetime.date(2008, 8, 15)
end = datetime.date(2008, 9, 15)
next_day = begin
while True:
if next_day > end:
break
print next_day
next_day += datetime.timedelta(days=1)
What are -moz- and -webkit-?
CSS properties starting with -webkit-
, -moz-
, -ms-
or -o-
are called vendor prefixes.
Why do different browsers add different prefixes for the same effect?
A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:
Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.
Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.
Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds
-ms-grid
.The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.
UPDATE AS OF THE YEAR 2016
As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.
As mentioned in this glossary about Mozilla's view on Vendor Prefix
on May 3, 2016
,
Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.
For example, just a few years ago, to set a rounded corner on a box you had to write:
-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;
But now that browsers have come to fully support this feature, you really only need the standardized version:
border-radius: 10px 5px;
Finding the right rules for all browsers
As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.
You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.
Input:
a {
column-count: 3;
column-gap: 10px;
column-fill: auto;
}
Output:
a {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
-webkit-column-gap: 10px;
-moz-column-gap: 10px;
column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-fill: auto;
column-fill: auto;
}
<div>
with some proportions
div {
position: relative;
width: 100%;
height: 100%;
}
<img>
's with their own proportions
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: auto; /* to keep proportions */
height: auto; /* to keep proportions */
max-width: 100%; /* not to stand out from div */
max-height: 100%; /* not to stand out from div */
margin: auto auto 0; /* position to bottom and center */
}
char **orderIds;
orderIds = malloc(variableNumberOfElements * sizeof(char*));
for(int i = 0; i < variableNumberOfElements; i++) {
orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
strcpy(orderIds[i], your_string[i]);
}
You can simply 'add' the arrays:
>> $a = array(1, 2, 3);
array (
0 => 1,
1 => 2,
2 => 3,
)
>> $b = array("a" => 1, "b" => 2, "c" => 3)
array (
'a' => 1,
'b' => 2,
'c' => 3,
)
>> $a + $b
array (
0 => 1,
1 => 2,
2 => 3,
'a' => 1,
'b' => 2,
'c' => 3,
)
Try this:
SELECT GETDATE(), 'Today'
UNION ALL
SELECT DATEADD(DAY, 10, GETDATE()), '10 Days Later'
UNION ALL
SELECT DATEADD(DAY, –10, GETDATE()), '10 Days Earlier'
UNION ALL
SELECT DATEADD(MONTH, 1, GETDATE()), 'Next Month'
UNION ALL
SELECT DATEADD(MONTH, –1, GETDATE()), 'Previous Month'
UNION ALL
SELECT DATEADD(YEAR, 1, GETDATE()), 'Next Year'
UNION ALL
SELECT DATEADD(YEAR, –1, GETDATE()), 'Previous Year'
Result Set:
———————– —————
2011-05-20 21:11:42.390 Today
2011-05-30 21:11:42.390 10 Days Later
2011-05-10 21:11:42.390 10 Days Earlier
2011-06-20 21:11:42.390 Next Month
2011-04-20 21:11:42.390 Previous Month
2012-05-20 21:11:42.390 Next Year
2010-05-20 21:11:42.390 Previous Year
I had the same issue in trying to start the server and followed the "checked" solution. But still had the problem. The issue was the my /etc/my.cnf file was not pointing to my designated datadir as defined when I executed the mysql_install_db with --datadir defined. Once I updated this, the server started correctly.
From Increase MySQL connection limit:-
MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:
For MySQL 3.x:
# vi /etc/my.cnf
set-variable = max_connections = 250
For MySQL 4.x and 5.x:
# vi /etc/my.cnf
max_connections = 250
Restart MySQL once you’ve made the changes and verify with:
echo "show variables like 'max_connections';" | mysql
EDIT:-(From comments)
The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
The pattern you want is something like (see it on rubular.com):
^[a-zA-Z0-9_.-]*$
Explanation:
^
is the beginning of the line anchor$
is the end of the line anchor[...]
is a character class definition*
is "zero-or-more" repetitionNote that the literal dash -
is the last character in the character class definition, otherwise it has a different meaning (i.e. range). The .
also has a different meaning outside character class definitions, but inside, it's just a literal .
Here's a snippet to show how you can use this pattern:
<?php
$arr = array(
'screen123.css',
'screen-new-file.css',
'screen_new.js',
'screen new file.css'
);
foreach ($arr as $s) {
if (preg_match('/^[\w.-]*$/', $s)) {
print "$s is a match\n";
} else {
print "$s is NO match!!!\n";
};
}
?>
The above prints (as seen on ideone.com):
screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!
Note that the pattern is slightly different, using \w
instead. This is the character class for "word character".
This seems to follow your specification, but note that this will match things like .....
, etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.
The above regex also matches the empty string. If you need at least one character, then use +
(one-or-more) instead of *
(zero-or-more) for repetition.
In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.
As you stated, according to the jqGrid documentation for getCell and getRowData:
Do not use this method when you editing the row or cell. This will return the cell content and not the actual value of the input element
Since neither of these methods will return your data directly, you would have to use them to return the cell content itself and then parse it, perhaps using jQuery. It would be nice if a future version of jqGrid could provide a means to do some of this parsing itself, and/or provide an API to make it more straightforward. But on the other hand is this really a use case that comes up that often?
Alternatively, if you can explain your original problem in more detail there may be other options.
How about:
if (($key = array_search($id, $items)) !== false) unset($items[$key]);
or for multiple values:
while(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
This would prevent key loss as well, which is a side effect of array_flip()
.
This is a much more fool proof method.
VirtualPathUtility.ToAbsolute("~/");
You could try out the following code snippet:
private Point CenterOfMenuPanel<T>(T control, int height=0) where T:Control {
Point center = new Point(
MenuPanel.Size.Width / 2 - control.Width * 2,
height != 0 ? height : MenuPanel.Size.Height / 2 - control.Height / 2);
return center;
}
It's Really Center
If you are using a Toolbar as the ActionBar,
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
then just use the layout_height of the toolbar.
int actionBarHeight = toolbar.getLayoutParams().height;
Just incase anybody is interested in a pure css solution for this. The following code overlays a transparent div over the map, and moves the transparent div behind the map when it is clicked. The overlay prevents zooming, once clicked, and behind the map, zooming is enabled.
See my blog post Google maps toggle zoom with css for an explanation how it works, and pen codepen.io/daveybrown/pen/yVryMr for a working demo.
Disclaimer: this is mainly for learning and probably won't be the best solution for production websites.
HTML:
<div class="map-wrap small-11 medium-8 small-centered columns">
<input id="map-input" type="checkbox" />
<label class="map-overlay" for="map-input" class="label" onclick=""></label>
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d19867.208601651986!2d-0.17101002911118332!3d51.50585742500925!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2suk!4v1482355389969"></iframe>
</div>
CSS:
.map-wrap {
position: relative;
overflow: hidden;
height: 180px;
margin-bottom: 10px;
}
#map-input {
opacity: 0;
}
.map-overlay {
display: block;
content: '';
position: absolute;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
overflow: hidden;
z-index: 2;
}
#map-input[type=checkbox]:checked ~ iframe {
z-index: 3;
}
#map-input[type=checkbox]:checked ~ .map-overlay {
position: fixed;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
}
iframe {
position: absolute;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
z-index: 1;
border: none;
}
Bootstrap default "contextual backgrounds" helper classes to change the background color:
.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger
If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below
.bg-pink
{
background-color: #CE6F9E;
}
Minimal runnable example with disassembly analysis
As usual, I like to see some disassembly to get a better understanding of what is going on.
In this case, the insight we obtain is that if a variable is optimized to be stored only in a register rather than the stack, and then the register it was in gets overwritten, then it shows as <optimized out>
as mentioned by R..
Of course, this can only happen if the variable in question is not needed anymore, otherwise the program would lose its value. Therefore it tends to happen that at the start of the function you can see the variable value, but then at the end it becomes <optimized out>
.
One typical case which we often are interested in of this is that of the function arguments themselves, since these are:
This understanding actually has a concrete application: when using reverse debugging, you might be able to recover the value of variables of interest simply by stepping back to their last point of usage: How do I view the value of an <optimized out> variable in C++?
main.c
#include <stdio.h>
int __attribute__((noinline)) f3(int i) {
return i + 1;
}
int __attribute__((noinline)) f2(int i) {
return f3(i) + 1;
}
int __attribute__((noinline)) f1(int i) {
int j = 1, k = 2, l = 3;
i += 1;
j += f2(i);
k += f2(j);
l += f2(k);
return l;
}
int main(int argc, char *argv[]) {
printf("%d\n", f1(argc));
return 0;
}
Compile and run:
gcc -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
gdb -q -nh main.out
Then inside GDB, we have the following session:
Breakpoint 1, f1 (i=1) at main.c:13
13 i += 1;
(gdb) disas
Dump of assembler code for function f1:
=> 0x00005555555546c0 <+0>: add $0x1,%edi
0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
0x00005555555546cb <+11>: callq 0x5555555546b0 <f2>
0x00005555555546d0 <+16>: lea 0x2(%rax),%edi
0x00005555555546d3 <+19>: callq 0x5555555546b0 <f2>
0x00005555555546d8 <+24>: add $0x3,%eax
0x00005555555546db <+27>: retq
End of assembler dump.
(gdb) p i
$1 = 1
(gdb) p j
$2 = 1
(gdb) n
14 j += f2(i);
(gdb) disas
Dump of assembler code for function f1:
0x00005555555546c0 <+0>: add $0x1,%edi
=> 0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
0x00005555555546cb <+11>: callq 0x5555555546b0 <f2>
0x00005555555546d0 <+16>: lea 0x2(%rax),%edi
0x00005555555546d3 <+19>: callq 0x5555555546b0 <f2>
0x00005555555546d8 <+24>: add $0x3,%eax
0x00005555555546db <+27>: retq
End of assembler dump.
(gdb) p i
$3 = 2
(gdb) p j
$4 = 1
(gdb) n
15 k += f2(j);
(gdb) disas
Dump of assembler code for function f1:
0x00005555555546c0 <+0>: add $0x1,%edi
0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
=> 0x00005555555546cb <+11>: callq 0x5555555546b0 <f2>
0x00005555555546d0 <+16>: lea 0x2(%rax),%edi
0x00005555555546d3 <+19>: callq 0x5555555546b0 <f2>
0x00005555555546d8 <+24>: add $0x3,%eax
0x00005555555546db <+27>: retq
End of assembler dump.
(gdb) p i
$5 = <optimized out>
(gdb) p j
$6 = 5
(gdb) n
16 l += f2(k);
(gdb) disas
Dump of assembler code for function f1:
0x00005555555546c0 <+0>: add $0x1,%edi
0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
0x00005555555546cb <+11>: callq 0x5555555546b0 <f2>
0x00005555555546d0 <+16>: lea 0x2(%rax),%edi
=> 0x00005555555546d3 <+19>: callq 0x5555555546b0 <f2>
0x00005555555546d8 <+24>: add $0x3,%eax
0x00005555555546db <+27>: retq
End of assembler dump.
(gdb) p i
$7 = <optimized out>
(gdb) p j
$8 = <optimized out>
To understand what is going on, remember from the x86 Linux calling convention: What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 you should know that:
From this we deduce that:
add $0x1,%edi
corresponds to the:
i += 1;
since i
is the first argument of f1
, and therefore stored in RDI.
Now, while we were at both:
i += 1;
j += f2(i);
the value of RDI hadn't been modified, and therefore GDB could just query it at anytime in those lines.
However, as soon as the f2
call is made:
i
is not needed anymore in the programlea 0x1(%rax),%edi
does EDI = j + RAX + 1
, which both:
j = 1
f2
call to RDI = j
Therefore, when the following line is reached:
k += f2(j);
both of the following instructions have/may have modified RDI, which is the only place i
was being stored (f2
may use it as a scratch register, and lea
definitely set it to RAX + 1):
0x00005555555546c3 <+3>: callq 0x5555555546b0 <f2>
0x00005555555546c8 <+8>: lea 0x1(%rax),%edi
and so RDI does not contain the value of i
anymore. In fact, the value of i
was completely lost! Therefore the only possible outcome is:
$3 = <optimized out>
A similar thing happens to the value of j
, although j
only becomes unnecessary one line later afer the call to k += f2(j);
.
Thinking about j
also gives us some insight on how smart GDB is. Notably, at i += 1;
, the value of j
had not yet materialized in any register or memory address, and GDB must have known it based solely on debug information metadata.
-O0
analysis
If we use -O0
instead of -O3
for compilation:
gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
then the disassembly would look like:
11 int __attribute__((noinline)) f1(int i) {
=> 0x0000555555554673 <+0>: 55 push %rbp
0x0000555555554674 <+1>: 48 89 e5 mov %rsp,%rbp
0x0000555555554677 <+4>: 48 83 ec 18 sub $0x18,%rsp
0x000055555555467b <+8>: 89 7d ec mov %edi,-0x14(%rbp)
12 int j = 1, k = 2, l = 3;
0x000055555555467e <+11>: c7 45 f4 01 00 00 00 movl $0x1,-0xc(%rbp)
0x0000555555554685 <+18>: c7 45 f8 02 00 00 00 movl $0x2,-0x8(%rbp)
0x000055555555468c <+25>: c7 45 fc 03 00 00 00 movl $0x3,-0x4(%rbp)
13 i += 1;
0x0000555555554693 <+32>: 83 45 ec 01 addl $0x1,-0x14(%rbp)
14 j += f2(i);
0x0000555555554697 <+36>: 8b 45 ec mov -0x14(%rbp),%eax
0x000055555555469a <+39>: 89 c7 mov %eax,%edi
0x000055555555469c <+41>: e8 b8 ff ff ff callq 0x555555554659 <f2>
0x00005555555546a1 <+46>: 01 45 f4 add %eax,-0xc(%rbp)
15 k += f2(j);
0x00005555555546a4 <+49>: 8b 45 f4 mov -0xc(%rbp),%eax
0x00005555555546a7 <+52>: 89 c7 mov %eax,%edi
0x00005555555546a9 <+54>: e8 ab ff ff ff callq 0x555555554659 <f2>
0x00005555555546ae <+59>: 01 45 f8 add %eax,-0x8(%rbp)
16 l += f2(k);
0x00005555555546b1 <+62>: 8b 45 f8 mov -0x8(%rbp),%eax
0x00005555555546b4 <+65>: 89 c7 mov %eax,%edi
0x00005555555546b6 <+67>: e8 9e ff ff ff callq 0x555555554659 <f2>
0x00005555555546bb <+72>: 01 45 fc add %eax,-0x4(%rbp)
17 return l;
0x00005555555546be <+75>: 8b 45 fc mov -0x4(%rbp),%eax
18 }
0x00005555555546c1 <+78>: c9 leaveq
0x00005555555546c2 <+79>: c3 retq
From this horrendous disassembly, we see that the value of RDI is moved to the stack at the very start of program execution at:
mov %edi,-0x14(%rbp)
and it then gets retrieved from memory into registers whenever needed, e.g. at:
14 j += f2(i);
0x0000555555554697 <+36>: 8b 45 ec mov -0x14(%rbp),%eax
0x000055555555469a <+39>: 89 c7 mov %eax,%edi
0x000055555555469c <+41>: e8 b8 ff ff ff callq 0x555555554659 <f2>
0x00005555555546a1 <+46>: 01 45 f4 add %eax,-0xc(%rbp)
The same basically happens to j
which gets immediately pushed to the stack when when it is initialized:
0x000055555555467e <+11>: c7 45 f4 01 00 00 00 movl $0x1,-0xc(%rbp)
Therefore, it is easy for GDB to find the values of those variables at any time: they are always present in memory!
This also gives us some insight on why it is not possible to avoid <optimized out>
in optimized code: since the number of registers is limited, the only way to do that would be to actually push unneeded registers to memory, which would partly defeat the benefit of -O3
.
Extend the lifetime of i
If we edited f1
to return l + i
as in:
int __attribute__((noinline)) f1(int i) {
int j = 1, k = 2, l = 3;
i += 1;
j += f2(i);
k += f2(j);
l += f2(k);
return l + i;
}
then we observe that this effectively extends the visibility of i
until the end of the function.
This is because with this we force GCC to use an extra variable to keep i
around until the end:
0x00005555555546c0 <+0>: lea 0x1(%rdi),%edx
0x00005555555546c3 <+3>: mov %edx,%edi
0x00005555555546c5 <+5>: callq 0x5555555546b0 <f2>
0x00005555555546ca <+10>: lea 0x1(%rax),%edi
0x00005555555546cd <+13>: callq 0x5555555546b0 <f2>
0x00005555555546d2 <+18>: lea 0x2(%rax),%edi
0x00005555555546d5 <+21>: callq 0x5555555546b0 <f2>
0x00005555555546da <+26>: lea 0x3(%rdx,%rax,1),%eax
0x00005555555546de <+30>: retq
which the compiler does by storing i += i
in RDX at the very first instruction.
Tested in Ubuntu 18.04, GCC 7.4.0, GDB 8.1.0.
Here is the code snippet I found:
var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();
Worth mentioning that there are many different solutions which offer two way binding and play really nicely.
I have had a pleasant experience with this model binder - https://github.com/theironcook/Backbone.ModelBinder. which gives sensible defaults yet a lot of custom jquery selector mapping of model attributes to input elements.
There is a more extended list of backbone extensions/plugins on github
<-
does assignment in the current environment.
When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.
In most cases <<-
will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.
This might illustrate what is going on.
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
bar <- "in baz - before <<-"
bar <<- "in baz - after <<-"
print(bar)
}
print(bar)
baz()
print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
The first time we print bar we haven't called foo
yet so it should still be global - this makes sense. The second time we print it's inside of foo
before calling baz
so the value "in foo" makes sense. The following is where we see what <<-
is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-
. This is because <<-
doesn't look in the current environment (unless you're in the global environment in which case <<-
acts like <-
). So inside of baz
the value of bar stays as "in baz - before <<-". Once we call baz
the copy of bar inside of foo
gets changed to "in baz" but as we can see the global bar
is unchanged. This is because the copy of bar
that is defined inside of foo
is in the parent environment when we created baz
so this is the first copy of bar
that <<-
sees and thus the copy it assigns to. So <<-
isn't just directly assigning to the global environment.
<<-
is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.
Now I change the <<-
to an assign statement and we can see what effect that has:
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
assign("bar", "in baz", envir = .GlobalEnv)
}
print(bar)
baz()
print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
So both times we print bar inside of foo
the value is "in foo" even after calling baz
. This is because assign
never even considered the copy of bar
inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.
Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local
function.
bar <- "global"
# local will create a new environment for us to play in
local({
bar <- "local"
print(bar)
})
#[1] "local"
bar
#[1] "global"
Thanks to Ali Tokmen answer. I managed to force delete the specific local dependency with the following command:
mvn dependency:purge-local-repository -DmanualInclude=com.skyfish:utils
With this, it removes utils
from my .m2/repository and it always re-download the utils
JAR dependency when I run mvn clean install
.