I usually do this and works always.
/try this/
for (i = res; i < *size-1; i++) {
arrb[i] = arrb[i + 1];
}
*size = *size - 1; /*in some ides size -- could give problems*/
Rules ordered by priority:
Source : https://www.lucidar.me/en/web-dev/sessions-or-cookies/
Sessions use a cookie! Session data is stored on the server side, but a UID is stored on client side in a cookie. It allows the server to match a given user with the right session data. UID is protected and hard to hack, but not invulnarable. For sensitive actions (changing email or resetting password), do not rely on sessions neither cookies : ask for the user password to confirm the action.
Sensitive data should never be stored in cookies (emails, encrypted passwords, personal data ...). Keep in mind the data are stored on a foreign computer, and if the computer is not private (classroom or public computers) someone else can potentially read the cookies content.
Remember-me data must be stored in cookies, otherwise data will be lost when the user closes the browser. However, don't save password or user personal data in the 'remember-me' cookie. Store user data in database and link this data with an encrypted pair of ID / key stored in a cookie.
After considering the previous recommandations, the following question is finally what helps you choosing between cookies and sessions:
Must persistent data remain when the user closes the browser ?
FWIW, htpasswd -n username
will output the result directly to stdout, and avoid touching files altogether.
private String message;
private ScreenManager s;
//Here is an example of code to add the keyListener() as suggested; modify
public void init(){
Window w = s.getFullScreenWindow();
w.addKeyListener(this);
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_F5)
message = "Pressed: " + KeyEvent.getKeyText(keyCode);
}
Just use the length
property of a JavaScript
array like so:
$scope.names.length
Also, I don't see a starting <script>
tag in your code.
If you want the length inside your view, do it like so:
{{ names.length }}
The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.
So if you are like me who work in a branch, here are tips:
Or more simply, just use HEAD:
I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error
The FLAWED version
import threading
import time
# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []
def add():
for i in range(count):
l.append(i)
time.sleep(0.0001)
def remove():
for i in range(count):
l.remove(i)
time.sleep(0.0001)
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()
print(l)
Output when ERROR
Exception in thread Thread-63:
Traceback (most recent call last):
File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
l.remove(i)
ValueError: list.remove(x): x not in list
Version that uses locks
import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
with lock:
for i in range(count):
l.append(i)
time.sleep(0.0001)
def remove():
with lock:
for i in range(count):
l.remove(i)
time.sleep(0.0001)
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()
print(l)
Output
[] # Empty list
Conclusion
As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another
Try this statement:
exit 1
Replace 1
with appropriate error codes. See also Exit Codes With Special Meanings.
You may use jQuery in it like
$('#yesh').click(function(){
*****HERE GOES THE FUNCTION*****
});
Besides jQuery is easy to use.
You can make changes in colors etc using simple jQUery or Javascript.
The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:
my
variables are lexically scoped within a single block defined by {}
or within the same file if not in {}
s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.
our
variables are scoped within a package/file and accessible from any code that use
or require
that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.
Just to round it out, local
variables are "dynamically" scoped, differing from my
variables in that they are also accessible from subroutines called within the same block.
module - camera, location, ....
class PermissionType(val manifest_permission: String, val packageManager: String) {
object Defined {
val camera = PermissionType(Manifest.permission.CAMERA, PackageManager.FEATURE_CAMERA)
val currentLocation = PermissionType(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.FEATURE_LOCATION_GPS)
}
}
class Permission {
enum class PermissionResult {
ACCESS_ALLOWED, ACCESS_DENIED, NO_SYSTEM_FEATURE;
}
interface ManagerDelegate {
fun permissionManagerDelegate(result: Array<Pair<String, PermissionResult>>)
}
class Manager internal constructor(private val delegate: ManagerDelegate?) {
private var context: Context? = null
private var fragment: Fragment? = null
private var activity: AppCompatActivity? = null
private var permissionTypes: Array<PermissionType> = arrayOf()
private val REQUEST_CODE = 999
private val semaphore = Semaphore(1, true)
private var result: Array<Pair<String, PermissionResult>> = arrayOf()
constructor(permissionType: PermissionType, delegate: ManagerDelegate?): this(delegate) {
permissionTypes = arrayOf(permissionType)
}
constructor(permissionTypes: Array<PermissionType>, delegate: ManagerDelegate?): this(delegate) {
this.permissionTypes = permissionTypes
}
init {
when (delegate) {
is Fragment -> {
this.fragment = delegate
this.context = delegate.context
}
is AppCompatActivity -> {
this.activity = delegate
this.context = delegate
}
}
}
private fun hasSystemFeature(permissionType: PermissionType) : Boolean {
return context?.packageManager?.hasSystemFeature(permissionType.packageManager) ?: false
}
private fun hasAccess(permissionType: PermissionType) : Boolean {
return if (Build.VERSION.SDK_INT < 23) true else {
context?.checkSelfPermission(permissionType.manifest_permission) == PackageManager.PERMISSION_GRANTED
}
}
private fun sendRequest(permissionTypes: Array<String>) {
if (fragment != null) {
fragment?.requestPermissions(permissionTypes, REQUEST_CODE)
return
}
if (activity != null){
ActivityCompat.requestPermissions(activity!!, permissionTypes, REQUEST_CODE)
}
}
fun check() {
semaphore.acquire()
AsyncTask.execute {
var permissionsForSendingRequest: Array<String> = arrayOf()
this.result = arrayOf()
for (it in permissionTypes) {
if (!hasSystemFeature(it)) {
result += Pair(it.manifest_permission, PermissionResult.NO_SYSTEM_FEATURE)
continue
}
if (hasAccess(it)) {
result += Pair(it.manifest_permission, PermissionResult.ACCESS_ALLOWED)
} else {
permissionsForSendingRequest += it.manifest_permission
}
}
if (permissionsForSendingRequest.isNotEmpty()) {
sendRequest(permissionsForSendingRequest)
} else {
delegate?.permissionManagerDelegate(result)
}
}
}
fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_CODE -> {
if (grantResults.isEmpty()) {
return
}
for ((i,permission) in permissions.withIndex()) {
for (item in this.permissionTypes) {
if (permission == item.manifest_permission && i < grantResults.size) {
result += if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Pair(item.manifest_permission, PermissionResult.ACCESS_ALLOWED)
} else {
Pair(item.manifest_permission, PermissionResult.ACCESS_DENIED)
}
break
}
}
}
delegate?.permissionManagerDelegate(result)
}
}
semaphore.release()
}
}
}
class BaseActivity : AppCompatActivity(), Permission.ManagerDelegate {
private lateinit var permissionManager: Permission.Manager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.base_activity)
permissionManager = Permission.Manager(arrayOf(PermissionType.Defined.camera, PermissionType.Defined.currentLocation), this)
permissionManager.check()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun permissionManagerDelegate(result: Array<Pair<String, Permission.PermissionResult>>) {
result.forEach {
println("!!! ${it.first} ${it.second}")
// when (it.second) {
// Permission.PermissionResult.NO_SYSTEM_FEATURE -> {
// }
//
// Permission.PermissionResult.ACCESS_DENIED -> {
// }
//
// Permission.PermissionResult.ACCESS_ALLOWED -> {
// }
// }
}
}
}
If you are mocking the behavior (with something like doNothing()
) there should really be no need to call to verify*()
. That said, here's my stab at re-writing your test method:
@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
public void testProcessOrder() {
//Variables
InternalService is = new InternalService();
Order order = mock(Order.class);
//Mock Behavior
when(order.isSuccessful()).thenReturn(true);
mockStatic(Internalutils.class);
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
//Execute
is.processOrder(order);
//Verify
verifyStatic(InternalUtils.class); //Similar to how you mock static methods
//this is how you verify them.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
}
}
I grouped into four sections to better highlight what is going on:
I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.
This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.
Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.
This is when you call any method starting with verify
or assert
. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.
This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.
I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:
This is perhaps more succinct:
function toggle(element, klass) {
var classes = element.className.match(/\S+/g) || [],
index = classes.indexOf(klass);
index >= 0 ? classes.splice(index, 1) : classes.push(klass);
element.className = classes.join(' ');
}
If you ever need to do this dynamically, you can use the following:
boolean isInstance(Object object, Class<?> type) {
return type.isInstance(object);
}
You can get an instance of java.lang.Class
by calling the instance method Object::getClass
on any object (returns the Class
which that object is an instance of), or you can do class literals (for example, String.class
, List.class
, int[].class
). There are other ways as well, through the reflection API (which Class
itself is the entry point for).
Your expression should already match dashes, because the final - will not be interpreted as a range operator (since the range has no end). To add underscores as well, try:
([A-Za-z0-9_-]+)
I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.
Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".
Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.
My little contribution:
function isInArray(array, search)
{
return array.indexOf(search) >= 0;
}
//usage
if(isInArray(my_array, "my_value"))
{
//...
}
You need to use delegates and protocols. Here is a site with an example http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
This post asked a similar question and used LINQ to solve it, maybe it will help you out too.
string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();
As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;
JsonSerializer serializer = new JsonSerializer();
MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(@".\path\to\json\config\file.json");
The above code assumes that you have something like
public class MyObject
{
public string prop1 { get; set; };
public string prop2 { get; set; };
}
And your json looks like;
{
"prop1":"value1",
"prop2":"value2"
}
I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.
I know this post is old. But i have seen several attempts of guys trying to answer using async and await but getting it wrong. This should clear it up for any new references
async function axiosTest() {
try {
const {data:response} = await axios.get(url) //use data destructuring to get data from the promise object
return response
}
catch (error) {
console.log(error);
}
}
I would like to add this, I used this in laravel to just index my table:
My Code:
@foreach($resultsPerCountry->first()->studies as $result)
<tr>
<td>{{ ++$loop->index}}</td>
</tr>
@endforeach
Why not copy Microsoft.Web.Infrastructure.dll file manually to the server BIN folder. This works for. My project is VS2010 Website.
This file can be located:
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40
Just copy and paste it in the BIN folder.
You probably need to include this in the web.config if you don't have it already
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
Reference: http://thedeveloperblog.com/
Use the hasClass
method:
jQueryCollection.hasClass(className);
or
$(selector).hasClass(className);
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
Note: If you pass a className
argument that contains whitespace, it will be matched literally against the collection's elements' className
string. So if, for instance, you have an element,
<span class="foo bar" />
then this will return true
:
$('span').hasClass('foo bar')
and these will return false
:
$('span').hasClass('bar foo')
$('span').hasClass('foo bar')
If you have https
server, change your url to use https://
protocol.
I got into similar issue with this one. My url has http://
protocol and I want to make a POST
request, but the server wants to redirect it to https
. What happen is that, turns out to be node http behavior sends the redirect request (next) in GET
method which is not the case.
What I did is to change my url to https://
protocol and it works.
I had the same issue after I tried to restart mysql.
I use the following two aliases in my .profile for convenience
alias mysql-stop='launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist'
alias mysql-start='launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist'
After stoping mysql and then trying to restart I experienced the issue you were having. I looked into the launchctl load and it was reporting a “nothing found to load” error.
After a quick search I found this..
http://www.daveoncode.com/2013/02/01/solve-mac-osx-launchctl-nothing-found-to-load-error/
So I updated me mysql-start
alias as follows
alias mysql-start='launchctl load -w -F ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist'
This solved my issue which may be useful for you.
Use either the <button>
element or use an <input type="button"/>
.
SyntaxError: Unexpected token o in JSON
This also happens when you forget to use the await
keyword for a method that returns JSON data.
For example:
async function returnJSONData()
{
return "{\"prop\": 2}";
}
var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);
will throw an error because of the missing await
. What is actually returned is a Promise
[object], not a string
.
To fix just add await as you're supposed to:
var json_str = await returnJSONData();
This should be pretty obvious, but the error is called on JSON.parse
, so it's easy to miss if there's some distance between your await
method call and the JSON.parse
call.
I solved it changing my 'Compiler compliance level'. In Eclipse:
Window -> Preferences -> Java -> Compiler
I got this error message after making the following change in my top-level build.gradle
to update to the latest version of gradle:
//classpath 'com.android.tools.build:gradle:2.3.2' old
classpath 'com.android.tools.build:gradle:2.3.3' //new
I foolishly made the change while I was connected behind a hostile workplace proxy. The proxy caused the .jar
files for the new version of gradle to become corrupt. This can be verified by inspecting the jars to see if they are an unusual size or whether they can be unzipped.
In order to fix the mistake, I connected to my network at home (which is not behind a proxy) and did a refresh dependencies from the Terminal:
./gradlew --refresh-dependencies
This caused the newer version of gradle to be re-downloaded and the error no longer occurs.
If it says the API key is listed as a header, more than likely you need to set it in the headers
option of your http request. Normally something like this :
headers: {'Authorization': '[your API key]'}
Here is an example from another Question
$http({method: 'GET', url: '[the-target-url]', headers: {
'Authorization': '[your-api-key]'}
});
Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :
$.ajax({
type : "GET",
url : "[the-target-url]",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
success : function(result) {
//set your variable to the result
},
error : function(result) {
//handle the error
}
});
I got this from this question and I'm at work so I can't test it at the moment but looks solid
Edit 2: Pretty sure you should be able to use this line :
headers: {'Authorization': '[your API key]'},
instead of the beforeSend
line in the first edit. This may be simpler for you
Make sure, following jar file included in your class path and lib folder.
spring-core-3.0.5.RELEASE.jar
if you are using maven, make sure you have included dependency for spring-core-3xxxxx.jar file
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
Note : Replace ${org.springframework.version} with version number.
The main answer worked for me but made the app extremely unresponsive in IE, so I used a timer as suggested. Code looks something like this ($(#contentColumn)
is the div that the JQGrid sits in):
function resizeGrids() {
var reportObjectsGrid = $("#ReportObjectsGrid");
reportObjectsGrid.setGridWidth($("#contentColumn").width());
};
var resizeTimer;
$(window).bind('resize', function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeGrids, 60);
});
Instead of using the "c" tags, you could also do the following:
<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />
<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>
I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?
The grep utility is not needed. Awk can do it all:
netstat -rn | awk '/default/ {print $2}'
192.168.128.1
Note that if you have something like Parallels (or a VPN, or both) running, you may see two or more default routing entries - it will be true if you use the 'grep' suggestion above, too.
netstat -rn | awk '/default/ {print $2}'
192.168.128.1
link#12
and
netstat -rn | awk '/default/ {print $2}'
utun1
192.168.128.1
link#12
To set a variable (_default) for further use (assuming only one entry for 'default') .....
_default=$( netstat -rn inet | awk '/default/ {print $2}' ) # I prefer $( ... ) over back-ticks
In the case of multiple default routes use:
netstat -rn | awk '/default/ {if ( index($6, "en") > 0 ){print $2} }'
192.168.128.1
These examples tested in Mavericks Terminal.app and are specific to OSX only. For example, other *nix versions frequently use 'eth' for ethernet/wireless connections, not 'en'. This is also only tested with ksh. Other shells may need a slightly different syntax.
You can use position:absolute;
to absolutely position an element within a parent div.
When using position:absolute;
the element will be positioned absolutely from the first positioned parent div, if it can't find one it will position absolutely from the window so you will need to make sure the content div is positioned.
To make the content div positioned, all position
values that aren't static will work, but relative
is the easiest since it doesn't change the divs positioning by itself.
So add position:relative;
to the content div, remove the float from the button and add the following css to the button:
position: absolute;
right: 0;
bottom: 0;
Include the port number with the IP address.
For example:
http://19.18.20.101:5566
where 5566 is the port number.
Also having smartNavigation="true" causes this"
You can use the | operator to combine querysets directly without needing Q objects:
result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)
(edit - I was initially unsure if this caused an extra query but @spookylukey pointed out that lazy queryset evaluation takes care of that)
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:
for (int i = 0; i < letters.size(); i++) {
letters.set(i, "D");
}
At the end the whole list will have the letter "D"
as its content. It's not a good idea to use an enhanced for
loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.
Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:
A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification
None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.
l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()
UTF-8 is a variable-length encoding. In the case of UTF-8, this means that storing one code point requires one to four bytes. However, MySQL's encoding called "utf8" (alias of "utf8mb3") only stores a maximum of three bytes per code point.
So the character set "utf8"/"utf8mb3" cannot store all Unicode code points: it only supports the range 0x000 to 0xFFFF, which is called the "Basic Multilingual Plane". See also Comparison of Unicode encodings.
This is what (a previous version of the same page at) the MySQL documentation has to say about it:
The character set named utf8[/utf8mb3] uses a maximum of three bytes per character and contains only BMP characters. As of MySQL 5.5.3, the utf8mb4 character set uses a maximum of four bytes per character supports supplemental characters:
For a BMP character, utf8[/utf8mb3] and utf8mb4 have identical storage characteristics: same code values, same encoding, same length.
For a supplementary character, utf8[/utf8mb3] cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8[/utf8mb3] cannot store the character at all, you do not have any supplementary characters in utf8[/utf8mb3] columns and you need not worry about converting characters or losing data when upgrading utf8[/utf8mb3] data from older versions of MySQL.
So if you want your column to support storing characters lying outside the BMP (and you usually want to), such as emoji, use "utf8mb4". See also What are the most common non-BMP Unicode characters in actual use?.
I got the unexpected token export error also when I was trying to import a local javascript module in my project. I solved it by declaring a type as a module when adding a script tag in my index.html file.
<script src = "./path/to/the/module/" type = "module"></script>
I don't think there's a concise, sensible way to do that, but there are verbose, sensible ways (such as Foo Bah's) and concise, pathological ways, such as
ifneq (,$(findstring $(GCC_MINOR),4-5))
CFLAGS += -fno-strict-overflow
endif
(which will execute the command provided that the string $(GCC_MINOR) appears inside the string 4-5).
EasyPHP is very good :
WAMP or UWAMP are good choices if you need to test with multiples versions of PHP and Apache.
But you can also use multiple versions of PHP with EasyPHP (by downloading the PHP version you need on php.net, and loading this version by editing httpd.conf) :
LoadModule php4_module "${path}/php4/php4apache2_2.dll"
If your data is coming from a model you can do:
App\Http\Controller\SomeController
public function index(MyModel $model)
{
return view('index', [
'data' => $model->all()->toJson(),
]);
}
index.blade.php
@push('footer-scripts')
<script>
(function(global){
var data = {!! $data !!};
console.log(data);
// [{..}]
})(window);
</script>
@endpush
I struggled with this for a long time before finding my php-fpm logs were being written to /var/log/upstart/php5-fpm.log
. It appears to be a bug between how upstart and php-fpm interact. See more here: https://bugs.launchpad.net/ubuntu/+source/php5/+bug/1319595
List does not implement IBindingList
so the grid does not know about your new items.
Bind your DataGridView to a BindingList<T>
instead.
var list = new BindingList<Person>(persons);
myGrid.DataSource = list;
But I would even go further and bind your grid to a BindingSource
var list = new List<Person>()
{
new Person { Name = "Joe", },
new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
The first method is the proper approach and will do what you need. However, with the inner joins, you will only select rows from Table1
if both phone numbers exist in Table2
. You may want to do a LEFT JOIN
so that all rows from Table1
are selected. If the phone numbers don't match, then the SomeOtherField
s would be null. If you want to make sure you have at least one matching phone number you could then do WHERE t2.PhoneNumber IS NOT NULL OR t3.PhoneNumber IS NOT NULL
The second method could have a problem: what happens if Table2
has both PhoneNumber1
and PhoneNumber2
? Which row will be selected? Depending on your data, foreign keys, etc. this may or may not be a problem.
Or something like this:
private static String myRemComa(String input) {
String[] exploded = input.split(",");
input="";
boolean start = true;
for(String str : exploded) {
str=str.trim();
if (str.length()>0) {
if (start) {
input = str;
start = false;
} else {
input = input + "," + str;
}
}
}
return input;
}
We can do this using JavaScript, no need of jQuery. Just pass the changed element and let JavaScript handle it.
HTML
<form id="myform">
syn<input type="checkbox" name="checkfield" id="g01-01" onchange="doalert(this)"/>
</form>
JS
function doalert(checkboxElem) {
if (checkboxElem.checked) {
alert ("hi");
} else {
alert ("bye");
}
}
Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true.
I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural...
MongoDB speaks JavaScript, so utilize JS naming conventions of camelCase.
MongoDB official documentation mentions you may use underscores, also built-in identifier is named _id
(but this may be be to indicate that _id
is intended to be private, internal, never displayed or edited.
Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:
If a module imports objects from another module using
from ... import ...
, callingreload()
for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to useimport
and qualified names (module.*name*
) instead.
However, if using the __all__
variable to define the public API, it is possible to automatically reload all publicly available modules:
# Python >= 3.5
import importlib
import types
def walk_reload(module: types.ModuleType) -> None:
if hasattr(module, "__all__"):
for submodule_name in module.__all__:
walk_reload(getattr(module, submodule_name))
importlib.reload(module)
walk_reload(my_module)
The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__
variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.
You can simply use shape method
df[df['LastName'] == 'Smith'].shape
Output
(1,1)
Which indicates 1 row and 1 column. This way you can get the idea of whole datasets
Let me explain the above code
DataframeName[DataframeName['Column_name'] == 'Value to match in column']
This works flawlessly @ 2019
.marketing-panel {
background-image: url("../images/background.jpg");
background-repeat: no-repeat;
background-size: auto;
background-position: center;
}
How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.
There is also a DataTable.ReadXml method.
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
For a small number of items, the difference is pretty trivial. However, if you're inserting a lot of items, or working with a very large array, calling .sort() after each insertion will cause a tremendous amount of overhead.
I ended up writing a pretty slick binary search/insert function for this exact purpose, so I thought I'd share it. Since it uses a while
loop instead of recursion, there is no overheard for extra function calls, so I think the performance will be even better than either of the originally posted methods. And it emulates the default Array.sort()
comparator by default, but accepts a custom comparator function if desired.
function insertSorted(arr, item, comparator) {
if (comparator == null) {
// emulate the default Array.sort() comparator
comparator = function(a, b) {
if (typeof a !== 'string') a = String(a);
if (typeof b !== 'string') b = String(b);
return (a > b ? 1 : (a < b ? -1 : 0));
};
}
// get the index we need to insert the item at
var min = 0;
var max = arr.length;
var index = Math.floor((min + max) / 2);
while (max > min) {
if (comparator(item, arr[index]) < 0) {
max = index;
} else {
min = index + 1;
}
index = Math.floor((min + max) / 2);
}
// insert the item
arr.splice(index, 0, item);
};
If you're open to using other libraries, lodash provides sortedIndex and sortedLastIndex functions, which could be used in place of the while
loop. The two potential downsides are 1) performance isn't as good as my method (thought I'm not sure how much worse it is) and 2) it does not accept a custom comparator function, only a method for getting the value to compare (using the default comparator, I assume).
Create an instance of OrientationEventListener
class and enable it.
OrientationEventListener mOrientationEventListener = new OrientationEventListener(YourActivity.this) {
@Override
public void onOrientationChanged(int orientation) {
Log.d(TAG,"orientation = " + orientation);
}
};
if (mOrientationEventListener.canDetectOrientation())
mOrientationEventListener.enable();
You need to use either PHP's ImageMagick or GD functions to work with images.
With GD, for example, it's as simple as...
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
And you could call this function, like so...
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.
Note also that table names are case sensitive on Linux unless you set the lower_case_table_name
config directive to 1. This is because tables are represented by files which are case sensitive in Linux.
Especially beware of development on Windows which is not case sensitive and deploying to production where it is. For example:
"SELECT * from mytable"
against table myTable will succeed in Windows but fail in Linux, again, unless the abovementioned directive is set.
Reference here: http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html
My working solution is:
npm install --save-dev cross-env
or npm install -g cross-env
.package.json
add new build script...
"build:prod:ios": "cross-env NODE_OPTIONS='--max-old-space-size=8192' ionic cordova build ios --prod --release"
...
Use that command to build next time.
npm run build:prod:ios
Problem solved.
I had this same problem - it turned out that the .gitmodules file was committed, but the actual submodule commit (i.e. the record of the submodule's commit ID) wasn't.
Adding it manually seemed to do the trick - e.g.:
git submodule add http://github.com/sciyoshi/pyfacebook.git external/pyfacebook
(Even without removing anything from .git/config or .gitmodules.)
Then commit it to record the ID properly.
Adding some further comments to this working answer: If the git submodule init or git submodule update does'nt work, then as described above git submodule add url should do the trick. One can cross check this by
git config --list
and one should get an entry of the submodule you want to pull in the result of the git config --list command. If there is an entry of your submodule in the config result, then now the usual git submodule update --init should pull your submodule. To test this step, you can manually rename the submodule and then updating the submodule.
mv yourmodulename yourmodulename-temp
git submodule update --init
To find out if you have local changes in the submodule, it can be seen via git status -u ( if you want to see changes in the submodule ) or git status --ignore-submodules ( if you dont want to see the changes in the submodule ).
Why "Accepted Answer" works... but it wasn't enough for me
This works in the specification. At least swagger-tools
(version 0.10.1) validates it as a valid.
But if you are using other tools like swagger-codegen
(version 2.1.6) you will find some difficulties, even if the client generated contains the Authentication definition, like this:
this.authentications = {
'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};
There is no way to pass the token into the header before method(endpoint) is called. Look into this function signature:
this.rootGet = function(callback) { ... }
This means that, I only pass the callback (in other cases query parameters, etc) without a token, which leads to a incorrect build of the request to server.
My alternative
Unfortunately, it's not "pretty" but it works until I get JWT Tokens support on Swagger.
Note: which is being discussed in
So, it's handle authentication like a standard header. On path
object append an header paremeter:
swagger: '2.0'
info:
version: 1.0.0
title: Based on "Basic Auth Example"
description: >
An example for how to use Auth with Swagger.
host: localhost
schemes:
- http
- https
paths:
/:
get:
parameters:
-
name: authorization
in: header
type: string
required: true
responses:
'200':
description: 'Will send `Authenticated`'
'403':
description: 'You do not have necessary permissions for the resource'
This will generate a client with a new parameter on method signature:
this.rootGet = function(authorization, callback) {
// ...
var headerParams = {
'authorization': authorization
};
// ...
}
To use this method in the right way, just pass the "full string"
// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);
And works.
When you use jackson to map from string to your concrete class, especially if you work with generic type. then this issue may happen because of different class loader. i met it one time with below scenarior:
Project B depend on Library A
in Library A:
public class DocSearchResponse<T> {
private T data;
}
it has service to query data from external source, and use jackson to convert to concrete class
public class ServiceA<T>{
@Autowired
private ObjectMapper mapper;
@Autowired
private ClientDocSearch searchClient;
public DocSearchResponse<T> query(Criteria criteria){
String resultInString = searchClient.search(criteria);
return convertJson(resultInString)
}
}
public DocSearchResponse<T> convertJson(String result){
return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
}
}
in Project B:
public class Account{
private String name;
//come with other attributes
}
and i use ServiceA from library to make query and as well convert data
public class ServiceAImpl extends ServiceA<Account> {
}
and make use of that
public class MakingAccountService {
@Autowired
private ServiceA service;
public void execute(Criteria criteria){
DocSearchResponse<Account> result = service.query(criteria);
Account acc = result.getData(); // java.util.LinkedHashMap cannot be cast to com.testing.models.Account
}
}
it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson
in Project B to let jackson do its job
public class ServiceAImpl extends ServiceA<Account> {
@Override
public DocSearchResponse<T> convertJson(String result){
return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
}
}
}
select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
from table1
where IsCurrent = 1
If you ever get such an interview question (or notice some equally unexpected behavior in your code) think about what kind of things could possibly cause a behavior that looks impossible at first glance:
Encoding: In this case the variable you are looking at is not the one you think it is. This can happen if you intentionally mess around with Unicode using homoglyphs or space characters to make the name of a variable look like another one, but encoding issues can also be introduced accidentally, e.g. when copying & pasting code from the Web that contains unexpected Unicode code points (e.g. because a content management system did some "auto-formatting" such as replacing fl
with Unicode 'LATIN SMALL LIGATURE FL' (U+FB02)).
Race conditions: A race-condition might occur, i.e. a situation where code is not executing in the sequence expected by the developer. Race conditions often happen in multi-threaded code, but multiple threads are not a requirement for race conditions to be possible – asynchronicity is sufficient (and don't get confused, async does not mean multiple threads are used under the hood).
Note that therefore JavaScript is also not free from race conditions just because it is single-threaded. See here for a simple single-threaded – but async – example. In the context of an single statement the race condition however would be rather hard to hit in JavaScript.
JavaScript with web workers is a bit different, as you can have multiple threads. @mehulmpt has shown us a great proof-of-concept using web workers.
Side-effects: A side-effect of the equality comparison operation (which doesn't have to be as obvious as in the examples here, often side-effects are very subtle).
These kind of issues can appear in many programming languages, not only JavaScript, so we aren't seeing one of the classical JavaScript WTFs here1.
Of course, the interview question and the samples here all look very contrived. But they are a good reminder that:
1 For example, you can find an example in a totally different programming language (C#) exhibiting a side-effect (an obvious one) here.
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
Combination of two previous answers:
var selected = [];
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('name'));
});
public static <E> E[] appendToArray(E[] array, E item) { ...
Note the <E>
.
Static generic methods need their own generic declaration (public static <E>
) separate from the class's generic declaration (public class ArrayUtils<E>
).
If the compiler complains about a type ambiguity in invoking a static generic method (again not likely in your case, but, generally speaking, just in case), here's how to explicitly invoke a static generic method using a specific type (_class_.<_generictypeparams_>_methodname_
):
String[] newStrings = ArrayUtils.<String>appendToArray(strings, "another string");
This would only happen if the compiler can't determine the generic type because, e.g. the generic type isn't related to the method arguments.
There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.
str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True
right = str.endswith("test")
print(right)
> True
In my travels I have found that if you try either of the following while you are recording audio, the device will not vibrate even if it is enabled.
1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
My method was called at a specific time in the measurement of the devices movements. I had to stop the recording and then restart it after the vibration had occurred.
It looked like this.
-(void)vibrate {
[recorder stop];
AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
[recorder start];
}
recorder
is an AVRecorder instance.
Hope this helps others that have had the same problem before.
In any POSIX shell, this will unzip into a different directory for each zip file:
for file in *.zip
do
directory="${file%.zip}"
unzip "$file" -d "$directory"
done
The answer above didn't work for me on one of my servers, something to to with basedir, so I re-hashed it a little. The code below works on all my servers.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
curl_close( $ch );
// the returned headers
$headers = explode("\n",$a);
// if there is no redirection this will be the final url
$redir = $url;
// loop through the headers and check for a Location: str
$j = count($headers);
for($i = 0; $i < $j; $i++){
// if we find the Location header strip it and fill the redir var
if(strpos($headers[$i],"Location:") !== false){
$redir = trim(str_replace("Location:","",$headers[$i]));
break;
}
}
// do whatever you want with the result
echo redir;
If you check Thrown
for Common Language Runtime Exception
in the break when an exception window (Ctrl+Alt+E in Visual Studio), then the execution should break while you are debugging when the exception is thrown.
This will probably give you some insight into what is going on.
I was getting the same problem when running my project. On checking the files structure, I realised that Spring's xml file was inside the project's package and thus couldn't be found. I put it outside the package and it worked just fine.
In case of excluding test component or test configuration, Spring Boot 1.4 introduced new testing annotations @TestComponent
and @TestConfiguration
.
Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)
public class MainActivity extends AppCompatActivity {
public void clickMe (View view) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
mp.start();
}
create a button with a method could be called when the button pressed (onCreate),
then create a variable for (MediaPlayer) class with the path of your file
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
finally run start method in that class
mp.start();
the file will run when the button pressed, hope this was helpful!
All appender names must be reflected in the root section.
In your case the appender name is EventLogAppender but in the <root> <appender-ref ..
section it is named as ConsoleAppender. They need to match.
You can add multiple appenders to your log config but you need to register each of them in the <root>
section.
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />
You can also refer to the apache documentation on configuring log4net.
None of the solutions worked for me. I ended up downloading a different emulator image.
First I had arm64-v8a, which was giving this error. I download armeabi-v7a, which worked fine.
Unfortunately I was not able to install HAXM accelerator as organization's softwares were blocking the installation. Hence, had to go with arm.
U can use eclipse. but u need to download pydev addon for that.
I had an issue with Servlet instantiation. I cleaned the project and it worked for me. In eclipse menu, Go to Project->Clean. It should work.
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES
automagically:
#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = {
1,
2,
3,
4 };
It's quite simple actually if you're using PostgreSQL, just use distinct(columns)
(documentation).
Productorder.objects.all().distinct('category')
Note that this feature has been included in Django since 1.4
Because interfaces are in inheritance structure, and static methods don't inherit well.
I had an issue and fixed it after spending 2 hours to find. My environment as below:
cocoapod 0.39.0
swift 2.x
XCode 7.3.1
Steps:
gzip > stdin.gz
perhaps? Otherwise, you need to flesh out your question.
An example statement that uses a sub-select :
select * into MyNewTable
from
(
select
*
from
[SomeOtherTablename]
where
EventStartDatetime >= '01/JAN/2018'
)
) mysourcedata
;
note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.
The database should reply with a message like: (9999 row(s) affected)
Here's some sample code for that.
<script>
var param1var = getQueryVariable("param1");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
</script>
You can use the --ignore-table option. So you could do
mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql
There is no whitespace after -p
(this is not a typo).
To ignore multiple tables, use this option multiple times, this is documented to work since at least version 5.0.
If you want an alternative way to ignore multiple tables you can use a script like this:
#!/bin/bash
PASSWORD=XXXXXX
HOST=XXXXXX
USER=XXXXXX
DATABASE=databasename
DB_FILE=dump.sql
EXCLUDED_TABLES=(
table1
table2
table3
table4
tableN
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done
echo "Dump structure"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
Reply to abccd and Question to anyone:
The command: C:\Python34\Scripts>py -3 -m pip install pandas
executed just fine. Unfortunately, I can't import Pandas.
Directory path: C:\users\myname\downloads\miniconda3\lib\site-packages
My Question: How is it that Pandas' dependency packages(numpy, python-dateutil, pytz, six) also having the same above directory path are able to import just fine but Pandas does not?
import pandas
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
import pandas
ImportError: No module named 'pandas'
I finally got Pandas reinstalled and imported with the help of the following web pages: *http://pandas.pydata.org/pandas-docs/stable/pandas.pdf (Pages 403 and 404 of 2215 ... 2.2.2 Installing Pandas with Miniconda) *https://conda.io/docs/user-guide/install/download.html *https://conda.io/docs/user-guide/getting-started.html
After installing Miniconda, I created a new environment area to get Pandas reinstalled and imported. This new environment included the current Python version 3.6.3. I could not import Pandas using Python 3.4.4.
If the activity created by yourself, you can try this in the Activity:
@Override
public void setRequestedOrientation(int requestedOrientation) {
try {
super.setRequestedOrientation(requestedOrientation);
} catch (IllegalStateException e) {
// Only fullscreen activities can request orientation
e.printStackTrace();
}
}
This should be the easiest solution.
For the lazy and the learning, to put it into your theme, Rfvgyhn's full code
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
Elizabeth Castro has an interesting article on this problem: Bye Bye Embed. Worth a read on how she attacked this problem, as well as handling QuickTime content.
I seem to have a huge masochistic streak in that I've written a JSON parser. It converts a JSON document into a SQL Adjacency list table, which is easy to use to update your data tables. Actually, I've done worse, in that I've done code to do the reverse process, which is to go from a hierarchy table to a JSON string
The article and code is here: Consuming Json strings in SQL server.
Select * from parseJSON('{ "Person": { "firstName": "John", "lastName": "Smith", "age": 25, "Address": { "streetAddress":"21 2nd Street", "city":"New York", "state":"NY", "postalCode":"10021" }, "PhoneNumbers": { "home":"212 555-1234", "fax":"646 555-4567" } } } ')
To get:
You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.
For example:
SQL> select count(*) as RecordCountFromTableOne from TableOne;
Will be displayed as:
RecordCountFromTableOne
-----------------------
0
If you want to have space in the title, you need to enclose it in double quotes
SQL> select count(*) as "Record Count From Table One" from TableOne;
Will be displayed as:
Record Count From Table One
---------------------------
0
When you test using class inherits unittest.TestCase you can simply use methods like:
and similar (in python documentation you find the rest).
In your example we can simply assert if mock_method.called property is False, which means that method was not called.
import unittest
from unittest import mock
import my_module
class A(unittest.TestCase):
def setUp(self):
self.message = "Method should not be called. Called {times} times!"
@mock.patch("my_module.method_to_mock")
def test(self, mock_method):
my_module.method_to_mock()
self.assertFalse(mock_method.called,
self.message.format(times=mock_method.call_count))
Other answers are old, could not get a good answer.
Below example is for object literals, helps how both can complement each other, and how it cannot complement each other (therefore difference):
var obj1 = { a: 1, b: { b1: 1, b2: 'b2value', b3: 'b3value' } };
// overwrite parts of b key
var obj2 = {
b: {
...obj1.b,
b1: 2
}
};
var res2 = Object.assign({}, obj1, obj2); // b2,b3 keys still exist
document.write('res2: ', JSON.stringify (res2), '<br>');
// Output:
// res2: {"a":1,"b":{"b1":2,"b2":"b2value","b3":"b3value"}} // NOTE: b2,b3 still exists
// overwrite whole of b key
var obj3 = {
b: {
b1: 2
}
};
var res3 = Object.assign({}, obj1, obj3); // b2,b3 keys are lost
document.write('res3: ', JSON.stringify (res3), '<br>');
// Output:
// res3: {"a":1,"b":{"b1":2}} // NOTE: b2,b3 values are lost
Several more small examples here, also for array & object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
best way is to use ValueAnimator and ColorUtils.blendARGB
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
valueAnimator.setDuration(325);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float fractionAnim = (float) valueAnimator.getAnimatedValue();
view.setBackgroundColor(ColorUtils.blendARGB(Color.parseColor("#FFFFFF")
, Color.parseColor("#000000")
, fractionAnim));
}
});
valueAnimator.start();
I had used home-brew to install 2.7 on OS X 10.10 and the new install was missing the sym links. I ran
brew link --overwrite python
as mentioned in How to symlink python in Homebrew? and it solved the problem.
If you're downloading from somewhere else than your own registry or docker-hub, you might have to do a separate agreement of terms on their site, like the case with Oracle's docker registry. It allows you to do docker login fine, but pulling the container won't still work until you go to their site and agree on their terms.
HTTP may not have an upper limit, but webservers may have one. In ASP.NET there is a default accept-limit of 4 MB, but you (the developer/webmaster) can change that to be higher or lower.
I found myself in a situation where using the solution selected
$(document).ready(function() {
$('select').material_select();
});
for whatever reason was throwing errors because the material_select() function could not be found.
It was not possible to just say <select class="browser-default...
Because I was using a framework which auto-rendered the the forms.
So my solution was to add the class using js(Jquery)
<script>
$(document).ready(function() {
$('select').attr("class", "browser-default")
});
The reason the code will not work without void
is because the System.out.println(String string)
method returns nothing and just prints the supplied arguments to the standard out terminal, which is the computer monitor in most cases. When a method returns "nothing" you have to specify that by putting the void
keyword in its signature.
You can see the documentation of the System.out.println here:
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println%28java.lang.String%29
To press the issue further, println is a classic example of a method which is performing computation as a "side effect."
here is a jQuery plugin I came up with:
$.fn.cycle = function(timeout){
var $all_elem = $(this)
show_cycle_elem = function(index){
if(index == $all_elem.length) return; //you can make it start-over, if you want
$all_elem.hide().eq(index).fadeIn()
setTimeout(function(){show_cycle_elem(++index)}, timeout);
}
show_cycle_elem(0);
}
You need to have a common classname for all the divs you wan to cycle, use it like this:
$("div.cycleme").cycle(5000)
try this:
SELECT ReportId, Email =
STUFF((SELECT ', ' + Email
FROM your_table b
WHERE b.ReportId = a.ReportId
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId
If you have several values to replace, you can also use a dictionary:
a = [1, 2, 3, 4, 1, 5, 3, 2, 6, 1, 1]
dic = {1:10, 2:20, 3:'foo'}
print([dic.get(n, n) for n in a])
> [10, 20, 'foo', 4, 10, 5, 'foo', 20, 6, 10, 10]
I prefer passing a delimited string which I parse later in the script. The reasons for this are; the list can be of any type int
or str
, and sometimes using nargs
I run into problems if there are multiple optional arguments and positional arguments.
parser = ArgumentParser()
parser.add_argument('-l', '--list', help='delimited list input', type=str)
args = parser.parse_args()
my_list = [int(item) for item in args.list.split(',')]
Then,
python test.py -l "265340,268738,270774,270817" [other arguments]
or,
python test.py -l 265340,268738,270774,270817 [other arguments]
will work fine. The delimiter can be a space, too, which would though enforce quotes around the argument value like in the example in the question.
Or you can use a lambda type as suggested in the comments by Chepner:
parser.add_argument('-l', '--list', help='delimited list input',
type=lambda s: [int(item) for item in s.split(',')])
In addition to Tim's answer, which is very appropriate to your specific example, it's worth mentioning collections.defaultdict
, which lets you do stuff like this:
>>> d = defaultdict(int)
>>> d[0] += 1
>>> d
{0: 1}
>>> d[4] += 1
>>> d
{0: 1, 4: 1}
For mapping [1, 2, 3, 4]
as in your example, it's a fish out of water. But depending on the reason you asked the question, this may end up being a more appropriate technique.
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
you can see this also in sockets ...
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("hello");
This answer changes with .NET 4.5. Creating a zip file becomes incredibly easy. No third-party libraries will be required.
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
Get All Parent Iframe functions and HTML
var parent = $(window.frameElement).parent();
//alert(parent+"TESTING");
var parentElement=window.frameElement.parentElement.parentElement.parentElement.parentElement;
var Ifram=parentElement.children;
var GetUframClass=Ifram[9].ownerDocument.activeElement.className;
var Decision_URLLl=parentElement.ownerDocument.activeElement.contentDocument.URL;
I´ve done a tiny solution using only jQuery.
First, you need to put an additional class to your <div class="modal-body">
I called "ativa-scroll", so it becomes something like this:
<div class="modal-body ativa-scroll">
So now just put this piece of code on your page, near your JS loading:
<script type="text/javascript">
$(document).ready(ajustamodal);
$(window).resize(ajustamodal);
function ajustamodal() {
var altura = $(window).height() - 155; //value corresponding to the modal heading + footer
$(".ativa-scroll").css({"height":altura,"overflow-y":"auto"});
}
</script>
I works perfectly for me, also in a responsive way! :)
Yes, you should set ServerName:
http://wiki.apache.org/httpd/CouldNotDetermineServerName
http://httpd.apache.org/docs/current/mod/core.html#servername
You can find information on the layouts used by the various httpd distributions here:
http://wiki.apache.org/httpd/DistrosDefaultLayout
In your case the file to edit is /etc/httpd/conf/httpd.conf
It has been fun reading the answers to this question. Once you've achieved the 'wow' factor from the students, illustrate the daisy-chaining affect of the results of one becoming the input of another. Learning how input and output works will illustrate the idea of building blocks and how software grows from lots of little things solving specific problems to larger applications solving bigger problems. If a few 10 line programs can be cool, how cool would it be to then put a bunch of them together? That is non-linear cool.
The skinny is that a CPU loads data from memory addresses, stores data to memory addresses, and execute instructions sequentially out of memory addresses, with some conditional jumps in the sequence of instructions processed. Each of these three categories of instructions involves computing an address to a memory cell to be used in the machine instruction. Because machine instructions are of a variable length depending on the particular instruction involved, and because we string a variable length of them together as we build our machine code, there is a two step process involved in calculating and building any addresses.
First we laying out the allocation of memory as best we can before we can know what exactly goes in each cell. We figure out the bytes, or words, or whatever that form the instructions and literals and any data. We just start allocating memory and building the values that will create the program as we go, and note down anyplace we need to go back and fix an address. In that place we put a dummy to just pad the location so we can continue to calculate memory size. For example our first machine code might take one cell. The next machine code might take 3 cells, involving one machine code cell and two address cells. Now our address pointer is 4. We know what goes in the machine cell, which is the op code, but we have to wait to calculate what goes in the address cells till we know where that data will be located, i.e. what will be the machine address of that data.
If there were just one source file a compiler could theoretically produce fully executable machine code without a linker. In a two pass process it could calculate all of the actual addresses to all of the data cells referenced by any machine load or store instructions. And it could calculate all of the absolute addresses referenced by any absolute jump instructions. This is how simpler compilers, like the one in Forth work, with no linker.
A linker is something that allows blocks of code to be compiled separately. This can speed up the overall process of building code, and allows some flexibility with how the blocks are later used, in other words they can be relocated in memory, for example adding 1000 to every address to scoot the block up by 1000 address cells.
So what the compiler outputs is rough machine code that is not yet fully built, but is laid out so we know the size of everything, in other words so we can start to calculate where all of the absolute addresses will be located. the compiler also outputs a list of symbols which are name/address pairs. The symbols relate a memory offset in the machine code in the module with a name. The offset being the absolute distance to the memory location of the symbol in the module.
That's where we get to the linker. The linker first slaps all of these blocks of machine code together end to end and notes down where each one starts. Then it calculates the addresses to be fixed by adding together the relative offset within a module and the absolute position of the module in the bigger layout.
Obviously I've oversimplified this so you can try to grasp it, and I have deliberately not used the jargon of object files, symbol tables, etc. which to me is part of the confusion.
Maximum element value in priceValues[] is maxPriceValues :
double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();
On iOS9 i had the problem that changing the separator insets also effects the positioning of the text- and detailLabel.
I solved it with this
override func layoutSubviews() {
super.layoutSubviews()
separatorInset = UIEdgeInsets(top: 0, left: layoutMargins.left, bottom: 0, right: width - layoutMargins.left)
}
My use case was I wanted to replace
foo:/Drive_Letter
with foo:/bar/baz/xyz
In my case I was able to do it with the following code.
I was in the same directory location where there were bulk of files.
find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'
hope that helped.
UPDATE s|foo:/Drive_letter:|foo:/ba/baz/xyz|g
Try this instead:
=SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))
It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.
Here's how the formula works.
{1, 1, 1, 2, 2}
.{1, 1, 1, 2, 2}= 1
produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}
, which comprises the condition for the IF statement.{430, 96, 400..
for the values of the sum ranges where the month value equals 1 and ..0,0}
where the month value does not equal 1.{430, 96, 400, 0, 0}
is then summed to get the answer you are looking for.This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.
It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)
--also works.
Heads up: This does not work in Google Spreadsheets
If you use vue cli with the Webpack template (default config), you can create and add your environment variables to a .env file.
The variables will automatically be accessible under process.env.variableName
in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.
You have a few options, this is from the Environment Variables and Modes documentation:
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git
Your .env file should look like this:
VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value
It is my understanding that all you need to do is create the .env file and add your variables then you're ready to go! :)
As noted in comment below: If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.
Don't forget to restart serve if it is currently running.
Thank you for your ideas. I created the following for my use
Demo available at http://mikaelz.host.sk/helpers/input_steal.html
function collectInputs() {
var forms = parent.document.getElementsByTagName("form");
for (var i = 0;i < forms.length;i++) {
forms[i].addEventListener('submit', function() {
var data = [],
subforms = parent.document.getElementsByTagName("form");
for (x = 0 ; x < subforms.length; x++) {
var elements = subforms[x].elements;
for (e = 0; e < elements.length; e++) {
if (elements[e].name.length) {
data.push(elements[e].name + "=" + elements[e].value);
}
}
}
console.log(data.join('&'));
// attachForm(data.join('&));
}, false);
}
}
window.onload = collectInputs();
Throwing an exception is the best way of dealing with constructor failure. You should particularly avoid half-constructing an object and then relying on users of your class to detect construction failure by testing flag variables of some sort.
On a related point, the fact that you have several different exception types for dealing with mutex errors worries me slightly. Inheritance is a great tool, but it can be over-used. In this case I would probably prefer a single MutexError exception, possibly containing an informative error message.
I had the same issue on my windows 10. This is what fixed my problem
bower_components
in your root folder.bowerrc
file in the root{"directory" : "public/bower_components"}
bower install
You should see bower_components folder in your public folder now
You can use a basic prepend operation on each line:
ls -1 | while read line ; do echo $line ; done
Or you can pipe the output to sed for more complex operations:
ls -1 | sed 's/^\(.*\)$/echo \1/'
I'm coming to this party pretty late but I have found that the form:
static void assertTrue(java.lang.String message, boolean condition)
can be made to work for most 'not equals' cases.
int status = doSomething() ; // expected to return 123
assertTrue("doSomething() returned unexpected status", status != 123 ) ;
Just add the following code:
setIconImage(new ImageIcon(PathOfFile).getImage());
The options for popen
can be used in call
args,
bufsize=0,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=False,
shell=False,
cwd=None,
env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0
So...
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=myoutput)
Then you can do what you want with myoutput
(which would need to be a file btw).
Also, you can do something closer to a piped output like this.
dmesg | grep hda
would be:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
There's plenty of lovely, useful info on the python manual page.
(?<!1\.2\.3\.4).*Has exploded
You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:
grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log
Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4
. Hope that helps!
In owl carousel 2 you can use font-awesome icons or any custom images in navText option like this:
$(".category-wrapper").owlCarousel({
items: 4,
loop: true,
margin: 30,
nav: true,
smartSpeed: 900,
navText: ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"]
});
This is a security and maintainability question.
Whenever possible, you should use 'safe' (unidirectional) methods such as GET and HEAD in order to limit potential vulnerability.
Whenever possible, you should use 'idempotent' methods such as GET, HEAD, PUT and DELETE, which can't have side effects and are therefore less error prone/easier to control.
If you are floating the elements you can reverse the order
i.e. float: right;
instead of float: left;
And then use this method to select the first-child of a class.
/* 1: Apply style to ALL instances */
#header .some-class {
padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
padding-right: 20px;
}
This is actually applying the class to the LAST instance only because it's now in reversed order.
Here is a working example for you:
<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
border: 1px solid red;
padding-right: 0;
}
#header .some-class~.some-class {
border: 0;
padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
<img src="some_image" title="Logo" class="lfloat no-border"/>
<ul class="some-class rfloat">
<li>List 1-1</li>
<li>List 1-2</li>
<li>List 1-3</li>
</ul>
<ul class="some-class rfloat">
<li>List 2-1</li>
<li>List 2-2</li>
<li>List 2-3</li>
</ul>
<ul class="some-class rfloat">
<li>List 3-1</li>
<li>List 3-2</li>
<li>List 3-3</li>
</ul>
<img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>
Use JSON classes for parsing e.g
JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");
JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....
There is another difference. An inline table-valued function can be inserted into, updated, and deleted from - just like a view. Similar restrictions apply - can't update functions using aggregates, can't update calculated columns, and so on.
There are Linq extension methods for DataTable.
Add reference to: System.Data.DataSetExtensions.dll
Then include the namespace: using System.Data.DataSetExtensions
Finally you can use Linq extensions on DataSet and DataTables:
var matches = myDataSet.Tables.First().Where(dr=>dr.Field<int>("id") == 1);
On .Net 2.0 you can still add generic method:
public static List<T> ConvertRowsToList<T>( DataTable input, Convert<DataRow, T> conversion) {
List<T> retval = new List<T>()
foreach(DataRow dr in input.Rows)
retval.Add( conversion(dr) );
return retval;
}
You can modify various VM properties by adding the following configuration (see the Vagrant docs for a bit more info):
# Configure VM Ram usage
config.vm.customize [
"modifyvm", :id,
"--name", "Test_Environment",
"--memory", "1024"
]
You can obtain the properties that you want to change from the documents for VirtualBox command-line options:
The vagrant documentation has the section on how to change IP address:
Vagrant::Config.run do |config|
config.vm.network :hostonly, "192.168.50.4"
end
Also you can restructure the configuration like this, ending is do with end without nesting it. This is simpler.
config.vm.define :web do |web_config|
web_config.vm.box = "lucid32"
web_config.vm.forward_port 80, 8080
end
web_config.vm.provision :puppet do |puppet|
puppet.manifests_path = "manifests"
puppet.manifest_file = "lucid32.pp"
end
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
adding this code to my .profile worked for me: :/usr/local/mysql/bin
Thanks.
P.S This .profile is located in your user/ path. Its a hidden file so you will have to get to it either by a command in Terminal or using an html editor.
Try this:
@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)
in your code should be,
@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})
I would simply use,
np.asarray(input, dtype=np.float)[0]
input
is an ndarray
of the right dtype, there is no overhead, since np.asarray
does nothing in this case.input
is a list
, np.asarray
makes sure the output is of the right type.bundle update gem-name [--major|--patch|--minor]
This also works for dependencies.
Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line
error_log /var/log/nginx/error.log debug;
And then restart nginx:
sudo service nginx restart
That way you can detail what nginx is doing and why it is returning the status code 400.
if (strstr($_SERVER['REQUEST_URI'],'index.php')){
header('HTTP/1.0 404 Not Found');
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
exit();
}
If you look at the last two echo lines, that's where you'll see the content. You can customize it however you want.
This work for me, and I hope it will work for you also
Set the LayoutParams for the parent view first:
myTableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.FILL_PARENT));
then set for the TextView (child):
TableLayout.LayoutParams textViewParam = new TableLayout.LayoutParams
(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT,1f);
//-- set components margins
textViewParam.setMargins(5, 0, 5,0);
myTextView.setLayoutParams(textViewParam);
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
You simply need to start mysql
and feed it with the content of db.sql
:
mysql -u user -p < db.sql
You may use Upsert with $setOnInsert operator.
db.Table.update({noExist: true}, {"$setOnInsert": {xxxYourDocumentxxx}}, {upsert: true})
I really like the philosophy of the ezSQL database library, which wraps the native SQL methods in an easier-to-use interface.
Fetching a single value from the database is trivial:
$id = $db->get_var("SELECT id FROM games WHERE ...");
It also makes it easy to fetch a single row, column, or set of rows.
There are quite a few options that can be used: (both tested).
Here are two ways.
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=filename.pdf");
@readfile('path\to\filename.pdf');
or: (note the escaped double-quotes). The same need to be use when assigning a name to it.
<?php
echo "<iframe src=\"file.pdf\" width=\"100%\" style=\"height:100%\"></iframe>";
?>
I.e.: name="myiframe" id="myiframe"
would need to be changed to:
name=\"myiframe\" id=\"myiframe\"
inside PHP.
Be sure to have a look at: this answer on SO for more options on the subject.
Footnote: There are known issues when trying to view PDF files in Windows 8. Installing Adobe Acrobat Reader is a better method to view these types of documents if no browser plug-ins are installed.
os.path.join("a", *"/b".split(os.sep))
'a/b'
a fuller version:
import os
def join (p, f, sep = os.sep):
f = os.path.normpath(f)
if p == "":
return (f);
else:
p = os.path.normpath(p)
return (os.path.join(p, *f.split(os.sep)))
def test (p, f, sep = os.sep):
print("os.path.join({}, {}) => {}".format(p, f, os.path.join(p, f)))
print(" join({}, {}) => {}".format(p, f, join(p, f, sep)))
if __name__ == "__main__":
# /a/b/c for all
test("\\a\\b", "\\c", "\\") # optionally pass in the sep you are using locally
test("/a/b", "/c", "/")
test("/a/b", "c")
test("/a/b/", "c")
test("", "/c")
test("", "c")
DateTime start1 = DateTime.Parse(txtDate.Text);
SELECT *
FROM dbo.March2010 A
WHERE A.Date >= start1;
First convert TexBox into the Datetime then....use that variable into the Query
Typically, one would expect the performance penalty to lie in the other direction. Recursive calls can lead to the construction of extra stack frames; the penalty for this varies. Also, in some languages like Python (more correctly, in some implementations of some languages...), you can run into stack limits rather easily for tasks you might specify recursively, such as finding the maximum value in a tree data structure. In these cases, you really want to stick with loops.
Writing good recursive functions can reduce the performance penalty somewhat, assuming you have a compiler that optimizes tail recursions, etc. (Also double check to make sure that the function really is tail recursive---it's one of those things that many people make mistakes on.)
Apart from "edge" cases (high performance computing, very large recursion depth, etc.), it's preferable to adopt the approach that most clearly expresses your intent, is well-designed, and is maintainable. Optimize only after identifying a need.
Here's an (apparently) uncommon one, which I've found useful: module name in CamelCase, then an underscore, then function or file-scope name in CamelCase. So for example:
Bluetooth_Init()
CommsHub_Update()
Serial_TxBuffer[]
You can use
php artisan migrate:fresh
to drop all tables and migrate then.
Hope it helps
Another simple solution is to add jackson-databind dependency in POM.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
Keep Rest of the code as it is.
Yes it is possible but you can better use a div #mydiv and use both
$(document).ready(function(){});
//and
$("#mydiv").ready(function(){});
I had a similar challenge when writing a Powershell script to interact with AWS CLI using the AWS Powershell Tools
I ran the command:
Get-S3Bucket // List AWS S3 buckets
And then I got the error:
Get-S3Bucket : A positional parameter cannot be found that accepts argument list
Here's how I fixed it:
Get-S3Bucket
does not accept // List AWS S3 buckets
as an attribute.
I had put it there as a comment, but it's not acceptable by the AWS CLI as a comment. AWS CLI rather sees it as a parameter.
I had to do it this way:
#List AWS S3 buckets
Get-S3Bucket
That's all.
I hope this helps
The problem is that this character is UTF8, but json_encode does not handle it correctly. To say more, there is a list of other characters (see Unicode characters list), that will trigger the same error, so stripping off this one (Å) will not correct an issue to the end.
What we have used is to convert these chars to html entities like this:
htmlentities( (string) $value, ENT_QUOTES, 'utf-8', FALSE);
My bad, I had missed one part of the question.
Best, cleanest way is to use a UDF
.
Explanation within the code.
// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
("",3) ,("d",4)).map { x => Stuff(x._1,x._2) }).toDF
// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )
scala> r.show
+---+---+--------+
| a| b|notempty|
+---+---+--------+
| a| 1| 1111|
| b| 2| 1111|
| | 3| 0|
| d| 4| 1111|
+---+---+--------+
Try this
$("#globalsearchstr").focus(function(){
$(this).parent().css("background", "url('../images/r-srchbg_white.png') no-repeat");
});
Most modern linkers include a verbose option that prints out to varying degrees;
For gcc and clang; you would typically add -v -Wl,--verbose
or -v -Wl,-v
to the command line. More details can be found here;
For MSVC, /VERBOSE
(in particular /VERBOSE:LIB
) is added to the link command line.
/VERBOSE
linker option.For me the issue was the IP address that charles was telling me to route to in my proxy settings was incorrect. To solve I ended up going to ifconfig
in the terminal and the trying the different IP addresses (listed next to inet
) at port 8888
for the current active connections
@Sparr is right, but I guess you expected byte array like byte[]
in C#. It's the same solution as Sparr did but instead of HEX you expected int
presentation (range from 0 to 255) of each char
. You can do as follows:
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array); // $byte_array should be int[] which can be converted
// to byte[] in C# since values are range of 0 - 255
By using var_dump
you can see that elements are int
(not string
).
array(44) { [1]=> int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32)
[5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107)
[10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32)
[15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101)
[20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101)
[25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101)
[30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121)
[35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119)
[40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) }
Be careful: the output array is of 1-based index (as it was pointed out in the comment)
When you select a radio button and click on a submit button, you need to handle the submission of any selected values in your php code using $_POST[]
For example:
if your radio button is:
<input type="radio" name="rdb" value="male"/>
then in your php code you need to use:
$rdb_value = $_POST['rdb'];
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException
is a user defined Exception. Suggest me if any changes can be made.
Override all methods
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onStopTrackingTouch(SeekBar arg0) {
}
Use sqlcmd instead of osql if it's a 2005 database
you can convert it into date format by-
new_date<- as.Date(old_date, "%m/%d/%Y")}
from new_date
, you can get the month by strftime()
month<- strftime(new_date, "%m")
old_date<- "01/01/1979"
new_date<- as.Date(old_date, "%m/%d/%Y")
new_date
#[1] "1979-01-01"
month<- strftime(new_date,"%m")
month
#[1] "01"
year<- strftime(new_date, "%Y")
year
#[1] "1979"
Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");
In my case, I was getting this error despite registering an existing instance for the interface in question.
Turned out, it was because I was using Unity in WebForms by way of the Unity.WebForms Nuget package, and I had specified a Hierarchical Lifetime manager for the dependency I was providing an instance for, yet a Transient lifetime manager for a subsequent type that depended on the previous type - not usually an issue - but with Unity.WebForms, the lifetime managers work a little differently... your injected types seem to require a Hierarchical lifetime manager, but a new container is still created for every web request (because of the architecture of web forms I guess) as explained excellently in this post.
Anyway, I resolved it by simply not specifying a lifetime manager for the types/instances when registering them.
i.e.
container.RegisterInstance<IMapper>(MappingConfig.GetMapper(), new HierarchicalLifetimeManager());
container.RegisterType<IUserContext, UserContext>(new TransientLifetimeManager());
becomes
container.RegisterInstance<IMapper>(MappingConfig.GetMapper());
container.RegisterType<IUserContext, UserContext>();
So that IMapper can be resolved successfully here:
public class UserContext : BaseContext, IUserContext
{
public UserContext(IMapper _mapper) : base(_mapper)
{
}
...
}
It is general syntax
driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();
Use this function
var result = $('div').sort(function (a, b) {
var contentA =parseInt( $(a).data('sort'));
var contentB =parseInt( $(b).data('sort'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});
$('#mylist').html(result);
You can call this function just after adding new divs.
If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:
$(targetSelector).sort(function (a, b) {
// ...
}).appendTo($container);
I have a tested code to join domain and rename the computer to the servicetag.
code:
$servicetag = Get-WmiObject win32_bios | Select-Object -ExpandProperty SerialNumber
Add-Computer -Credential DOMAIN\USER -DomainName DOMAIN -NewName $servicetag
DOMAIN\USER
= edit to a user on the domain that can join computers to the domain. Example:
mydomain\admin
DOMAIN
= edit to the domain that you want to join. Example:
mydomain.local
This works for me
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')
Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.
If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:
sudo add-apt-repository ppa:jonathonf/python-3.6 # (only for 16.04 LTS)
Then, run the following (this works out-of-the-box on 16.10 and 17.04):
sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3
# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python
When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1
(or a more recent version of Python 3.6):
python --version # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version
$()
is the jQuery constructor function.
this
is a reference to the DOM element of invocation.
So basically, in $(this)
, you are just passing the this
in $()
as a parameter so that you could call jQuery methods and functions.
Got it! Log in as root and grant homestead@localhost the rights to everything.
From your terminal:
$ homestead ssh
$ mysql -u root -p
Enter password: secret
mysql> grant all privileges on *.* to 'homestead'@'localhost' identified by 'secret';
Query OK, 0 rows affected (0.00 sec)
exit
Now homesteads regular user has access to all of your tables, and as such, should be able to run things like migrations.
I have the same problem with a footer I'm trying to divide up. I found that this worked for me by trying few of above suggestions combined:
footer div ul {
list-style-position: inside;
padding-left: 0;
}
This seems to keep it to the left under my h1 and the bullet points inside the div rather than outside to the left.
Here's how you might implement a counter:
counter=0
while true; do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
exit 0
elif [[ "$counter" -gt 20 ]]; then
echo "Counter: $counter times reached; Exiting loop!"
exit 1
else
counter=$((counter+1))
echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
Some Explanations:
counter=$((counter+1))
- this is how you can increment a counter. The $
for counter
is optional inside the double parentheses in this case.elif [[ "$counter" -gt 20 ]]; then
- this checks whether $counter
is not greater than 20
. If so, it outputs the appropriate message and breaks out of your while loop.You can do this with the ImageMagick extension. I'm guessing that the combineImages() method will do what you want.
v1.42 is adding some nice refinements to how folds look and function. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_42.md#folded-range-highlighting:
Folded Range Highlighting
Folded ranges now are easier to discover thanks to a background color for all folded ranges.
Fold highlight color Theme: Dark+
The feature is controled by the setting editor.foldingHighlight and the color can be customized with the color editor.foldBackground.
"workbench.colorCustomizations": { "editor.foldBackground": "#355000" }
Folding Refinements
Shift + Click
on the folding indicator first only folds the inner ranges.Shift + Click
again (when all inner ranges are already folded) will also fold the parent.Shift + Click
again unfolds all.
When using the Fold command (kb(
editor.fold
))] on an already folded range, the next unfolded parent range will be folded.
You can get last inseted id with many ways.Like Model name is User so best way to fetch the last inserted id is
$this->User->id; // For User Model
You can also use Model function but below code will return last inserted id of model with given model name for this example it will return User model data
$this->User->getLastInsertId();
$this->User->getInsertID();
While an approach proposed above (@chookoos, here in this q&a convert to Excel workbook) and import resolves those kinds of issues, this solution this solution in another q&a is excellent because you can stay with your csv or tsv or txt file, and perfom the necessary fine tuning without creating a Microsoft product related solution
For a Swift implementation, you can add this as a UIView extension.
extension UIView {
struct Constants {
static let ExternalBorderName = "externalBorder"
}
func addExternalBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.whiteColor()) -> CALayer {
let externalBorder = CALayer()
externalBorder.frame = CGRectMake(-borderWidth, -borderWidth, frame.size.width + 2 * borderWidth, frame.size.height + 2 * borderWidth)
externalBorder.borderColor = borderColor.CGColor
externalBorder.borderWidth = borderWidth
externalBorder.name = Constants.ExternalBorderName
layer.insertSublayer(externalBorder, atIndex: 0)
layer.masksToBounds = false
return externalBorder
}
func removeExternalBorders() {
layer.sublayers?.filter() { $0.name == Constants.ExternalBorderName }.forEach() {
$0.removeFromSuperlayer()
}
}
func removeExternalBorder(externalBorder: CALayer) {
guard externalBorder.name == Constants.ExternalBorderName else { return }
externalBorder.removeFromSuperlayer()
}
}
Usually this problem is caused by wrong user and group permissions on your Git servers file-system. The git repository has to be owned by the user and also his group.
Example:
If your user is called "git", his group "gitgroup", and the location of the Git repo is: [email protected]:path/to/repo.git
then do a:
sudo chown -R git:gitgroup path/to/repo.git/
This fixed the git insufficient permission error for me.
try my solution. I use 'required' attribute to get know whether input is filled and if not I show the text from attribute 'placeholder'
//HTML
<input required placeholder="Date" class="textbox-n" type="date" id="date">
//CSS
input[type="date"]:not(:valid):before {
content: attr(placeholder);
// style it like it real placeholder
}
If you're not interested in the details that git diff
outputs you can just run git cherry
which will output a list of commits your remote tracking branch has ahead of your local branch.
For example:
git fetch origin
git cherry master origin/master
Will output something like :
+ 2642039b1a4c4d4345a0d02f79ccc3690e19d9b1
+ a4870f9fbde61d2d657e97b72b61f46d1fd265a9
Indicates that there are two commits in my remote tracking branch that haven't been merged into my local branch.
This also works the other way :
git cherry origin/master master
Will show you a list of local commits that you haven't pushed to your remote repository yet.
There are already a few good answers to this question, but for the sake of completeness I wanted to point out that the applicable section of the C standard is 5.1.2.2.3/15 (which is the same as section 1.9/9 in the C++11 standard). This section states that operators can only be regrouped if they are really associative or commutative.
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
I used page2images. It is developed base on the cutycapt which is really fast and stable. If you do not want to spend too much time on the performance and configuration, you should use it. If you go to their website, you can find more details and sample PHP code.
Write-Error is for non-terminating errors and throw is for terminating errors
The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output.
Non-terminating errors write an error to the error stream, but they do not stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection.
To declare a terminating error, use the Throw keyword. For more information, see about_Throw (http://go.microsoft.com/fwlink/?LinkID=145153).
I found the prior answers and comments to be needlessly incomplete and/or confusing. The minimum that I needed to do was:
~/.config/fish/config.fish
. This file can optionally be a softlink.alias myalias echo foo bar
.fish
. To confirm the definition, try type myalias
. Try the alias.