If you want to refresh previous activity, this solution should work:
In previous activity where you want to refresh:
@Override
public void onRestart()
{
super.onRestart();
// do some stuff here
}
A similar question was asked, but it didn't ask about statics.
A static variable is basically a global variable, even if you cannot access it globally. Usually there is an address for it that is in the executable itself. There is only one copy for the entire program. No matter how many times you go into a function call (or class) (and in how many threads!) the variable is referring to the same memory location.
The heap is a bunch of memory that can be used dynamically. If you want 4kb for an object then the dynamic allocator will look through its list of free space in the heap, pick out a 4kb chunk, and give it to you. Generally, the dynamic memory allocator (malloc, new, et c.) starts at the end of memory and works backwards.
Explaining how a stack grows and shrinks is a bit outside the scope of this answer, but suffice to say you always add and remove from the end only. Stacks usually start high and grow down to lower addresses. You run out of memory when the stack meets the dynamic allocator somewhere in the middle (but refer to physical versus virtual memory and fragmentation). Multiple threads will require multiple stacks (the process generally reserves a minimum size for the stack).
Statics/globals are useful for memory that you know you will always need and you know that you don't ever want to deallocate. (By the way, embedded environments may be thought of as having only static memory... the stack and heap are part of a known address space shared by a third memory type: the program code. Programs will often do dynamic allocation out of their static memory when they need things like linked lists. But regardless, the static memory itself (the buffer) is not itself "allocated", but rather other objects are allocated out of the memory held by the buffer for this purpose. You can do this in non-embedded as well, and console games will frequently eschew the built in dynamic memory mechanisms in favor of tightly controlling the allocation process by using buffers of preset sizes for all allocations.)
Stack variables are useful for when you know that as long as the function is in scope (on the stack somewhere), you will want the variables to remain. Stacks are nice for variables that you need for the code where they are located, but which isn't needed outside that code. They are also really nice for when you are accessing a resource, like a file, and want the resource to automatically go away when you leave that code.
Heap allocations (dynamically allocated memory) is useful when you want to be more flexible than the above. Frequently, a function gets called to respond to an event (the user clicks the "create box" button). The proper response may require allocating a new object (a new Box object) that should stick around long after the function is exited, so it can't be on the stack. But you don't know how many boxes you would want at the start of the program, so it can't be a static.
I've heard a lot lately about how great Garbage Collectors are, so maybe a bit of a dissenting voice would be helpful.
Garbage Collection is a wonderful mechanism for when performance is not a huge issue. I hear GCs are getting better and more sophisticated, but the fact is, you may be forced to accept a performance penalty (depending upon use case). And if you're lazy, it still may not work properly. At the best of times, Garbage Collectors realize that your memory goes away when it realizes that there are no more references to it (see reference counting). But, if you have an object that refers to itself (possibly by referring to another object which refers back), then reference counting alone will not indicate that the memory can be deleted. In this case, the GC needs to look at the entire reference soup and figure out if there are any islands that are only referred to by themselves. Offhand, I'd guess that to be an O(n^2) operation, but whatever it is, it can get bad if you are at all concerned with performance. (Edit: Martin B points out that it is O(n) for reasonably efficient algorithms. That is still O(n) too much if you are concerned with performance and can deallocate in constant time without garbage collection.)
Personally, when I hear people say that C++ doesn't have garbage collection, my mind tags that as a feature of C++, but I'm probably in the minority. Probably the hardest thing for people to learn about programming in C and C++ are pointers and how to correctly handle their dynamic memory allocations. Some other languages, like Python, would be horrible without GC, so I think it comes down to what you want out of a language. If you want dependable performance, then C++ without garbage collection is the only thing this side of Fortran that I can think of. If you want ease of use and training wheels (to save you from crashing without requiring that you learn "proper" memory management), pick something with a GC. Even if you know how to manage memory well, it will save you time which you can spend optimizing other code. There really isn't much of a performance penalty anymore, but if you really need dependable performance (and the ability to know exactly what is going on, when, under the covers) then I'd stick with C++. There is a reason that every major game engine that I've ever heard of is in C++ (if not C or assembly). Python, et al are fine for scripting, but not the main game engine.
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
<input
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||
event.charCode == 0 || event.charCode == 46">
Both are used to send some data and receive some response using that data.
GET: Get information stored in the server. (i.e. search, tweet, person information). If you want to send information then get request send request using process.php?name=subroto
So it basically sends information through url. Url cannot handle more than 2036 char. So for blog post can you remember it is not possible?
POST: Post do same thing as GET. User registration, User login, Big data send, Blog Post. If you need to send secure information then use post or for big data as it not go through url.
AJAX: $.get()
and $.post()
contain features that are subsets of $.ajax()
. It has more configuration.
$.get ()
method, which is a kind of shorthand for $.ajax()
. When using $.get ()
, instead of passing in an object, you pass in arguments. At minimum, you’ll need the first two arguments, which are the URL of the file you want to retrieve (eg. test.txt) and a success callback.
return
returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:
lst = defineAList()
useTheList(lst)
Returning list
from inside defineAList
doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []
. Inside defineAList
, you create a new list and return it; this list has no relationship to the one you defined with list = []
at the beginning.
Incidentally, I changed your variable name from list
to lst
. It's not a good idea to use list
as a variable name because that is already the name of a built-in Python type. If you make your own variable called list
, you won't be able to access the builtin one anymore.
The simplest Hello World example...
$hello = "Hello World"
$hello | Out-File c:\debug.txt
From python tutorial:
Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.
So it is safe to use x[:100]
.
If you are using spring with application.yml the following will work for you
spring:
datasource:
url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar
The solution indicated by Guannan Shen has one drawback that usually goes unnoticed.
When you run sudo R
in order to run install.packages()
as superuser, the directories in which you install the library end up belonging to root
user, a.k.a., the superuser.
So, next time you need to update your libraries, you will not remember that you ran sudo
, therefore leaving root
as the owner of the files and directories; that eventually causes the error when trying to move files, because no one can overwrite root
but themself.
That can be averted by running
sudo chown -R yourusername:yourusername *
in the directory lib
that contains your local libraries, replacing yourusername
by the adequated value in your installation. Then you try installing once again.
For test navegation on Express
:
const request = require('supertest');
const server = require('../bin/www');
describe('navegation', () => {
it('login page', function(done) {
this.timeout(4000);
const timeOut = setTimeout(done, 3500);
request(server)
.get('/login')
.expect(200)
.then(res => {
res.text.should.include('Login');
clearTimeout(timeOut);
done();
})
.catch(err => {
console.log(this.test.fullTitle(), err);
clearTimeout(timeOut);
done(err);
});
});
});
In the example the test time is 4000 (4s).
Note: setTimeout(done, 3500)
is minor for than done
is called within the time of the test but clearTimeout(timeOut)
it avoid than used all these time.
I use ui-grid - v3.0.0-rc.20
because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize
module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if
is optional to wait until your data is set before rendering.
angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
..._x000D_
_x000D_
$scope.gridData = {_x000D_
rowHeight: 30, // set row height, this is default size_x000D_
..._x000D_
};_x000D_
_x000D_
..._x000D_
_x000D_
$scope.getTableHeight = function() {_x000D_
var rowHeight = 30; // your row height_x000D_
var headerHeight = 30; // your header height_x000D_
return {_x000D_
height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"_x000D_
};_x000D_
};_x000D_
_x000D_
...
_x000D_
<div ui-if="gridData.data.length>0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>
_x000D_
Here is the clear working example:
//creating new array
var custom_arr1 = [];
//storing value in array
custom_arr1.push("test");
custom_arr1.push("test1");
alert(custom_arr1);
//output will be test,test1
Comparing Java 7 and C# 3
(Some features of Java 7 aren't mentioned here, but the using
statement advantage of all versions of C# over Java 1-6 has been removed.)
Not all of your summary is correct:
Beyond that (and what's in your summary already):
List<byte>
as a byte[]
backing it, rather than an array of boxed bytes.)ref
and out
for passing parameters by referenceThis is not exhaustive, but it covers everything I can think of off-hand.
Basically one needs to create a custom background for a spinner. It should be something like this:
spinner_background.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item>
<color
android:color="@android:color/white"/>
</item>
<item>
<bitmap
android:gravity="center_vertical|right"
android:src="@drawable/ic_arrow_drop_down_black_24dp"/>
</item>
</layer-list>
</item>
</selector>
Then create a custom style for your spinner, where you specify the above selector as background:
<style name="Widget.App.Spinner" parent="@style/Widget.AppCompat.Spinner">
<item name="overlapAnchor">true</item>
<item name="android:background">@drawable/spinner_background</item>
</style>
And finally in your app theme you should override two attributes if you want it to be applied all across your app:
<item name="spinnerStyle">@style/Widget.App.Spinner</item>
<item name="android:spinnerStyle">@style/Widget.App.Spinner</item>
And that's pretty much it.
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
source ~/.bash_profile
export ANDROID_HOME=/YOUR_PATH_TO/android-sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
Putting a whole array into one localStorage entry is very inefficient: the whole thing needs to be re-encoded every time you add something to the array or change one entry.
An alternative is to use http://rhaboo.org which stores any JS object, however deeply nested, using a separate localStorage entry for each terminal value. Arrays are restored much more faithfully, including non-numeric properties and various types of sparseness, object prototypes/constructors are restored in standard cases and the API is ludicrously simple:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
BTW, I wrote it.
I'm not allowed to comment, so regarding Shane's answer, keep in mind that
wp_localize_scripts()
must be hooked to wp or admin enqueue scripts. So a good example would be as follows:
function local() {
wp_localize_script( 'js-file-handle', 'ajax', array(
'url' => admin_url( 'admin-ajax.php' )
) );
}
add_action('admin_enqueue_scripts', 'local');
add_action('wp_enqueue_scripts', 'local');`
The size of a pointer is the size required by your system to hold a unique memory address (since a pointer just holds the address it points to)
Bitvise has a great product called Tunnelier which can bridge FTP to SFTP. You could then use the standard FtpWebRequest in .NET.
http://www.bitvise.com/ftp-bridge
I am currently testing this for my own purposes and will update with my findings.
This idea is not ideal for unattended automation, unless you want to jump through hoops keeping the client connected as a service or something, which I accomplished by using NSSM.
I've tried CLI automation with various clients including bitvise and winscp.com. I've also tried these .net class libraries: Winscp, SSH.NET, SharpSSH, and the commercial SecureBlackBox SFTP client.
SecureBlackBox worked well, but it's very heavy-weight, can be quite expensive depending on the licensing, and I didn't agree so much with it's API.
Hands down, the best free sftp client for .NET development is winscp. I've written a few classes and extension methods to make working with it easier: Winscp.Extensions
I found another option so you can just use @Html.EditorFor() with templates:
Say I have this enum:
public enum EmailType { Pdf, Html }
I can put this code in Views/Shared/EditorTemplates/EmailType.cshtml
@model EmailType
@{
var htmlOptions = Model == EmailType.Html ? new { @checked = "checked" } : null;
var pdfOptions = Model == EmailType.Pdf ? new { @checked = "checked" } : null;
}
@Html.RadioButtonFor(x => x, EmailType.Html, htmlOptions) @EmailType.Html.ToString()
@Html.RadioButtonFor(x => x, EmailType.Pdf, pdfOptions) @EmailType.Pdf.ToString()
Now I can simply use this if I want to use it at any time:
@Html.EditorFor(x => x.EmailType)
It's much more universal this way, and easier to change I feel.
I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh
let's use imshow
:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]) # added some commas and array creation code
fig = plt.figure(figsize=(6, 3.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
In newer browsers, you could do the following:
document.querySelectorAll( ":hover" );
That'll give you a NodeList of items that the mouse is currently over in document order. The last element in the NodeList is the most specific, each preceding one should be a parent, grandparent, and so on.
I was hoping for Math.average(values), but no such luck.
values = [0,4,8,2,5,0,2,6]
average = values.sum / values.size.to_f
That's an Object and you want to count the properties of it.
Object.keys(jsonArray).length
References:
That method can't return true
. That's the point of Long.MAX_VALUE
. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE
and have literally zero reasonable uses. Just use Android's isUserAGoat
, or you may roll your own function that always returns false
.
Note that a long
in memory takes a fixed number of bytes. From Oracle:
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE
. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.
If you actually need this for something for real then use BigInteger
class.
From Java 8 you can use :
Comparator.comparingInt(Dog::getDogAge).reversed();
Both of these frameworks aim to seperate concerns - for instance, interaction with a data source (model), application logic (or turning this data into useful information) (Controller/Presenter) and display code (View). In some cases the model can also be used to turn a data source into a higher level abstraction as well. A good example of this is the MVC Storefront project.
There is a discussion here regarding the differences between MVC vs MVP.
The distinction made is that in an MVC application traditionally has the view and the controller interact with the model, but not with each other.
MVP designs have the Presenter access the model and interact with the view.
Having said that, ASP.NET MVC is by these definitions an MVP framework because the Controller accesses the Model to populate the View which is meant to have no logic (just displays the variables provided by the Controller).
To perhaps get an idea of the ASP.NET MVC distinction from MVP, check out this MIX presentation by Scott Hanselman.
I had a similar problem. As you increase the line-height the space above the text increases. It's not padding but it will affect the vertical space between content. I found that adding a -ve top margin seemed to do the trick. It had to be done for all of the different instances of line-height and it varies with font-family too. Maybe this is something which designers need to be more aware of when passing design requirements (?) So for a particular instance of font-family and line-height:
h1 {
font-family: 'Garamond Premier Pro Regular';
font-size: 24px;
color: #001230;
line-height: 29px;
margin-top: -5px; /* CORRECTION FOR LINE-HEIGHT */
}
This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.
Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:
$(function() {_x000D_
var div = $('#dynamicheight');_x000D_
var width = div.width();_x000D_
_x000D_
div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
width: 50%;_x000D_
_x000D_
/* Just for looks: */_x000D_
background-color: cornflowerblue;_x000D_
margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
var div = $('#dynamicheight');_x000D_
var width = div.width();_x000D_
_x000D_
div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
width: 50%;_x000D_
_x000D_
/* Just for looks: */_x000D_
background-color: cornflowerblue;_x000D_
margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
Now there is an official way to add "PlantUML integration" plugin to your JetBrains product.
Installation steps please refer: https://stackoverflow.com/a/53387418/5320704
It is recommended to override equals()
and hashCode()
to work with hash-based collections, including HashMap
, HashSet
, and Hashtable
, So doing this you can easily remove duplicates by initiating HashSet
object with Blog list.
List<Blog> blogList = getBlogList();
Set<Blog> noDuplication = new HashSet<Blog>(blogList);
But Thanks to Java 8 which have very cleaner version to do this as you mentioned you can not change code to add equals()
and hashCode()
Collection<Blog> uniqueBlogs = getUniqueBlogList(blogList);
private Collection<Blog> getUniqueBlogList(List<Blog> blogList) {
return blogList.stream()
.collect(Collectors.toMap(createUniqueKey(), Function.identity(), (blog1, blog2) -> blog1))
.values();
}
List<Blog> updatedBlogList = new ArrayList<>(uniqueBlogs);
Third parameter of Collectors.toMap()
is merge Function (functional interface) used to resolve collisions between values associated with the same key.
For ASP.NET 1.1, this is still due to someone posting more than 1000 form fields, but the setting must be changed in the registry rather than a config file. It should be added as a DWORD named MaxHttpCollectionKeys in the registry under
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\1.1.4322.0
for 32-bit editions of Windows, and
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\1.1.4322.0
for 64-bit editions of Windows.
Illumination in case of confusion...
def quit(self):
self.destroy()
exit()
A) destroy() stops the mainloop and kills the window, but leaves python running
B) exit() stops the whole process
Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.
You may be looking for
for _ in itertools.repeat(None, times): ...
this is THE fastest way to iterate times
times in Python.
I combined @richelectron and @user1433454 answers.
It works very well and preserves the text formatting.
<pre style="white-space: pre-wrap; word-break: keep-all;">
</pre>
You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).
A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!
But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.
DROP USER 'user'@'localhost';
The above command will drop the user from the database, however, it is Important to know if the same user is already using the database, that session will not end until the user closes that session. It is important to note that dropped user will STILL access the database and perform any operations. DROPPING THE USER DOES NOT DROP THE CURRENT USER SESSION
To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:
$('#id-of-the-button').click(function() {document.forms[0].submit()});
Which assumes you just have the one form on the page.
While all of the answers here are a really good explanation of what cors is but the direct answer to your question would be because of the following differences postman and browser.
Browser: Sends OPTIONS
call to check the server type and getting the headers before sending any new request to the API endpoint. Where it checks for Access-Control-Allow-Origin
. Taking this into account Access-Control-Allow-Origin
header just specifies which all CROSS ORIGINS are allowed, although by default browser will only allow the same origin.
Postman: Sends direct GET
, POST
, PUT
, DELETE
etc. request without checking what type of server is and getting the header Access-Control-Allow-Origin
by using OPTIONS
call to the server.
You are missing a :selected
on the selector for show()
- see the jQuery documentation for an example of how to use this.
In your case it will probably look something like this:
$('#'+$('#colorselector option:selected').val()).show();
An additional option is to go to your build folder and use the command ccmake .
This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.
The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .
There might a case where some other argline setup or plugin in pom may be overriding jacoco execution order setup.
argLine set to -javaagent:/Users/davea/.m2/repository/org/jacoco/org.jacoco.agent/0.6.2.201302030002/org.jacoco.agent-0.6.2.201302030002-runtime.jar=destfile=/Users/davea/Dropbox/workspace/myproject/target/jacoco.exec
One of the example
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<forkCount>5</forkCount>
<reuseForks>true</reuseForks>
<argLine>-Dnet.sf.ehcache.disabled=true</argLine>
</configuration>
</plugin>
After getting rid of argLine from these plugins, jacoco started to work normally.
From Tomcat Documentation
maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.
maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.
When you make the call to gcc it should say
g++ -Wall -I/home/alwin/Development/Calculator/ -L/opt/lib main.cpp -lcalc -o calculator
not -libcalc.so
I have a similar problem with auto-generated makes.
You can create a soft link from your compile directory to the library directory. Then the library becomes "local".
cd /compile/directory
ln -s /path/to/libcalc.so libcalc.so
You can set the background color of a button using the getRed function.
Let's assume you have:
Then, place the following code in the function where you want to change the background color of your UIButton
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
// This will be some red-ish color
let color = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0)
if color.getRed(&r, green: &g, blue: &b, alpha: &a){
button.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: a)
}
PEP 8 advises the first form for readability. You can find it here.
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
There are different regex engines but I think most of them will work with this:
apple|banana
gvim version: 8.2
location of .gvimrc: %userprofile%/.gvimrc
" .gvimrc
colorscheme darkblue
Which color is allows me to choose?
Find your install directory and go to the directory of colors
.
in my case is:
%PROGRAMFILES(X86)%\Vim\vim82\colors
blue.vim
darkblue.vim
slate.vim
...
README.txt
GPS does not need any kind of internet or wireless connection, but there are technologies like A-GPS that use the mobile network to shorten the time to first fix, or the initial positioning or increase the precision in situations when there is a low satellite visibility.
Android phones tend to use A-GPS. If there is no connectivity, they use pure GPS. They do not override the data network mode. If you deactivated it, the phone won't use any data connection (which is handy if you are abroad, and do not want to pay expensive data roaming).
I think I encountered the same problem as you. I addressed this problem with the following steps:
1) Go to Google Developers Console
2) Set JavaScript origins:
3) Set Redirect URIs:
Old topic, but this works:
var rl = readline.createInterface({
input : fs.createReadStream('/path/file.txt'),
output: process.stdout,
terminal: false
})
rl.on('line',function(line){
console.log(line) //or parse line
})
Simple. No need for an external module.
One more solution:
function firstOrNull(array, expr) {
for (var i = 0; i < array.length; i++) {
if (expr(array[i]))
return array[i];
}
return null;
}
Using: firstOrNull([{ a: 1, b: 2 }, { a: 3, b: 3 }], function(item) { return item.a === 3; });
This function don't executes for each element from the array (it's valuable for large arrays)
Like this?
$string = 'FirstPart SecondPart'
$a,$b = $string.split(' ')
$a
$b
For non-Windows users:
import pandas as pd
import os
os.chdir("../data_folder")
df = pd.read_csv("data.csv")
For Windows users:
import pandas as pd
df = pd.read_csv(r"C:\data_folder\data.csv")
The prefix r in location above saves time when giving the location to the pandas Dataframe.
class MyController < ApplicationController
# include your helper
include MyHelper
# or Rails helper
include ActionView::Helpers::NumberHelper
def my_action
price = number_to_currency(10000)
end
end
In Rails 5+ simply use helpers (helpers.number_to_currency(10000))
To add to Alan Wells's elaborate answer here is a quick fix
you can serve any folder in your computer with Serve
First, navigate using the command line into the folder you'd like to serve.
Then
npx i -g serve
serve
or if you'd like to test Serve without downloading it
npx serve
and that's it! You can view your files at http://localhost:5000
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
There's a complete working example here.
<html>
<title>jQuery Summing</title>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
$(document).ready(function() {
$('.calc').on('input', function() {
var t1 = document.getElementById('txt1');
var t2 = document.getElementById('txt2');
var tot=0;
if (parseInt(t1.value))
tot += parseInt(t1.value);
if (parseInt(t2.value))
tot += parseInt(t2.value);
document.getElementById('txt3').value = tot;
});
});
</script>
</head>
<body>
<input type='text' class='calc' id='txt1'>
<input type='text' class='calc' id='txt2'>
<input type='text' id='txt3' readonly>
</body>
</html>
I found that I had to use .setAttribute('crossOrigin', '')
and had to append a timestamp to the URL's query string to avoid a 304 response lacking the Access-Control-Allow-Origin
header.
This gives me
var url = 'http://lorempixel.com/g/400/200/';
var imgObj = new Image();
imgObj.src = url + '?' + new Date().getTime();
imgObj.setAttribute('crossOrigin', '');
Hai Vu answer works great, just one comment:
In case you are using the global in other module and you want to set the global dynamically, pay attention to import the other modules after you set the global variables, for example:
# settings.py
def init(arg):
global myList
myList = []
mylist.append(arg)
# subfile.py
import settings
def print():
settings.myList[0]
# main.py
import settings
settings.init("1st") # global init before used in other imported modules
# Or else they will be undefined
import subfile
subfile.print() # global usage
Had same issue with Android Studio 3.3 Canary 13.
I was able to solve it by following these steps:
When you complete these steps the module will be copied into your project again, AS will start syncing Gradle again and that succeeds without errors :-) Check your GIT status and you will see as soon as you add your module directory to GIT again that nothing has changed to your working directory. So it's purely an issue with AS that gets somehow out-of-sync...
Based my solution on this comment: https://issuetracker.google.com/issues/37008041#comment3
Problem: choose the minimum rate value given to an entity Requirements: Agency rates can be null
[MinRateValue] =
CASE
WHEN ISNULL(FitchRating.RatingValue, 100) < = ISNULL(MoodyRating.RatingValue, 99)
AND ISNULL(FitchRating.RatingValue, 100) < = ISNULL(StandardPoorsRating.RatingValue, 99)
THEN FitchgAgency.RatingAgencyName
WHEN ISNULL(MoodyRating.RatingValue, 100) < = ISNULL(StandardPoorsRating.RatingValue , 99)
THEN MoodyAgency.RatingAgencyName
ELSE ISNULL(StandardPoorsRating.RatingValue, 'N/A')
END
Inspired by this answer from Nat
In your web.config, make sure these keys exist:
<configuration>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
req
is an object containing information about the HTTP request that raised the event. In response to req
, you use res
to send back the desired HTTP response.
Those parameters can be named anything. You could change that code to this if it's more clear:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Edit:
Say you have this method:
app.get('/people.json', function(request, response) { });
The request will be an object with properties like these (just to name a few):
request.url
, which will be "/people.json"
when this particular action is triggeredrequest.method
, which will be "GET"
in this case, hence the app.get()
call.request.headers
, containing items like request.headers.accept
, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.request.query
(e.g. /people.json?foo=bar
would result in request.query.foo
containing the string "bar"
).To respond to that request, you use the response object to build your response. To expand on the people.json
example:
app.get('/people.json', function(request, response) {
// We want to set the content-type header so that the browser understands
// the content of the response.
response.contentType('application/json');
// Normally, the data is fetched from a database, but we can cheat:
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
// Since the request is for a JSON representation of the people, we
// should JSON serialize them. The built-in JSON.stringify() function
// does that.
var peopleJSON = JSON.stringify(people);
// Now, we can use the response object's send method to push that string
// of people JSON back to the browser in response to this request:
response.send(peopleJSON);
});
If you want to use a string as a variable name, you can use assign:
var1="string_name"
assign(var1, c(5,4,5,6,7))
string_name
[1] 5 4 5 6 7
Create an initializer for it:
# config/initializers/time_formats.rb
Add something like this to it:
Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"
And then use it the following way:
post.updated_at.to_s(:custom_datetime)
?? Your have to restart rails server for this to work.
Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s
if you check only null or empty then you can use the with default option for this:
<c:out default="var1 is empty or null." value="${var1}"/>
Math.Ceiling((double)list.Count() / 10);
This works great if a straight copy is in order. If the situation calls for creating new objects from templates, I usually wrap the template div in a hidden storage div and use jquery's html() in conjunction with clone() applying the following technique:
<style>
#element-storage {
display: none;
top: 0;
right: 0;
position: fixed;
width: 0;
height: 0;
}
</style>
<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){
// .. code to modify template, e.g. below:
var newHTML = "";
newHTML = oldHTML.replace("[firstname]", "Tom");
newHTML = newHTML.replace("[lastname]", "Smith");
// newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
return newHTML;
}));
</script>
<div id="element-storage">
<div id="template">
<p>Hello [firstname] [lastname]</p>
</div>
</div>
<div id="new-div">
</div>
The generic view of a loop is
for (initialization; condition; increment-decrement){}
The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.
Ok man, the only thing that worked for me was:
Change permissions of the key
chmod 400 mykey.pem
Make sure to log in using ec2-user, and the correct ec2-99... address. The ec2-99 address is at the bottom of the aws console when you're logged in and seeing your instance listed
ssh -i mykey.pem [email protected]
This question has been out here a long time, but I wanted to contribute how I usually iterate through a JSON object. In the example below, I've shown a hard-coded string that contains the JSON, but the JSON string could just as easily have come from a web service or a file.
import json
def main():
# create a simple JSON array
jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'
# change the JSON string into a JSON object
jsonObject = json.loads(jsonString)
# print the keys and values
for key in jsonObject:
value = jsonObject[key]
print("The key and value are ({}) = ({})".format(key, value))
pass
if __name__ == '__main__':
main()
First of all, it's actually not accurate to say that
x % 2 == x & 1
Simple counterexample: x = -1
. In many languages, including Java, -1 % 2 == -1
. That is, %
is not necessarily the traditional mathematical definition of modulo. Java calls it the "remainder operator", for example.
With regards to bitwise optimization, only modulo powers of two can "easily" be done in bitwise arithmetics. Generally speaking, only modulo powers of base b can "easily" be done with base b representation of numbers.
In base 10, for example, for non-negative N
, N mod 10^k
is just taking the least significant k
digits.
A good seed initialisation can be done like this
Random rnd = new Random((int)DateTime.Now.Ticks);
The ticks will be unique and the cast into a int with probably a loose of value will be OK.
Add a reference to 'Microsoft.VisualStudio.QualityTools.UnitTestFramework" NuGet packet and it should successfully build it.
Here is a basic example:
public class TestMethodPassing
{
private static void println()
{
System.out.println("Do println");
}
private static void print()
{
System.out.print("Do print");
}
private static void performTask(BasicFunctionalInterface functionalInterface)
{
functionalInterface.performTask();
}
@FunctionalInterface
interface BasicFunctionalInterface
{
void performTask();
}
public static void main(String[] arguments)
{
performTask(TestMethodPassing::println);
performTask(TestMethodPassing::print);
}
}
Output:
Do println
Do print
One option which seems to missing from the other answers (only mentioned deep down in a comment by naxa) is the following:
def foo():
string = ("line one\n" # Add \n in the string
"line two" "\n" # Add "\n" after the string
"line three\n")
This will allow proper aligning, join the lines implicitly, and still keep the line shift which, for me, is one of the reasons why I would like to use multiline strings anyway.
It doesn't require any postprocessing, but you need to manually add the \n
at any given place that you want the line to end. Either inline or as a separate string after. The latter is easier to copy-paste in.
I see some people prefer to generate sources into the target via jaxws-maven-plugin AND make this classes visible in source via build-helper-maven-plugin. As an argument for this structure
the version management system (svn/etc.) would always notice changed sources
With git it is not true. So you can just configure jaxws-maven-plugin
to put them into your sources, but not under the target folder. Next time you build your project, git will not mark these generated files as changed. Here is the simple solution with only one plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.6</version>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<packageName>som.path.generated</packageName>
<xjcArgs>
<xjcArg>-Xfluent-api</xjcArg>
</xjcArgs>
<verbose>true</verbose>
<keep>true</keep> <!--used by default-->
<sourceDestDir>${project.build.sourceDirectory}</sourceDestDir>
<wsdlDirectory>src/main/resources/META-INF/wsdl</wsdlDirectory>
<wsdlLocation>META-INF/wsdl/soap.wsdl</wsdlLocation>
</configuration>
</execution>
</executions>
</plugin>
Additionally (just to note) in this example SOAP classes are generated with Fluent API, so you can create them like:
A a = new A()
.withField1(value1)
.withField2(value2);
The other answer (to date) appear to check for substrings rather than words. Major difference.
With the help of this article, I have created this simple method:
static boolean containsWord(String mainString, String word) {
Pattern pattern = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE); // "\\b" represents any word boundary.
Matcher matcher = pattern.matcher(mainString);
return matcher.find();
}
I might misunderstand, but are you trying to delete files newly ignored or do you want to ignore new modifications to these files ? In this case, the thing is working.
If you want to delete ignored files previously commited, then use
git rm –cached `git ls-files -i –exclude-standard`
git commit -m 'clean up'
This worked for me:
SELECT EXTRACT(YEAR FROM ASOFDATE) FROM PSASOFDATE;
Today I encountered a problem with the exact same symptoms as you describe. I closed all files and restarted VS only to find out that some files disappeared from the Solution Explorer.
The following solved my problem: by selecting the current project in the Solution Explorer, a little icon Show all files
appears on the top bar. Right-clicking the file and selecting Include In Project
does the thing.
i have done the following and it worked perfectly
try {
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
File f = jfc.getSelectedFile();
Image bi = ImageIO.read(f);
image1.setText("");
image1.setIcon(new ImageIcon(bi.getScaledInstance(int width, int width, int width)));
} catch (Exception e) {
}
Once when I was interviewing for Microsoft in college, the guy asked me how to detect a cycle in a linked list.
Having discussed in class the prior week the optimal solution to the problem, I started to tell him.
He told me, "No, no, everybody gives me that solution. Give me a different one."
I argued that my solution was optimal. He said, "I know it's optimal. Give me a sub-optimal one."
At the same time, it's a pretty good problem.
Or you can use this function:
DELIMITER $$
CREATE FUNCTION BLOB2TXT (blobfield VARCHAR(255)) RETURNS longtext
DETERMINISTIC
NO SQL
BEGIN
RETURN CAST(blobfield AS CHAR(10000) CHARACTER SET utf8);
END
$$
DELIMITER ;
I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
The code would look something like this (to count user objects):
from sqlalchemy import func
session.query(func.count(User.id)).scalar()
You can do this ( where data-x has the appropriate display:xxxx set ):
<!-- TH -->
<div data-tr>
<div data-th style="width:25%">TH</div>
<div data-th style="width:50%">
<div data-table style="width:100%">
<div data-tr>
<div data-th style="width:25%">TH</div>
<div data-th style="width:25%">TH</div>
<div data-th style="width:25%">TH</div>
<div data-th style="width:25%">TH</div>
</div>
</div>
</div>
<div data-th style="width:25%">TH</div>
</div>
<!-- TD -->
<div data-tr>
<div data-td style="width:25%">TD</div>
<div data-th style="width:50%">
<div data-table style="width:100%">
<div data-tr>
<div data-td style="width:25%">TD</div>
<div data-td style="width:25%">TD</div>
<div data-td style="width:25%">TD</div>
<div data-td style="width:25%">TD</div>
</div>
<div data-tr>
...
</div>
</div>
</div>
<div data-td style="width:25%">TD</div>
</div>
It's very simple:
foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
{
dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
}
Added content of pg_env.sh to my .bashrc:
cat /opt/PostgreSQL/10/pg_env.sh
#!/bin/sh
# The script sets environment variables helpful for PostgreSQL
export PATH=/opt/PostgreSQL/10/bin:$PATH
export PGDATA=/opt/PostgreSQL/10/data
export PGDATABASE=postgres
export PGUSER=postgres
export PGPORT=5433
export PGLOCALEDIR=/opt/PostgreSQL/10/share/locale
export MANPATH=$MANPATH:/opt/PostgreSQL/10/share/man
with addition of (as per user4653174 suggestion)
export PGPASSWORD='password'
Download whatever configuration script that your browser is using.
the script would have various host:port configuration. based on the domain you want to connect , one of the host:port is selected by the borwser.
in the eclipse network setting you can try to put on of the host ports and see if that works.
worked for me.
the config script looks like,
if (isPlainHostName(host))
return "DIRECT";
else if (dnsDomainIs(host, "<***sample host name *******>"))
return "PROXY ***some ip*****; DIRECT";
else if (dnsDomainIs(host, "address.com")
|| dnsDomainIs(host, "adress2..com")
|| dnsDomainIs(host, "address3.com")
|| dnsDomainIs(host, "address4.com")
return "PROXY <***some proxyhost****>:8080";
you would need to look for the host port in the return statement.
If Java is installed on your 11G then you can do it in a java class and call it from your PL/SQL, but I am not sure that it does not require also a specific grant to call java.
Apple OSX Folder Actions allow you to automate tasks based on actions taken on a folder.
$('#list option').each(function(index){
//do stuff
console.log(index);
});
logs the index :)
a more detailed example is below.
function run_each() {_x000D_
_x000D_
var $results = $(".results");_x000D_
_x000D_
$results.empty();_x000D_
_x000D_
$results.append("==================== START 1st each ====================");_x000D_
console.log("==================== START 1st each ====================");_x000D_
_x000D_
$('#my_select option').each(function(index, value) {_x000D_
$results.append("<br>");_x000D_
// log the index_x000D_
$results.append("index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log("index: " + index);_x000D_
// logs the element_x000D_
// $results.append(value); this would actually remove the element_x000D_
$results.append("<br>");_x000D_
console.log(value);_x000D_
// logs element property_x000D_
$results.append(value.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(value.innerHTML);_x000D_
// logs element property_x000D_
$results.append(this.text);_x000D_
$results.append("<br>");_x000D_
console.log(this.text);_x000D_
// jquery_x000D_
$results.append($(this).text());_x000D_
$results.append("<br>");_x000D_
console.log($(this).text());_x000D_
_x000D_
// BEGIN just to see what would happen if nesting an .each within an .each_x000D_
$('p').each(function(index) {_x000D_
$results.append("==================== nested each");_x000D_
$results.append("<br>");_x000D_
$results.append("nested each index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log(index);_x000D_
});_x000D_
// END just to see what would happen if nesting an .each within an .each_x000D_
_x000D_
});_x000D_
_x000D_
$results.append("<br>");_x000D_
$results.append("==================== START 2nd each ====================");_x000D_
console.log("");_x000D_
console.log("==================== START 2nd each ====================");_x000D_
_x000D_
_x000D_
$('ul li').each(function(index, value) {_x000D_
$results.append("<br>");_x000D_
// log the index_x000D_
$results.append("index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log(index);_x000D_
// logs the element_x000D_
// $results.append(value); this would actually remove the element_x000D_
$results.append("<br>");_x000D_
console.log(value);_x000D_
// logs element property_x000D_
$results.append(value.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(value.innerHTML);_x000D_
// logs element property_x000D_
$results.append(this.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(this.innerHTML);_x000D_
// jquery_x000D_
$results.append($(this).text());_x000D_
$results.append("<br>");_x000D_
console.log($(this).text());_x000D_
});_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(document).on("click", ".clicker", function() {_x000D_
_x000D_
run_each();_x000D_
_x000D_
});
_x000D_
.results {_x000D_
background: #000;_x000D_
height: 150px;_x000D_
overflow: auto;_x000D_
color: lime;_x000D_
font-family: arial;_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.one,_x000D_
.two,_x000D_
.three {_x000D_
width: 33.3%;_x000D_
}_x000D_
_x000D_
.one {_x000D_
background: yellow;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.two {_x000D_
background: pink;_x000D_
}_x000D_
_x000D_
.three {_x000D_
background: darkgray;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="one">_x000D_
<select id="my_select">_x000D_
<option>apple</option>_x000D_
<option>orange</option>_x000D_
<option>pear</option>_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
<div class="two">_x000D_
<ul id="my_list">_x000D_
<li>canada</li>_x000D_
<li>america</li>_x000D_
<li>france</li>_x000D_
</ul>_x000D_
</div>_x000D_
_x000D_
<div class="three">_x000D_
<p>do</p>_x000D_
<p>re</p>_x000D_
<p>me</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<button class="clicker">run_each()</button>_x000D_
_x000D_
_x000D_
<div class="results">_x000D_
_x000D_
_x000D_
</div>
_x000D_
I know its way too old to be answered now.. but still, a small tweak to @Daniel's answer for rectifying the problem of not showing zero valued progress bar. Just draw the Progress only if the inner rectangle's width is found to be non-zero.
Thanks to all the contributers.
public class ProgressBarEx : ProgressBar
{
public ProgressBarEx()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaintBackground(PaintEventArgs pevent){}
// None... Helps control the flicker.
protected override void OnPaint(PaintEventArgs e)
{
const int inset = 2; // A single inset value to control teh sizing of the inner rect.
using (Image offscreenImage = new Bitmap(this.Width, this.Height))
{
using (Graphics offscreen = Graphics.FromImage(offscreenImage))
{
Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
if (ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawHorizontalBar(offscreen, rect);
rect.Inflate(new Size(-inset, -inset)); // Deflate inner rect.
rect.Width = (int)(rect.Width * ((double)this.Value / this.Maximum));
if (rect.Width != 0)
{
LinearGradientBrush brush = new LinearGradientBrush(rect, this.ForeColor, this.BackColor, LinearGradientMode.Vertical);
offscreen.FillRectangle(brush, inset, inset, rect.Width, rect.Height);
e.Graphics.DrawImage(offscreenImage, 0, 0);
offscreenImage.Dispose();
}
}
}
}
}
I had the same problem. I tried installing Visual Studio 2010 SP1 but it didn't worked.
Finally I get Microsoft.Web.Infrastructure.dll from the colleague. You can find the dll into your friends PC where the project is perfectly working. Try to search dll into Temp/Temporary ASP.NET Files. Go to Temp using %temp% into run window.
After getting dll into your pc, just add reference to your project and it will work.
Reformat affects the whole source code and may rebreak your lines, while Correct Indentation only affects the whitespace at the beginning of the lines.
How about this option:
docker logs containername >& logs/myFile.log
It will not redirect logs which was asked for in the question, but copy them once to a specific file.
You can read about the keyword unsigned in the C++ Reference.
There are two different types in this matter, signed and un-signed. The default for integers is signed which means that they can have negative values.
On a 32-bit system an integer is 32 Bit which means it can contain a value of ~4 billion.
And when it is signed, this means you need to split it, leaving -2 billion to +2 billion.
When it is unsigned however the value cannot contain any negative numbers, so for integers this would mean 0 to +4 billion.
There is a bit more informationa bout this on Wikipedia.
If you want to remove unique constraints from mysql database table, use alter table with drop index.
Example:
create table unique_constraints(unid int,activity_name varchar(100),CONSTRAINT activty_uqniue UNIQUE(activity_name),primary key (unid));
alter table unique_constraints drop index activty_uqniue;
Where activty_uqniue is UNIQUE constraint for activity_name column.
If your arrays are sorted, this should run in O(n), where n is min( a.length, b.length )
function intersect_1d( a, b ){
var out=[], ai=0, bi=0, acurr, bcurr, last=Number.MIN_SAFE_INTEGER;
while( ( acurr=a[ai] )!==undefined && ( bcurr=b[bi] )!==undefined ){
if( acurr < bcurr){
if( last===acurr ){
out.push( acurr );
}
last=acurr;
ai++;
}
else if( acurr > bcurr){
if( last===bcurr ){
out.push( bcurr );
}
last=bcurr;
bi++;
}
else {
out.push( acurr );
last=acurr;
ai++;
bi++;
}
}
return out;
}
Another way...
# translate long options to short
for arg
do
delim=""
case "$arg" in
--help) args="${args}-h ";;
--verbose) args="${args}-v ";;
--config) args="${args}-c ";;
# pass through anything else
*) [[ "${arg:0:1}" == "-" ]] || delim="\""
args="${args}${delim}${arg}${delim} ";;
esac
done
# reset the translated args
eval set -- $args
# now we can process with getopt
while getopts ":hvc:" opt; do
case $opt in
h) usage ;;
v) VERBOSE=true ;;
c) source $OPTARG ;;
\?) usage ;;
:)
echo "option -$OPTARG requires an argument"
usage
;;
esac
done
When you think "check to see if a in b", think hashes (in this case, sets). The fastest way is to hash the list you want to check, and then check each item in there.
This is why Joe Koberg's answer is fast: checking set intersection is very fast.
When you don't have a lot of data though, making sets can be a waste of time. So, you can make a set of the list and just check each item:
tocheck = [1,2] # items to check
a = [2,3,4] # the list
a = set(a) # convert to set (O(len(a)))
print [i for i in tocheck if i in a] # check items (O(len(tocheck)))
When the number of items you want to check is small, the difference can be negligible. But check lots of numbers against a large list...
tests:
from timeit import timeit
methods = ['''tocheck = [1,2] # items to check
a = [2,3,4] # the list
a = set(a) # convert to set (O(n))
[i for i in tocheck if i in a] # check items (O(m))''',
'''L1 = [2,3,4]
L2 = [1,2]
[i for i in L1 if i in L2]''',
'''S1 = set([2,3,4])
S2 = set([1,2])
S1.intersection(S2)''',
'''a = [1,2]
b = [2,3,4]
any(x in a for x in b)''']
for method in methods:
print timeit(method, number=10000)
print
methods = ['''tocheck = range(200,300) # items to check
a = range(2, 10000) # the list
a = set(a) # convert to set (O(n))
[i for i in tocheck if i in a] # check items (O(m))''',
'''L1 = range(2, 10000)
L2 = range(200,300)
[i for i in L1 if i in L2]''',
'''S1 = set(range(2, 10000))
S2 = set(range(200,300))
S1.intersection(S2)''',
'''a = range(200,300)
b = range(2, 10000)
any(x in a for x in b)''']
for method in methods:
print timeit(method, number=1000)
speeds:
M1: 0.0170331001282 # make one set
M2: 0.0164539813995 # list comprehension
M3: 0.0286040306091 # set intersection
M4: 0.0305438041687 # any
M1: 0.49850320816 # make one set
M2: 25.2735087872 # list comprehension
M3: 0.466138124466 # set intersection
M4: 0.668627977371 # any
The method that is consistently fast is to make one set (of the list), but the intersection works on large data sets the best!
you can do it with SVN/Tortoise git as well.
just right click on node_modules -> Tortoise git -> add to ignore list.
This will generate .gitIgnore for you and you won't find node_modules folder in staging again.
You can use a Contains
query for this:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false)
. To add an extra column with only the non-reimbursed amounts, you would use something like:
=IF(B1="No", A1, 0)
and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.
If just want to use Linq, you can override Equals and GetHashCode methods.
Product class:
public class Product
{
public string ProductName { get; set; }
public int Id { get; set; }
public override bool Equals(object obj)
{
if (!(obj is Product))
{
return false;
}
var other = (Product)obj;
return Id == other.Id;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
Main Method:
static void Main(string[] args)
{
var products = new List<Product>
{
new Product{ ProductName="Product 1",Id = 1},
new Product{ ProductName="Product 2",Id = 2},
new Product{ ProductName="Product 4",Id = 5},
new Product{ ProductName="Product 3",Id = 3},
new Product{ ProductName="Product 4",Id = 4},
new Product{ ProductName="Product 6",Id = 4},
new Product{ ProductName="Product 6",Id = 4},
};
var itemsDistinctByProductName = products.Distinct().ToList();
foreach (var product in itemsDistinctByProductName)
{
Console.WriteLine($"Product Id : {product.Id} ProductName : {product.ProductName} ");
}
Console.ReadKey();
}
In my case, for tensorflow 2.4.0, none of the previous answer works unless you install tensorflow-cpu
pip install tensorflow-cpu
I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.
Depending on what document type you want you can use XmlDocument.LoadXml
or XDocument.Load
.
Interestingly enough, building on the answer from @olefevre, one can not only do 50/50 layouts with "invisible struts", but all sorts of layouts involving powers of two.
For example, here is a layout that cuts the width into four equal parts (actually three, with weights of 1, 1, 2):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<View
android:id="@+id/strut"
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:background="#000000" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/strut" >
<View
android:id="@+id/left_strut"
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_toLeftOf="@+id/strut"
android:layout_centerHorizontal="true"
android:background="#000000" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/left_strut"
android:text="Far Left" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/left_strut"
android:text="Near Left" />
</RelativeLayout>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/strut"
android:layout_alignParentRight="true"
android:text="Right" />
</RelativeLayout>
Here is my full post with topic: PHP find difference between two datetimes
USAGE EXAMPLE
echo timeDifference('2016-05-27 02:00:00', 'Y-m-d H:i:s', '2017-08-30 00:01:59', 'Y-m-d H:i:s', false, '%a days %h hours');
#459 days 22 hours (string)
echo timeDifference('2016-05-27 02:00:00', 'Y-m-d H:i:s', '2016-05-27 07:00:00', 'Y-m-d H:i:s', true, 'hours',true);
#-5 (int)
You can get the HTML of the website with driver.getPageSource(). If the html does not change in a given interval of time this means that the page is done loading. One or two seconds should be enough. If you want to speed things up you can just compare the lenght of the two htmls. If their lenght is equal the htmls should be equal and that means the page is fully loaded. The JavaScript solution did not work for me.
I would like to suggest DBEAVER .it is based on eclipse and supports better data handling
For the second part of your question, you can also use shift
, for example:
df['t-1'] = df['t'].shift(1)
t-1
would then contain the values from t one row above.
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html
x if y else z
is the syntax for the expression you're returning for each element. Thus you need:
[ x if x%2 else x*100 for x in range(1, 10) ]
The confusion arises from the fact you're using a filter in the first example, but not in the second. In the second example you're only mapping each value to another, using a ternary-operator expression.
With a filter, you need:
[ EXP for x in seq if COND ]
Without a filter you need:
[ EXP for x in seq ]
and in your second example, the expression is a "complex" one, which happens to involve an if-else
.
in my case, I declared one static variable in .h file, like
//myClass.h
class myClass
{
static int m_nMyVar;
static void myFunc();
}
and in myClass.cpp, I tried to use this m_nMyVar. It got LINK error like:
error LNK2001: unresolved external symbol "public: static class... The link error related cpp file looks like:
//myClass.cpp
void myClass::myFunc()
{
myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}
So I add below code on the top of myClass.cpp
//myClass.cpp
int myClass::m_nMyVar; //it seems redefine m_nMyVar, but it works well
void myClass::myFunc()
{
myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}
then LNK2001 is gone.
BigDecimal offers a string constructor. You'll need to strip all commas from the number, via via an regex or String filteredString=inString.replaceAll(",","")
.
You then simply call BigDecimal myBigD=new BigDecimal(filteredString);
You can also create a NumberFormat
and call setParseBigDecimal(true)
. Then parse(
will give you a BigDecimal without worrying about manually formatting.
Yes it is Possible Will Den. we can run PHP code in tomcat server using it's own port number localhost:8080
here I'm writing some step which is so much useful for you.
How to install or run PHP on Tomcat 6 in windows
download and unzip PHP 5 to a directory, c:\php-5.2.6-Win32
- php-5.2.9-2-Win32.zip Download
download PECL 5.2.5 Win32 binaries - PECL 5.2.5 Win32 Download
rename php.ini-dist
to php.ini
in c:\php-5.2.6-Win32
Uncomment or add the line (remove semi-colon at the beginning) in php.ini
:
;extension=php_java.dll
copy php5servlet.dll
from PECL 5.2.5 to c:\php-5.2.6-Win32
copy php_java.dll
from PECL 5.2.5 to c:\php-5.2.6-Win32\ext
copy php_java.jar
from PECL 5.2.5 to tomcat\lib
create a directory named "php"
(or what ever u like) in tomcat\webapps
directory
copy phpsrvlt.jar
from PECL 5.2.5 to tomcat\webapps\php\WEB-INF\lib
Unjar or unzip phpsrvlt.jar
for unzip use winrar or winzip for unjar use : jar xfv phpsrvlt.jar
change both net\php\reflect.properties
and net\php\servlet.properties
to library=php5servlet
Recreate the jar file
-> jar cvf php5srvlt.jar net/php/.
PS: if the jar file doesnt run you have to add the Path to system variables for me I added C:\Program Files\Java\jdk1.6.0\bin; to System variables/Path
create web.xml
in tomcat\webapps\php\WEB-INF
with this content:
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">
<servlet>
<servlet-name>php</servlet-name>
<servlet-class>net.php.servlet</servlet-class>
</servlet>
<servlet>
<servlet-name>php-formatter</servlet-name>
<servlet-class>net.php.formatter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>php</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>php-formatter</servlet-name>
<url-pattern>*.phps</url-pattern>
</servlet-mapping>
</web-app>
Add PHP path( c:\php-5.2.6-Win32
) to your System or User Path in Windows enironment (Hint: Right-click and select Properties from My Computer
create test.php
for testing under tomcat\webapps\php
like
Restart tomcat
browse localhost:8080/php/test.php
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
This might not be very applicable to others, but my problem was that the changes I made was NOT saved yet! Press CMD + S
and save your work before building on top of it.
Explanation from the Preshing on Programming blog:
It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:
with open('output.txt', 'w') as f: f.write('Hi there!')
The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.
after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.
Sometimes autoplay is needed. Someone once pointed out that the famous Les Paul Google Doodle (2011) required autoplay, even though the sound didn't play until you moused over the guitar strings. If it's done with class and great design it can be beautiful (especially movie websites with immersive design)
It depends on where the files reside. For instance, if they are all supposed to be in the same directory, you can read all the directory entries into a hash table and then check all the names against the hash table. This might be faster on some systems than checking each file individually. The fastest way to check each file individually depends on your system ... if you're writing ANSI C, the fastest way is fopen
because it's the only way (a file might exist but not be openable, but you probably really want openable if you need to "do something on it"). C++, POSIX, Windows all offer additional options.
While I'm at it, let me point out some problems with your question. You say that you want the fastest way, and that you have thousands of files, but then you ask for the code for a function to test a single file (and that function is only valid in C++, not C). This contradicts your requirements by making an assumption about the solution ... a case of the XY problem. You also say "in standard c++11(or)c++(or)c" ... which are all different, and this also is inconsistent with your requirement for speed ... the fastest solution would involve tailoring the code to the target system. The inconsistency in the question is highlighted by the fact that you accepted an answer that gives solutions that are system-dependent and are not standard C or C++.
Use the -isEqualToString:
method to compare the value of two strings. Using the C ==
operator will simply compare the addresses of the objects.
if ([category isEqualToString:@"Some String"])
{
// Do stuff...
}
let array = [267, 306, 108]
let longest = Math.max(...array);
You only have to replace the WHERE with a LEFT JOIN:
SELECT CASE
WHEN S.Id IS NOT NULL AND S.Status = 1 AND ...) THEN 1
ELSE 0
END AS [Value]
FROM (SELECT @SiteId AS Id) R
LEFT JOIN Sites S ON S.Id = R.Id
This solution allows you to return default values for each column also, for example:
SELECT
CASE WHEN S.Id IS NULL THEN 0 ELSE S.Col1 END AS Col1,
S.Col2,
ISNULL(S.Col3, 0) AS Col3
FROM
(SELECT @Id AS Id) R
LEFT JOIN Sites S ON S.Id = R.Id AND S.Status = 1 AND ...
The "break" command does not work within an "if" statement.
If you remove the "break" command from your code and then test the code, you should find that the code works exactly the same without a "break" command as with one.
"Break" is designed for use inside loops (for, while, do-while, enhanced for and switch).
I tried to Resize Canvas using jQuery but it din't work well. I think CSS3 is the best option you can try on, if you want on hover zooming at certain level.
Following hover option from other codepan link:
.style_prevu_kit:hover{
z-index: 2;
-webkit-transition: all 200ms ease-in;
-webkit-transform: scale(1.5);
-ms-transition: all 200ms ease-in;
-ms-transform: scale(1.5);
-moz-transition: all 200ms ease-in;
-moz-transform: scale(1.5);
transition: all 200ms ease-in;
transform: scale(1.5);
}
Follow my codepan link:
I've tested this and it works. What's the problem? Just put the new function inside your javascript element and then call it. It will work.
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {11, 12, 13, 14, 15};
copy(v2.begin(), v2.end(), back_inserter(v1));
It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.
I made my solution based on the posts I found here with Google. And I thought there is no harm to post mine as well even if it is an old thread.
The only plus this code gives is that it can iterate through sub-directories as well.
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
Method is as follows:
List <File> exploreThis(String dirPath){
File topDir = new File(dirPath);
List<File> directories = new ArrayList<>();
directories.add(topDir);
List<File> textFiles = new ArrayList<>();
List<String> filterWildcards = new ArrayList<>();
filterWildcards.add("*.txt");
filterWildcards.add("*.doc");
FileFilter typeFilter = new WildcardFileFilter(filterWildcards);
while (directories.isEmpty() == false)
{
List<File> subDirectories = new ArrayList();
for(File f : directories)
{
subDirectories.addAll(Arrays.asList(f.listFiles((FileFilter)DirectoryFileFilter.INSTANCE)));
textFiles.addAll(Arrays.asList(f.listFiles(typeFilter)));
}
directories.clear();
directories.addAll(subDirectories);
}
return textFiles;
}
For top right corner try this:
position: absolute;
top: 0;
right: 0;
The prime example to understand the fork()
and exec()
concept is the shell,the command interpreter program that users typically executes after logging into the system.The shell interprets the first word of command line as a command name
For many commands,the shell forks and the child process execs the command associated with the name treating the remaining words on the command line as parameters to the command.
The shell allows three types of commands. First, a command can be an executable file that contains object code produced by compilation of source code (a C program for example). Second, a command can be an executable file that contains a sequence of shell command lines. Finally, a command can be an internal shell command.(instead of an executable file ex->cd,ls etc.)
Update:
As of Notepad++ v7.6, use Plugin Admin to install JSTool per this answer
INSTALL
Download it from http://sourceforge.net/projects/jsminnpp/ and copy JSMinNpp.dll to plugin directory of Notepad++. Or you can just install "JSTool" from Plugin Manager in Notepad++.
New Notepad++ install and where did PluginManager go? See How to view Plugin Manager in Notepad++
{
"menu" : {
"id" : "file",
"value" : "File",
"popup" : {
"menuitem" : [{
"value" : "New",
"onclick" : "CreateNewDoc()"
}, {
"value" : "Open",
"onclick" : "OpenDoc()"
}, {
"value" : "Close",
"onclick" : "CloseDoc()"
}
]
}
}
}
Tip: Select the code you want to reformat, then Plugins | JSTool | JSFormat.
If you need to know the default collation for a newly created database use:
SELECT SERVERPROPERTY('Collation')
This is the server collation for the SQL Server instance that you are running.
i tried the last answer from Sandeep Kumar, and i found way more simple :
<option value="1" <c:if test="${item.key == 1}"> selected </c:if>>
As long as your List is a concrete class, you can simply call the contains() method as long as you have implemented your equals() method on MyItem.
// given
// some input ... you to complete
// when
List<MyItems> results = service.getMyItems();
// then
assertTrue(results.contains(new MyItem("foo")));
assertTrue(results.contains(new MyItem("bar")));
Assumes you have implemented a constructor that accepts the values you want to assert on. I realise this isn't on a single line, but it's useful to know which value is missing rather than checking both at once.
Java (at least 5 and 6, java 7 Paths solved most) has a problem with UNC and URI. Eclipse team wrapped it up here : http://wiki.eclipse.org/Eclipse/UNC_Paths
From java.io.File javadocs, the UNC prefix is "////", and java.net.URI handles file:////host/path (four slashes).
More details on why this happens and possible problems it causes in other URI and URL methods can be found in the list of bugs at the end of the link given above.
Using these informations, Eclipse team developed org.eclipse.core.runtime.URIUtil class, which source code can probably help out when dealing with UNC paths.
Check if this solves the problem:
<div class="container-fluid no-padding">
<div class="row">
<div class="col-md-12">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
</div>
</div>
</div>
CSS
.no-padding {
padding-left: 0;
padding-right: 0;
}
Css class no-padding
will override default bootstrap container padding.
Full example here.
@Update If you use bootstrap 4 it could be done even simpler
<div class="container-fluid px-0">
<div class="row">
<div class="col-md-12">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
</div>
</div>
</div>
Updated example here.
Dump
mysqldump db_name table_name > table_name.sql
Dumping from a remote database
mysqldump -u <db_username> -h <db_host> -p db_name table_name > table_name.sql
For further reference:
http://www.abbeyworkshop.com/howto/lamp/MySQL_Export_Backup/index.html
Restore
mysql -u <user_name> -p db_name
mysql> source <full_path>/table_name.sql
or in one line
mysql -u username -p db_name < /path/to/table_name.sql
Credit: John McGrath
Dump
mysqldump db_name table_name | gzip > table_name.sql.gz
Restore
gunzip < table_name.sql.gz | mysql -u username -p db_name
Pattern class is the entry point of the regex engine.You can use it through Pattern.matches() and Pattern.comiple(). #Difference between these two. matches()- for quickly check if a text (String) matches a given regular expression comiple()- create the reference of Pattern. So can use multiple times to match the regular expression against multiple texts.
For reference:
public static void main(String[] args) {
//single time uses
String text="The Moon is far away from the Earth";
String pattern = ".*is.*";
boolean matches=Pattern.matches(pattern,text);
System.out.println("Matches::"+matches);
//multiple time uses
Pattern p= Pattern.compile("ab");
Matcher m=p.matcher("abaaaba");
while(m.find()) {
System.out.println(m.start()+ " ");
}
}
Try rejson-py which is relatively new since 2017. Look at this introduction.
from rejson import Client, Path
rj = Client(host='localhost', port=6379)
# Set the key `obj` to some object
obj = {
'answer': 42,
'arr': [None, True, 3.14],
'truth': {
'coord': 'out there'
}
}
rj.jsonset('obj', Path.rootPath(), obj)
# Get something
print 'Is there anybody... {}?'.format(
rj.jsonget('obj', Path('.truth.coord'))
)
# Delete something (or perhaps nothing), append something and pop it
rj.jsondel('obj', Path('.arr[0]'))
rj.jsonarrappend('obj', Path('.arr'), 'something')
print '{} popped!'.format(rj.jsonarrpop('obj', Path('.arr')))
# Update something else
rj.jsonset('obj', Path('.answer'), 2.17)
Use execute_script
, here's a python example:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python")
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")
There is a somehow recommended directory structure mentioned at https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html
You can create a api
folder and put your controllers there.
If you have some configuration beans, put them in a separate package too.
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
Use the code below:
using Newtonsoft.Json;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(ds.Tables[0]);
just right click on the project file in eclipse and in build path select "Use as source folder"...It worked for me
That only works for numbers less than 1.
select to_char(12.34, '0D99') from dual;
-- Result: #####
This won't work.
You could do something like this but this results in leading whitespaces:
select to_char(12.34, '999990D99') from dual;
-- Result: ' 12,34'
Ultimately, you could add a TRIM to get rid of the whitespaces again but I wouldn't consider that a proper solution either...
select trim(to_char(12.34, '999990D99')) from dual;
-- Result: 12,34
Again, this will only work for numbers with 6 digits max.
Edit: I wanted to add this as a comment on DCookie's suggestion but I can't.
try putting
ErrorDocument 404 /(root directory)/(error file)
in .htaccess
file.
Do this for any error but substitute 404 for your error.
The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.
The question asked is just a type conversion question and here its conversion from int
data type to float
data type and for that you can do it by the function :
float()
And for more details you can visit this page.
You have probably added them to the repository before putting *.pyc
in .gitignore
.
First remove them from the repository.
write like this:
<div class="parent">
<a href="http://www.example.com">example</a>
</div>
CSS
.parent{
text-align:center
}
Is your repository at "upstream" a bare repository? I got the same error, but when I change to bare they no longer happen.
When you use ng-options to populate a select list, it uses the entire object as the selected value, not just the single value you see in the select list. So in your case, you'd need to set
$scope.object.setDefault = {
id:600,
name:"def"
};
or
$scope.object.setDefault = $scope.selectItems[1];
I also recommend just outputting the value of $scope.object.setDefault in your template to see what I'm talking about getting selected.
<pre>{{object.setDefault}}</pre>
Because C++ inherited them from C. Unfortunately.
H2CO3 is right, you can use a makefile with the CXXFLAGS set with -std=c++11 A makefile is a simple text file with instructions about how to compile your program. Create a new file named Makefile (with a capital M). To automatically compile your code just type the make command in a terminal. You may have to install make.
Here's a simple one :
CXX=clang++
CXXFLAGS=-g -std=c++11 -Wall -pedantic
BIN=prog
SRC=$(wildcard *.cpp)
OBJ=$(SRC:%.cpp=%.o)
all: $(OBJ)
$(CXX) -o $(BIN) $^
%.o: %.c
$(CXX) $@ -c $<
clean:
rm -f *.o
rm $(BIN)
It assumes that all the .cpp files are in the same directory as the makefile. But you can easily tweak your makefile to support a src, include and build directories.
Edit : I modified the default c++ compiler, my version of g++ isn't up-to-date. With clang++ this makefile works fine.
If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.
See this page with information on how to create a user style
As a professional Developer I'd say it depends. But I definitely follow GATS and OMG Ponies advice. Know What You are doing, know when it helps and when it hurts and
read hints and other poor ideas
what might make You understand the sql server deeper. I generally follow the rule that SQL Hints are EVIL, but unfortunately I use them every now and then when I get fed up with forcing SQL server do things... But these are rare cases.
luke
You can use the required
html attribute if you want:
@Html.TextBoxFor(m => m.ShortName,
new { @class = "form-control", placeholder = "short name", required="required"})
or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute
can Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.
OR
You can get really advanced:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
@Html.TextBoxFor(m => m.ShortName, attributes)
}
or if you need it for multiple editor templates:
public static class ViewPageExtensions
{
public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
instance.Html.GetUnobtrusiveValidationAttributes(
instance.ViewData.TemplateInfo.HtmlFieldPrefix));
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
}
}
then in your templates:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = this.GetAttributes();
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
@Html.TextBoxFor(m => m.ShortName, attributes)
}
Update 1 (for Tomas who is unfamilar with ViewData).
What's the difference between ViewData and ViewBag?
Excerpt:
So basically it (ViewBag) replaces magic strings:
ViewData["Foo"]
with magic properties:
ViewBag.Foo
Scopes in AngularJS use prototypal inheritance, when looking up a property in a child scope the interpreter will look up the prototype chain starting from the child and continue to the parents until it finds the property, not the other way around.
Check Vojta's comments on the issue https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J
In a nutshell: You cannot access child scopes from a parent scope.
Your solutions:
$emit
sends events upwards to parents until the root scope and $broadcast
dispatches events downwards. This might help you to keep things semantically correct.you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
New ways I: fetch
TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.
A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch()
to send a request and ResponseBody.json()
to parse the response:
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(jsonResponse) {
// do something with jsonResponse
});
Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.
New ways II: responseType
As Londeren has written in his answer, newer browsers allow you to use the responseType
property to define the expected format of the response. The parsed response data can then be accessed via the response
property:
var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload = function() {
var jsonResponse = req.response;
// do something with jsonResponse
};
req.send(null);
Compatibility: responseType = 'json'
is not supported by IE11.
The classic way
The standard XMLHttpRequest has no responseJSON
property, just responseText
and responseXML
. As long as bitly really responds with some JSON to your request, responseText
should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse()
:
var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload = function() {
var jsonResponse = JSON.parse(req.responseText);
// do something with jsonResponse
};
req.send(null);
Compatibility: This approach should work with any browser that supports XMLHttpRequest
and JSON
.
JSONHttpRequest
If you prefer to use responseJSON
, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON
property. All you have to change in your code would be the first line:
var req = new JSONHttpRequest();
JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.
Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.
This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).
When you type in a command at the Unix prompt, you are interacting with the shell.
E.g., #!/bin/csh
refers to the C-shell, /bin/tcsh
the t-shell, /bin/bash
the bash shell, etc.
You can tell which interactive shell you are using the
echo $SHELL
command, or alternatively
env | grep -i shell
You can change your command shell with the chsh
command.
Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.
This page might be of interest as it "translates" between bash and tcsh commands/syntax.
Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh
shell interactively, but often run bash scripts using /bin/bash in the script file.
Aside:
This concept extends to other scripts too. For instance if you program in Python you'd put
#!/usr/bin/python
at the top of your Python program
Swift 4: Use following code
let number = 2.4
let string = String(format: "%.2f", number)
Here's a programmatic solution from @Aromero's answer to calculate the hexadecimal value for the alpha channel. :)
public static void main(String[] args) throws Exception {
final Scanner scanner = new Scanner(System.in);
int transPerc;
float fPerc;
System.out.println("Enter the transparency percentage without % symbol:");
while((transPerc=scanner.nextInt())>=0 && transPerc <=100){
fPerc = (float) transPerc / 100;
transPerc = Math.round(255 * fPerc);
System.out.println("= " + Integer.toHexString(transPerc));
System.out.print("another one please : ");
}
scanner.close();
}
matrix.size
according to the numpy docs returns the Number of elements in the array.
Hope that helps.
I just hit this exact issue with Angular 6 using the CLI and workspaces to create a library using ng g library foo
.
In my case the issue was in the tsconfig.lib.json
in the library folder which did not have es2017
included in the lib
section.
Anyone stumbling across this issue with Angular 6 you just need to ensure that you update you tsconfig.lib.json
as well as your application tsconfig.json
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
Above .net core 2.2 the method Main support args with WebHost.CreateDefaultBuilder(args)
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
You can build your project and go to bin
run command like this
dotnet <yours>.dll --urls=http://localhost:5001
or with multi-urls
dotnet <yours>.dll --urls="http://localhost:5001,https://localhost:5002"
I took @hajamie's solution and wrapped it up into a slightly more convenient script wrapper.
I added an option to start from an offset before the end of the file, so you can use the tail-like functionality of reading a certain amount from the end of the file. Note the offset is in bytes, not lines.
There's also an option to continue waiting for more content.
Examples (assuming you save this as TailFile.ps1):
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000 -Follow:$true
.\TailFile.ps1 -File .\path\to\myfile.log -Follow:$true
And here is the script itself...
param (
[Parameter(Mandatory=$true,HelpMessage="Enter the path to a file to tail")][string]$File = "",
[Parameter(Mandatory=$true,HelpMessage="Enter the number of bytes from the end of the file")][int]$InitialOffset = 10248,
[Parameter(Mandatory=$false,HelpMessage="Continuing monitoring the file for new additions?")][boolean]$Follow = $false
)
$ci = get-childitem $File
$fullName = $ci.FullName
$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($fullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length - $InitialOffset
while ($true)
{
#if the file size has not changed, idle
if ($reader.BaseStream.Length -ge $lastMaxOffset) {
#seek to the last max offset
$reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null
#read out of the file until the EOF
$line = ""
while (($line = $reader.ReadLine()) -ne $null) {
write-output $line
}
#update the last max offset
$lastMaxOffset = $reader.BaseStream.Position
}
if($Follow){
Start-Sleep -m 100
} else {
break;
}
}
In Swift the isEmpty
function it will check if the string is empty.
if username.isEmpty || password.isEmpty {
println("Sign in failed. Empty character")
}
Update: For bash scripts, the most direct and performant approach is:
if compgen -G "${PROJECT_DIR}/*.png" > /dev/null; then
echo "pattern exists!"
fi
This will work very speedily even in directories with millions of files and does not involve a new subshell.
The simplest should be to rely on ls
return value (it returns non-zero when the files do not exist):
if ls /path/to/your/files* 1> /dev/null 2>&1; then
echo "files do exist"
else
echo "files do not exist"
fi
I redirected the ls
output to make it completely silent.
EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls
:
for f in /path/to/your/files*; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo "files do exist" || echo "files do not exist"
## This is all we needed to know, so we can break after the first iteration
break
done
This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.
Use these simple steps to resize the vmdk
File -> Virtual Media Player
properties
Here you can increase or decrease the vdi size.
std::fill(v.begin(), v.end(), 0);
to close fancybox by funciton its necessary to make setTimtout to the function that will close the fancybox Fancybox needs some time to acept the close function If you call the function directly will not work
function close_fancybox(){
$.fancybox.close();
}
setTimeout(close_fancybox, 50);
This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs
SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.
And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.
This is the fix we did
<listener>
<listener-class>
net.sf.ehcache.constructs.web.ShutdownListener
</listener-class>
</listener>
So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.
Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html
In Go with "sql.DB" (note the search_path
with underscore):
postgres://user:password@host/dbname?sslmode=disable&search_path=schema
I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)
I think you missed a key point in the documentation for .add()
Mutates the original moment by adding time.
You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)
If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.
You can work around this behavior by cloning the moment, as described here.
Also, you cannot just use ==
to test. You could format each moment to the same output and compare those, or you could just use the .isSame()
method.
Your code is now:
var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours'); // see the cloning?
returned_endate.isSame(expected_enddate) // true
Use raw_input
instead of input
:)
If you use
input
, then the data you type is is interpreted as a Python Expression which means that you end up with gawd knows what type of object in your target variable, and a heck of a wide range of exceptions that can be generated. So you should NOT useinput
unless you're putting something in for temporary testing, to be used only by someone who knows a bit about Python expressions.
raw_input
always returns a string because, heck, that's what you always type in ... but then you can easily convert it to the specific type you want, and catch the specific exceptions that may occur. Hopefully with that explanation, it's a no-brainer to know which you should use.
Note: this is only for Python 2. For Python 3, raw_input()
has become plain input()
and the Python 2 input()
has been removed.
In my case neither M
or G
helped, so I have converted allocated memory to bytes using: https://www.gbmb.org/mb-to-bytes
4096M = 4294967296
php.ini:
memory_limit = 4294967296
Do you mean like this
int index = 2;
string s = "hello";
Console.WriteLine(s[index]);
string also implements IEnumberable<char>
so you can also enumerate it like this
foreach (char c in s)
Console.WriteLine(c);
Here's the way I was able to truncate and not round:
select 100.0019-(100.0019%.001)
returns 100.0010
And your example:
select 123.456-(123.456%.001)
returns 123.450
Now if you want to get rid of the ending zero, simply cast it:
select cast((123.456-(123.456%.001)) as decimal (18,2))
returns 123.45
Use the DEFAULT keyword:
$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')";
Also, you can specify the columns, (which is better practice):
$query = "INSERT INTO myTable
(fname, lname, website)
VALUES
('fname', 'lname', 'website')";
Reference:
try this:
head -1 /etc/*release | awk '{print $1}'
Are you sure using the java.net.URL
class? Check your import statements.
in simple words
in Html - add below code only
<form name="upload" class="form" data-ng-submit="addFile()">
<input type="file" name="file" multiple
onchange="angular.element(this).scope().uploadedFile(this)" />
<button type="submit">Upload </button>
</form>
in the controller - This function is called when you click "upload file button". it will upload the file. you can console it.
$scope.uploadedFile = function(element) {
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
add more in controllers - below code add into the function . This function is called when you click on button which is used "hitting the api (POST)". it will send file(which uploaded) and form-data to the backend .
var url = httpURL + "/reporttojson"
var files=$scope.files;
for ( var i = 0; i < files.length; i++)
{
var fd = new FormData();
angular.forEach(files,function(file){
fd.append('file',file);
});
var data ={
msg : message,
sub : sub,
sendMail: sendMail,
selectUsersAcknowledge:false
};
fd.append("data", JSON.stringify(data));
$http.post(url, fd, {
withCredentials : false,
headers : {
'Content-Type' : undefined
},
transformRequest : angular.identity
}).success(function(data)
{
toastr.success("Notification sent successfully","",{timeOut: 2000});
$scope.removereport()
$timeout(function() {
location.reload();
}, 1000);
}).error(function(data)
{
toastr.success("Error in Sending Notification","",{timeOut: 2000});
$scope.removereport()
});
}
in this case .. i added below code as form data
var data ={
msg : message,
sub : sub,
sendMail: sendMail,
selectUsersAcknowledge:false
};
An alternative to using keytool
, you can use the command
openssl x509 -in certificate.pem -text
This should work for any x509 .pem file provided you have openssl
installed.
For Spring Boot 2 following properties are deprecated in application.yml configuration
security.basic.enabled: false
management.security.enabled: false
To disable security for Sprint Boot 2 Basic + Actuator Security following properties can be used in application.yml file instead of annotation based exclusion (@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}))
spring:
autoconfigure:
exclude[0]: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
exclude[1]: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration
For application.properties syntax would be like
spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
Git Stash Pop vs apply
Working
If you want to apply your top stashed changes to current non-staged change and delete that stash as well, then you should go for git stash pop
.
# apply the top stashed changes and delete it from git stash area.
git stash pop
But if you are want to apply your top stashed changes to current non-staged change without deleting it, then you should go for git stash apply
.
Note : You can relate this case with
Stack
classpop()
andpeek()
methods, where pop change the top by decrements (top = top-1) butpeek()
only able to get the top element.
assuming you have a SQL table called mydata - you can load data from a csv file as follows:
COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;
For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html
Implementation with Guzzle library:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$httpClient = new Client();
$response = $httpClient->post(
'https://postman-echo.com/post',
[
RequestOptions::BODY => 'POST raw request content',
RequestOptions::HEADERS => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]
);
echo(
$response->getBody()->getContents()
);
PHP CURL extension:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify request content
*/
CURLOPT_POSTFIELDS => 'POST raw request content',
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
Does GitHub have this social feature?
If the commit email is kept private, GitHub now (July 2020) proposes:
Users and organizations can now add Twitter usernames to their GitHub profiles
You can now add your Twitter username to your GitHub profile directly from your profile page, via profile settings, and also the REST API.
We've also added the latest changes:
- Organization admins can now add Twitter usernames to their profile via organization profile settings and the REST API.
- All users are now able to see Twitter usernames on user and organization profiles, as well as via the REST and GraphQL APIs.
- When sponsorable maintainers and organizations add Twitter usernames to their profiles, we'll encourage new sponsors to include that Twitter username when they share their sponsorships on Twitter.
That could be a workaround to leave a message to a GitHub user.