You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).
Your code could be like:
const myArray = [
{
"id":25,
"name":"Anakin Skywalker",
"createdAt":"2017-04-12T12:48:55.000Z",
"updatedAt":"2017-04-12T12:48:55.000Z"
},
{
"id":1,
"name":"Luke Skywalker",
"createdAt":"2017-04-12T11:25:03.000Z",
"updatedAt":"2017-04-12T11:25:03.000Z"
}
]
const myOrderedArray = _.sortBy(myArray, o => o.name)
Very sort cut and effective solution is below:-
Add the below rule in your tsconfig.json file:-
"noImplicitAny": false
Then restart your project.
There's no need to fiddle around with ssh configurations. Use a configuration file (not a Dockerfile) that contains environment variables, and have a shell script update your docker file at runtime. You keep tokens out of your Dockerfiles and you can clone over https (no need to generate or pass around ssh keys).
Go to Settings > Personal Access Tokens
repo
scope enabled.git clone https://[email protected]/user-or-org/repo
Some commenters have noted that if you use a shared Dockerfile, this could expose your access key to other people on your project. While this may or may not be a concern for your specific use case, here are some ways you can deal with that:
sed
or similar, i.e. calling the script with sh rundocker.sh MYTOKEN=foo
which would replace on https://{{MY_TOKEN}}@github.com/user-or-org/repo
. Note that you could also use a configuration file (in .yml or whatever format you want) to do the same thing but with environment variables.Factory
and Service
is a just wrapper of a provider
.
Factory
Factory
can return anything which can be a class(constructor function)
, instance of class
, string
, number
or boolean
. If you return a constructor
function, you can instantiate in your controller.
myApp.factory('myFactory', function () {
// any logic here..
// Return any thing. Here it is object
return {
name: 'Joe'
}
}
Service
Service does not need to return anything. But you have to assign everything in this
variable. Because service will create instance by default and use that as a base object.
myApp.service('myService', function () {
// any logic here..
this.name = 'Joe';
}
Actual angularjs code behind the service
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
It just a wrapper around the factory
. If you return something from service
, then it will behave like Factory
.
IMPORTANT
: The return result from Factory and Service will be cache and same will be returned for all controllers.
When should i use them?
Factory
is mostly preferable in all cases. It can be used when you have constructor
function which needs to be instantiated in different controllers.
Service
is a kind of Singleton
Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application.
Eg: Authenticated user details.
For further understanding, read
http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
The problem is that you forgot to import os. Add this line of code:
import os
And everything should be fine. Hope this helps!
This can be done by using SUMPRODUCT
as well. Update the ranges as you see fit
=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)
A2:A7 = First name range
B2:B7 = Last Name Range
C2:C7 = Numbers Range
This will find all the names with the same first and last name and sum the numbers in your numbers column
To really get this clear, here's my for-beginners answer:
You inputed the arguments in the wrong order.
A keyword argument has this style:
nullable=True, unique=False
A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:
name="Ricardo", fruit="chontaduro"
This syntax error asks you to first put name="Ricardo"
and all of its kind (non-keyword) before those like nullable=True.
Based on @AlecRust idea, I did an implementation of png text service.
The demo is here:
http://lingtalfi.com/services/pngtext?color=cc0000&size=10&text=Hello%20World
There are four parameters:
Please do not use this service directly (except for testing), but use the class I created that provides the service:
https://github.com/lingtalfi/WebBox/blob/master/Image/PngTextUtil.php
class PngTextUtil
{
/**
* Displays a png text.
*
* Note: this method is meant to be used as a webservice.
*
* Options:
* ------------
* - font: string = arial/Arial.ttf
* The font to use.
* If the path starts with a slash, it's an absolute path to the font file.
* Else if the path doesn't start with a slash, it's a relative path to the font directory provided
* by this class (the WebBox/assets/fonts directory in this repository).
* - fontSize: int = 12
* The font size.
* - color: string = 000000
* The color of the text in hexadecimal format (6 chars).
* This can optionally be prefixed with a pound symbol (#).
*
*
*
*
*
*
* @param string $text
* @param array $options
* @throws \Bat\Exception\BatException
* @throws WebBoxException
*/
public static function displayPngText(string $text, array $options = []): void
{
if (false === extension_loaded("gd")) {
throw new WebBoxException("The gd extension is not loaded!");
}
header("Content-type: image/png");
$font = $options['font'] ?? "arial/Arial.ttf";
$fontsize = $options['fontSize'] ?? 12;
$hexColor = $options['color'] ?? "000000";
if ('/' !== substr($font, 0, 1)) {
$fontDir = __DIR__ . "/../assets/fonts";
$font = $fontDir . "/" . $font;
}
$rgbColors = ConvertTool::convertHexColorToRgb($hexColor);
//--------------------------------------------
// GET THE TEXT BOX DIMENSIONS
//--------------------------------------------
$charWidth = $fontsize;
$charFactor = 1;
$textLen = mb_strlen($text);
$imageWidth = $textLen * $charWidth * $charFactor;
$imageHeight = $fontsize;
$logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
imagealphablending($logoimg, false);
imagesavealpha($logoimg, true);
$col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
imagefill($logoimg, 0, 0, $col);
$white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]); //for font color
$x = 0;
$y = $fontsize;
$angle = 0;
$bbox = imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text); //fill text in your image
$boxWidth = $bbox[4] - $bbox[0];
$boxHeight = $bbox[7] - $bbox[1];
imagedestroy($logoimg);
//--------------------------------------------
// CREATE THE PNG
//--------------------------------------------
$imageWidth = abs($boxWidth);
$imageHeight = abs($boxHeight);
$logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
imagealphablending($logoimg, false);
imagesavealpha($logoimg, true);
$col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
imagefill($logoimg, 0, 0, $col);
$white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]); //for font color
$x = 0;
$y = $fontsize;
$angle = 0;
imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text); //fill text in your image
imagepng($logoimg); //save your image at new location $target
imagedestroy($logoimg);
}
}
Note: if you don't use the universe framework, you will need to replace this line:
$rgbColors = ConvertTool::convertHexColorToRgb($hexColor);
With this code:
$rgbColors = sscanf($hexColor, "%02x%02x%02x");
In which case your hex color must be exactly 6 chars long (don't put the hash symbol (#) in front of it).
Note: in the end, I did not use this service, because I found that the font was ugly and worse: it was not possible to select the text. But for the sake of this discussion I thought this code was worth sharing...
Please try this, if you want to fetch first/last.
{{#each list}}
{{#if @first}}
<div class="active">
{{else}}
<div>
{{/if}}
{{/each}}
{{#each list}}
{{#if @last}}
<div class="last-element">
{{else}}
<div>
{{/if}}
{{/each}}
For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:
First, you need to link against QuickLook.framework
and #import
<QuickLook/QuickLook.h>;
Afterwards, in either viewDidLoad
or any of the lazy initialization methods:
QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];
I'm having a very similar problem. In the past, this has been related to serialization problems. If you are still having this problem, can you verify that you can correctly serialize the objects you are returning. Specifically, if you are using Linq-To-Sql objects that have relationships, there are known serialization problems if you put a back reference on a child object to the parent object and mark that back reference as a DataMember.
You can verify serialization by writing a console app that serializes and deserializes your objects using the DataContractSerializer on the server side and whatever serialization methods your client uses. For example, in our current application, we have both WPF and Compact Framework clients. I wrote a console app to verify that I can serialize using a DataContractSerializer and deserialize using an XmlDesserializer. You might try that.
Also, if you are returning Linq-To-Sql objects that have child collections, you might try to ensure that you have eagerly loaded them on the server side. Sometimes, because of lazy loading, the objects being returned are not populated and may cause the behavior you are seeing where the request is sent to the service method multiple times.
If you have solved this problem, I'd love to hear how because I'm stuck with it too. I have verified that my issue is not serialization so I'm at a loss.
UPDATE: I'm not sure if it will help you any but the Service Trace Viewer Tool just solved my problem after 5 days of very similar experience to yours. By setting up tracing and then looking at the raw XML, I found the exceptions that were causing my serialization problems. It was related to Linq-to-SQL objects that occasionally had more child objects than could be successfully serialized. Adding the following to your web.config file should enable tracing:
<sharedListeners>
<add name="sharedListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\Temp\servicetrace.svclog" />
</sharedListeners>
<sources>
<source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" >
<listeners>
<add name="sharedListener" />
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
<listeners>
<add name="sharedListener" />
</listeners>
</source>
</sources>
The resulting file can be opened with the Service Trace Viewer Tool or just in IE to examine the results.
I use org.reflections:
Reflections reflections = new Reflections("com.mycompany");
Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);
Another example:
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Reflections reflections = new Reflections("java.util");
Set<Class<? extends List>> classes = reflections.getSubTypesOf(java.util.List.class);
for (Class<? extends List> aClass : classes) {
System.out.println(aClass.getName());
if(aClass == ArrayList.class) {
List list = aClass.newInstance();
list.add("test");
System.out.println(list.getClass().getName() + ": " + list.size());
}
}
}
Its Really Easy. "In Design mode FORM" (form1.cs[Design]) copy the whole Form "ctrl A" then ctrl C. All objects at once. Then add a new windows form to the project. Change the size of the form to the size that you want then paste ctrl V all of the new objects will be copied to the new form. When they are all still picked double click on any of the objects. NOT THE FORM!!!..... This will create the code on the Form side matching the objects you just pasted. if it doesn't you can double click on each object and it will create the code one at a time. I use a text box area to double click in and it works almost every time. I use this method everyday WORKS GREAT.
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
The official way to disable the popup is this:
Pack your extension: go to chrome://extensions
, check Developer mode and click Pack extension
Install the extension by dragging and dropping the .crx
file into the chrome://extensions
page.
You'll get an "Unsupported extensions disabled" popup if you try restarting Chrome at this point.
Then for Windows 7 or Windows 8:
[zip]\windows\admx\chrome.admx
to c:\windows\policydefinitions
[zip]\windows\admx\[yourlanguage]\chrome.adml
to c:\windows\policydefinitions\[yourlanguage]\chrome.adml
(not c:\windows\[yourlanguage]
)chrome://extensions
gpedit.msc
and hit enter.That's it!
Chrome Version 69.0.3497.100 (Official Build) (64-bit)
:Temporarily enable Developer mode in chrome://extensions
Uninstall the extension that causes the popup using the Load unpacked.
Click on Pack extension, and find and select the folder containing the extension files. Don't enter the private key file if you don't have it.
Click Pack extension. A .crx
and .pem
file will be created near the root directory of the extension. Install the extension using the .crx
file and keep the .pem
file safe.
Copy the .crx
installed extension ID to the whitelist and restart Chrome.
The popup should be gone.
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
class myThread (threading.Thread):
def __init__(self, threadID, fileName, directory, origin):
threading.Thread.__init__(self)
self.threadID = threadID
self.fileName = fileName
self.daemon = True
self.dir = directory
self.originalFile = origin
def run(self):
startMonitor(self.fileName, self.dir, self.originalFile)
def startMonitor(fileMonitoring,dirPath,originalFile):
hDir = win32file.CreateFile (
dirPath,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
# Wait for new data and call ProcessNewData for each new chunk that's
# written
while 1:
# Wait for a change to occur
results = win32file.ReadDirectoryChangesW (
hDir,
1024,
False,
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
None,
None
)
# For each change, check to see if it's updating the file we're
# interested in
for action, file_M in results:
full_filename = os.path.join (dirPath, file_M)
#print file, ACTIONS.get (action, "Unknown")
if len(full_filename) == len(fileMonitoring) and action == 3:
#copy to main file
...
You can use the key
parameter to list.sort()
:
my_list.sort(key=lambda x: x[1])
or, slightly faster,
my_list.sort(key=operator.itemgetter(1))
(As with any module, you'll need to import operator
to be able to use it.)
default_keys = [1, "name"]
To get dictionary with None as values:
dict.fromkeys(default_keys)
Output :
{1: None, 'name': None}
To get dictionary with default values:
dict.fromkeys(default_keys, [])
Output :
{1: [], 'name': []}
For Mac Yosemite,
JDK 1.7.0_xx is using
$ ls -ltar /usr/bin/java
/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.7.0_xx.jdk/Contents/Home
I believe you're not fully understanding how pointers work.
When you have a pointer pointing to some memory there are three different things you must understand:
- there is "what is pointed" by the pointer (the memory)
- this memory address
- not all pointers need to have their memory deleted: you only need to delete memory that was dynamically allocated (used new
operator).
Imagine:
int *ptr = new int;
// ptr has the address of the memory.
// at this point, the actual memory doesn't have anything.
*ptr = 8;
// you're assigning the integer 8 into that memory.
delete ptr;
// you are only deleting the memory.
// at this point the pointer still has the same memory address (as you could
// notice from your 2nd test) but what inside that memory is gone!
When you did
ptr = NULL;
// you didn't delete the memory
// you're only saying that this pointer is now pointing to "nowhere".
// the memory that was pointed by this pointer is now lost.
C++ allows that you try to delete
a pointer that points to null
but it doesn't actually do anything, just doesn't give any error.
I had to make SQL scripts often and add them to source control and send them to DBA. I used this ExcelIntoSQL App from windows store https://www.microsoft.com/store/apps/9NH0W51XXQRM It creates complete script with "CREATE TABLE" and INSERTS.
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Static memory allocation. Memory allocated will be in stack.
int a[10];
Dynamic memory allocation. Memory allocated will be in heap.
int *a = malloc(sizeof(int) * 10);
and the latter should be freed since there is no Garbage Collector(GC) in C.
free(a);
Simple Alternative
Just use a query string.
Routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Controller
public class TestController : ApiController
{
public IEnumerable<SomeViewModel> Get()
{
}
public SomeViewModel GetById(int objectId)
{
}
}
Requests
GET /Test
GET /Test?objectId=1
Note
Keep in mind that the query string param should not be "id" or whatever the parameter is in the configured route.
So, let's say you have this table:
CREATE TABLE YourTable(Col1 VARCHAR(10))
And you want to change Col1
to VARCHAR(20)
. What you need to do is this:
ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)
That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5)
, then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE
will fail.
Simply you can put a back slash in front of your css link
select index_name, column_name
from user_ind_columns
where table_name = 'NAME';
OR use this:
select TABLE_NAME, OWNER
from SYS.ALL_TABLES
order by OWNER, TABLE_NAME
And for Indexes:
select INDEX_NAME, TABLE_NAME, TABLE_OWNER
from SYS.ALL_INDEXES
order by TABLE_OWNER, TABLE_NAME, INDEX_NAME
package main
import "fmt"
func main() {
var x float64 = 5.7
var y int = int(x)
fmt.Println(y) // outputs "5"
}
Put following line into your ".profile" file.
Open .profile file and copy this line
find ~/ -name '.DS_Store' -delete
When you open terminal window it will automatically delete your .DS_Store file for you.
I've been facing this problem for long but what this solves my problem Go inside the tsconfig.json and add the following under compilerOptions
{
"compilerOptions": {
...
"allowJs": true
...
}
}
Everyone knows (hopefully) its bad to terminate thread. The problem is when you don't own a piece of code you're calling. If this code is running in some do/while infinite loop , itself calling some native functions, etc. you're basically stuck. When this happens in your own code termination, stop or Dispose call, it's kinda ok to start shooting the bad guys (so you don't become a bad guy yourself).
So, for what it's worth, I've written those two blocking functions that use their own native thread, not a thread from the pool or some thread created by the CLR. They will stop the thread if a timeout occurs:
// returns true if the call went to completion successfully, false otherwise
public static bool RunWithAbort(this Action action, int milliseconds) => RunWithAbort(action, new TimeSpan(0, 0, 0, 0, milliseconds));
public static bool RunWithAbort(this Action action, TimeSpan delay)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
var source = new CancellationTokenSource(delay);
var success = false;
var handle = IntPtr.Zero;
var fn = new Action(() =>
{
using (source.Token.Register(() => TerminateThread(handle, 0)))
{
action();
success = true;
}
});
handle = CreateThread(IntPtr.Zero, IntPtr.Zero, fn, IntPtr.Zero, 0, out var id);
WaitForSingleObject(handle, 100 + (int)delay.TotalMilliseconds);
CloseHandle(handle);
return success;
}
// returns what's the function should return if the call went to completion successfully, default(T) otherwise
public static T RunWithAbort<T>(this Func<T> func, int milliseconds) => RunWithAbort(func, new TimeSpan(0, 0, 0, 0, milliseconds));
public static T RunWithAbort<T>(this Func<T> func, TimeSpan delay)
{
if (func == null)
throw new ArgumentNullException(nameof(func));
var source = new CancellationTokenSource(delay);
var item = default(T);
var handle = IntPtr.Zero;
var fn = new Action(() =>
{
using (source.Token.Register(() => TerminateThread(handle, 0)))
{
item = func();
}
});
handle = CreateThread(IntPtr.Zero, IntPtr.Zero, fn, IntPtr.Zero, 0, out var id);
WaitForSingleObject(handle, 100 + (int)delay.TotalMilliseconds);
CloseHandle(handle);
return item;
}
[DllImport("kernel32")]
private static extern bool TerminateThread(IntPtr hThread, int dwExitCode);
[DllImport("kernel32")]
private static extern IntPtr CreateThread(IntPtr lpThreadAttributes, IntPtr dwStackSize, Delegate lpStartAddress, IntPtr lpParameter, int dwCreationFlags, out int lpThreadId);
[DllImport("kernel32")]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32")]
private static extern int WaitForSingleObject(IntPtr hHandle, int dwMilliseconds);
You can see which version gets executed when you load the page with Google Chrome + developer tools (preinstalled) or Firefox + Firebug (add-on).
I use Google Chrome:
It looks like this:
The easiest answer is to just use the cors package.
const cors = require('cors');
const app = require('express')();
app.use(cors());
That will enable CORS across the board. If you want to learn how to enable CORS without outside modules, all you really need is some Express middleware that sets the 'Access-Control-Allow-Origin' header. That's the minimum you need to allow cross-request domains from a browser to your server.
app.options('*', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
res.send('ok');
});
app.use((req, res) => {
res.set('Access-Control-Allow-Origin', '*');
});
As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.
foreach (var tempClass in macroClasses)
{
// using reflection I will be able to run the method as:
tempClass.GetMethod("Run").Invoke(null, null);
}
As the comment points out, you may want to ensure the method is static when calling GetMethod
:
tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
Use the following steps for setup
Download from Flutter SDK for Mac https://flutter.dev/docs/get-started/install/macos
Extract the Flutter SDK zip (saved in Downloads) file using terminal. If you want to extract the Flutter SDK in fluttrerDevelopment folder
$ cd ~/fluttrerDevelopment
$ unzip ~/Downloads/flutter_macos_1.20.1-stable.zip
Add the flutter tool to your path:
$ export PATH=“$PATH:pwd
/flutter/bin"
If you have only Xcode setup in your machine then run
$ flutter create my_first_flutter_app
$ cd my_first_flutter_app
$ flutter run
Npm now provides unlimited private hosted modules for $7/user/month used like so
cd private-project
npm login
in your package json set "name": " @username/private-project"
npm publish
then to require your project:
cd ../new-project
npm install --save @username/private-project
Just declare the enum outside the bounds of the class. Like this:
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
...
}
Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
__all__
is very good - it helps guide import statements without automatically importing modules
http://docs.python.org/tutorial/modules.html#importing-from-a-package
using __all__
and import *
is redundant, only __all__
is needed
I think one of the most powerful reasons to use import *
in an __init__.py
to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py
files empty.
for example:
foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo
then the app grows and now it's a whole folder
foo/
__init__.py
foofactories.py
tallFoos.py
shortfoos.py
mediumfoos.py
santaslittlehelperfoo.py
superawsomefoo.py
anotherfoo.py
then the init script can say
__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo
so that a script written to do the following does not break during the change:
from foo import fooFactory, tallFoo, shortFoo
I think you're going to need separate lines for each segment:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.random(size=(2,10))
for i in range(0, len(x), 2):
plt.plot(x[i:i+2], y[i:i+2], 'ro-')
plt.show()
(The numpy
import is just to set up some random 2x10 sample data)
This comment syntax should work for you:
@* enter comments here *@
Here you'll find your answer:
Using Git how do I find changes between local and remote
For the lazy:
- Use "git log origin..HEAD"
- Use "git fetch" followed by "git log HEAD..origin". You can cherry-pick individual commits using the listed commit ids.
The above assumes, of course, that "origin" is the name of your remote tracking branch (which it is if you've used clone with default options).
You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.
Set the svn:ignore
property of the parent directory:
svn propset svn:ignore dirname .
If you have multiple things to ignore, separate by newlines in the property value. In that case it's easier to edit the property value using an external editor:
svn propedit svn:ignore .
As has been mentioned, slicing with None
or with np.newaxes
is a great way to do this.
Another alternative is to use transposes and broadcasting, as in
(data.T - vector).T
and
(data.T / vector).T
For higher dimensional arrays you may want to use the swapaxes
method of NumPy arrays or the NumPy rollaxis
function.
There really are a lot of ways to do this.
For a fuller explanation of broadcasting, see http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
If you're using Bootstrap 3, you can use the embed-responsive class and set the padding bottom as the height divided by the width plus a little extra for toolbars. For example, to display an 8.5 by 11 PDF, use 130% (11/8.5) plus a little extra (20%).
<div class='embed-responsive' style='padding-bottom:150%'>
<object data='URL.pdf' type='application/pdf' width='100%' height='100%'></object>
</div>
Here's the Bootstrap CSS:
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
Highlight the cell, use Dat => Text to Columns and the DELIMITER is space. Result will appear in as many columns as the split find the space.
SELECT TOP 25 amount,
(SELECT SUM(amount)
FROM time_detail b
WHERE b.time_detail_id <= a.time_detail_id) AS Total FROM time_detail a
You can also use the ROW_NUMBER() function and a temp table to create an arbitrary column to use in the comparison on the inner SELECT statement.
With docker-compose, you could set context folder:
#docker-compose.yml
version: '3.3'
services:
yourservice:
build:
context: ./
dockerfile: ./docker/yourservice/Dockerfile
Setting the slice to nil
is the best way to clear a slice. nil
slices in go are perfectly well behaved and setting the slice to nil
will release the underlying memory to the garbage collector.
package main
import (
"fmt"
)
func dump(letters []string) {
fmt.Println("letters = ", letters)
fmt.Println(cap(letters))
fmt.Println(len(letters))
for i := range letters {
fmt.Println(i, letters[i])
}
}
func main() {
letters := []string{"a", "b", "c", "d"}
dump(letters)
// clear the slice
letters = nil
dump(letters)
// add stuff back to it
letters = append(letters, "e")
dump(letters)
}
Prints
letters = [a b c d]
4
4
0 a
1 b
2 c
3 d
letters = []
0
0
letters = [e]
1
1
0 e
Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil
will remove that aliasing.
This method changes the capacity to zero though.
In SQL Server:
SELECT LEN(REPLACE(myColumn, 'N', ''))
FROM ...
It means that in table kontakty
you have a row referencing the row in osoby
you want to delete. You have do delete that row first or set a cascade delete on the relation between tables.
Powodzenia!
You can use navigator.mimeTypes.
if (navigator.mimeTypes ["application/x-shockwave-flash"] == undefined)
$("#someDiv").show ();
I think the answer is there but only in bits and pieces, which makes it difficult to quickly fix the problem such as
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 2818: ordinal not in range(128)
Let's take an example, Suppose I have file which has some data in the following form ( containing ascii and non-ascii chars )
1/10/17, 21:36 - Land : Welcome ��
and we want to ignore and preserve only ascii characters.
This code will do:
import unicodedata
fp = open(<FILENAME>)
for line in fp:
rline = line.strip()
rline = unicode(rline, "utf-8")
rline = unicodedata.normalize('NFKD', rline).encode('ascii','ignore')
if len(rline) != 0:
print rline
and type(rline) will give you
>type(rline)
<type 'str'>
I don't think you can. You could use number_format() if you're coding in PHP. And other programing languages have a function for formatting numbers too.
Another way of writing <script>window.$ = window.jQuery = require('./path/to/jquery');</script>
is :
<script src="./path/to/jquery" onload="window.$ = window.jQuery = module.exports;"></script>
The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.
You can link the table either manually or with VBA like this
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
Dim db As DAO.Database
' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next: db.TableDefs.Delete "tblImport": On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh
' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
& "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close: Set db = Nothing
None of these issues solved this for me. The problem in the end was pretty easy. It looks like its a pretty major Xcode bug which I have logged the problem and fix under Apple bug: 29820370. If you are struggling (as it seems like there are several pages of problems similar to this ) then it would be great if you can raise a bug on bug reporter: https://bugreport.apple.com/ and reference the bug I raised to gain visibility. I want to make Xcode back into the pleasure that it was before - and this is something I am sure Xcode should have fixed itself.
Here is the fix: 1. Open Keychain - go to Apple Worldwide Developer Cert. 2. Double Click on it 3. Change the permission level from "always trust" to use System Defaults 4. Save and close it 5. Restart Xcode, Clean and build your project and it should be gone.
You can implement your own new
and delete
functions, as well as an additional get-size
function:
#define CEIL_DIV(x,y) (((x)-1)/(y)+1)
void* my_new(int size)
{
if (size > 0)
{
int* ptr = new int[1+CEIL_DIV(size,sizeof(int))];
if (ptr)
{
ptr[0] = size;
return ptr+1;
}
}
return 0;
}
void my_delete(void* mem)
{
int* ptr = (int*)mem-1;
delete ptr;
}
int my_size(void* mem)
{
int* ptr = (int*)mem-1;
return ptr[0];
}
Alternatively, you can override the new
and delete
operators in a similar manner.
Try put this in the head of the document:
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/>
The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.
When page has no meta viewport tag:
When page has either of these two meta tags:
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">
With <meta name="viewport" content="width=device-width">
:
With <meta name="viewport" content="height=device-height">
:
With <meta name="viewport" content="height=device-height,width=device-width">
:
With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">
With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">
The difference lies in the fact that ./gradlew
indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle
and then invoke gradle using the gradle
command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.
Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.
Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable
Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html
Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk
I just add function pr() to the global scope of my project. For example, you can define the following function to global.inc (if you have) which will be included into your index.php of your site. Or you can directly define this function at the top of index.php of root directory.
function pr($obj)
{
echo "<pre>";
print_r ($obj);
echo "</pre>";
}
I think that you can bind the load
event of the iframe, the event fires when the iframe content is fully loaded.
At the same time you can start a setTimeout, if the iFrame is loaded clear the timeout alternatively let the timeout fire.
Code:
var iframeError;
function change() {
var url = $("#addr").val();
$("#browse").attr("src", url);
iframeError = setTimeout(error, 5000);
}
function load(e) {
alert(e);
}
function error() {
alert('error');
}
$(document).ready(function () {
$('#browse').on('load', (function () {
load('ok');
clearTimeout(iframeError);
}));
});
Demo: http://jsfiddle.net/IrvinDominin/QXc6P/
It is because you miss the parens in the inline function call; try change this:
<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>
into this:
<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>
Python 2
sudo pip2 install johnbonjovi
Python 3
sudo pip3 install johnbonjovi
Simply create a new text document called "anaconda-navigator.desktop" in your home directory by the terminal command:
gedit anaconda-navigator.desktop
Then enter the following in your text document:
#!/usr/bin/env xdg-open
[Desktop Entry]
Name=Anaconda
Version=2.0
Type=Application
Exec=/path/to/anaconda-navigator
Icon=/path/to/selected/icon
Comment=Open Anaconda Navigator
Terminal=false
Save the file, then move it to your local applications folder:
mv anaconda-navigator.desktop ~/.local/share/applications/
Once this is done, you will be able to search for "Anaconda" on your applications screen, right click, and add to favorites. This way you don't have to go through the terminal every time!
Alex Answer is pretty neat but when using context rotate it can be hard to trace x,y coordinates, so I have made a Demo showing how to keep track of that.
Basically I am using this function & giving it the angle & the amount of distance traveled in that angel before drawing object.
function rotCor(angle, length){
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var newx = length*cos;
var newy = length*sin;
return {
x : newx,
y : newy
};
}
There is a concept of a working directory
.
This directory is represented by a .
(dot).
In relative paths, everything else is relative to it.
Simply put the .
(the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\
in your case.
So test\..\test.txt
means: the sub-directory test
in my working directory, then one level up, then the
file test.txt
. This is basically the same as just test.txt
.
For more details check here.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
The way I use these operators:
||, &&
are for boolean logic. or, and
are for control flow. E.g.
do_smth if may_be || may_be
-- we evaluate the condition here
do_smth or do_smth_else
-- we define the workflow, which is equivalent to
do_smth_else unless do_smth
to give a simple example:
> puts "a" && "b"
b
> puts 'a' and 'b'
a
A well-known idiom in Rails is render and return
. It's a shortcut for saying return if render
, while render && return
won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.
Try setting a Windows System Environment variable called _JAVA_OPTIONS
with the heap size you want. Java should be able to find it and act accordingly.
Although other answers include some of the following information, this is the absolute minimum that needs to be changed on EC2 instances, specifically regarding deployment of large WAR files, and is the least likely to cause issues during future updates. I've been running into these limits about every other year due to the ever-increasing size of the Jenkins WAR file (now ~72MB).
More specifically, this answer is applicable if you encounter a variant of the following error in catalina.out
:
SEVERE [https-jsse-nio-8443-exec-17] org.apache.catalina.core.ApplicationContext.log HTMLManager:
FAIL - Deploy Upload Failed, Exception:
[org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException:
the request was rejected because its size (75333656) exceeds the configured maximum (52428800)]
On Amazon EC2 Linux instances, the only file that needs to be modified from the default installation of Tomcat (sudo yum install tomcat8
) is:
/usr/share/tomcat8/webapps/manager/WEB-INF/web.xml
By default, the maximum upload size is exactly 50MB:
<multipart-config>
<!-- 50MB max -->
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
There are only two values that need to be modified (max-file-size
and max-request-size
):
<multipart-config>
<!-- 100MB max -->
<max-file-size>104857600</max-file-size>
<max-request-size>104857600</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
When Tomcat is upgraded on these instances, the new version of the manager web.xml
will be placed in web.xml.rpmnew
, so any modifications to the original file will not be overwritten during future updates.
I would turn it into CSV form, like so:
$string_version = implode(',', $original_array)
You can turn it back by doing:
$destination_array = explode(',', $string_version)
data attributes are commonly used for a variety of interactions. Typically via javascript. They do not affect anything regarding site behavior and stand as a convenient method to pass data for whatever purpose needed. Here is an article that may clear things up:
http://ejohn.org/blog/html-5-data-attributes/
You can create a data attribute by prefixing data-
to any standard attribute safe string (alphanumeric with no spaces or special characters). For example, data-id
or in this case data-reactid
gradle com.android.tools.build:gradle:2.2.0-alpha6
constraint layout dependency com.android.support.constraint:constraint-layout:1.0.0-alpha4
works for me
The dplyr package's select_if(
) function is an elegant solution:
library("dplyr")
select_if(x, is.numeric)
this worked for me , pyrotex answer didn' reset select fields, took his, here' my edit:
// Use a whitelist of fields to minimize unintended side effects.
$(':text, :password, :file', '#myFormId').val('');
// De-select any checkboxes, radios and drop-down menus
$(':input,select option', '#myFormId').removeAttr('checked').removeAttr('selected');
//this is for selecting the first entry of the select
$('select option:first', '#myFormId').attr('selected',true);
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private
).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...)
. You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super
or base
) since C++ supports multiple inheritance which may lead to ambiguity.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
The following is working fine for me using SQLite:
SELECT *
FROM ingresosgastos
WHERE fecharegistro BETWEEN "2010-01-01" AND "2013-01-01"
This debugging code should do the trick well:
You can explore the properties of the Screen Class
Put all displays in an array or list using Screen.AllScreens then capture the index of the current display and its properties.
C# (Converted from VB by Telerik - Please double check)
{
List<Screen> arrAvailableDisplays = new List<Screen>();
List<string> arrDisplayNames = new List<string>();
foreach (Screen Display in Screen.AllScreens)
{
arrAvailableDisplays.Add(Display);
arrDisplayNames.Add(Display.DeviceName);
}
Screen scrCurrentDisplayInfo = Screen.FromControl(this);
string strDeviceName = Screen.FromControl(this).DeviceName;
int idxDevice = arrDisplayNames.IndexOf(strDeviceName);
MessageBox.Show(this, "Number of Displays Found: " + arrAvailableDisplays.Count.ToString() + Constants.vbCrLf + "ID: " + idxDevice.ToString() + Constants.vbCrLf + "Device Name: " + scrCurrentDisplayInfo.DeviceName.ToString + Constants.vbCrLf + "Primary: " + scrCurrentDisplayInfo.Primary.ToString + Constants.vbCrLf + "Bounds: " + scrCurrentDisplayInfo.Bounds.ToString + Constants.vbCrLf + "Working Area: " + scrCurrentDisplayInfo.WorkingArea.ToString + Constants.vbCrLf + "Bits per Pixel: " + scrCurrentDisplayInfo.BitsPerPixel.ToString + Constants.vbCrLf + "Width: " + scrCurrentDisplayInfo.Bounds.Width.ToString + Constants.vbCrLf + "Height: " + scrCurrentDisplayInfo.Bounds.Height.ToString + Constants.vbCrLf + "Work Area Width: " + scrCurrentDisplayInfo.WorkingArea.Width.ToString + Constants.vbCrLf + "Work Area Height: " + scrCurrentDisplayInfo.WorkingArea.Height.ToString, "Current Info for Display '" + scrCurrentDisplayInfo.DeviceName.ToString + "' - ID: " + idxDevice.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
VB (Original code)
Dim arrAvailableDisplays As New List(Of Screen)()
Dim arrDisplayNames As New List(Of String)()
For Each Display As Screen In Screen.AllScreens
arrAvailableDisplays.Add(Display)
arrDisplayNames.Add(Display.DeviceName)
Next
Dim scrCurrentDisplayInfo As Screen = Screen.FromControl(Me)
Dim strDeviceName As String = Screen.FromControl(Me).DeviceName
Dim idxDevice As Integer = arrDisplayNames.IndexOf(strDeviceName)
MessageBox.Show(Me,
"Number of Displays Found: " + arrAvailableDisplays.Count.ToString & vbCrLf &
"ID: " & idxDevice.ToString + vbCrLf &
"Device Name: " & scrCurrentDisplayInfo.DeviceName.ToString + vbCrLf &
"Primary: " & scrCurrentDisplayInfo.Primary.ToString + vbCrLf &
"Bounds: " & scrCurrentDisplayInfo.Bounds.ToString + vbCrLf &
"Working Area: " & scrCurrentDisplayInfo.WorkingArea.ToString + vbCrLf &
"Bits per Pixel: " & scrCurrentDisplayInfo.BitsPerPixel.ToString + vbCrLf &
"Width: " & scrCurrentDisplayInfo.Bounds.Width.ToString + vbCrLf &
"Height: " & scrCurrentDisplayInfo.Bounds.Height.ToString + vbCrLf &
"Work Area Width: " & scrCurrentDisplayInfo.WorkingArea.Width.ToString + vbCrLf &
"Work Area Height: " & scrCurrentDisplayInfo.WorkingArea.Height.ToString,
"Current Info for Display '" & scrCurrentDisplayInfo.DeviceName.ToString & "' - ID: " & idxDevice.ToString, MessageBoxButtons.OK, MessageBoxIcon.Information)
My understanding is driver.close();
will close the current browser,
and driver.quit();
will terminate all the browser that.
It's never wise to rely on defaults being set to a particular value, IMHO, whether it's for date formats, currency formats, optimiser modes or whatever. You should always set the value of date format that you need, in the server, the client, or the application.
In particular, never rely on defaults when converting date or numeric data types for display purposes, because a single change to the database can break your application. Always use an explicit conversion format. For years I worked on Oracle systems where the out of the box default date display format was MM/DD/RR, which drove me nuts but at least forced me to always use an explicit conversion.
If you need to handle the action more specifically with the back button you can use the following method:
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK )
{
onCloseFragment();
return true;
} else {
return false;
}
}
});
For default exports you should use:
import * as fs from 'fs';
Or in case the module has named exports:
import {fs} from 'fs';
Example:
//module1.js
export function function1() {
console.log('f1')
}
export function function2() {
console.log('f2')
}
export default function1;
And then:
import defaultExport, { function1, function2 } from './module1'
defaultExport(); // This calls function1
function1();
function2();
Additionally, you should use Webpack or something similar to be able to use ES6 import
In my case the file .git/HEAD was corrupted (contained only dots). So I edited it and replaced its content with:
ref: refs/heads/master
and it started working again.
I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.
I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:
jQuery.param
JSON.stringify + encodeURIComponent
JSURL.stringify
clearly JSURL has the most optimized format for urlEncoding a js object.
the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.
Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
If you are using JQuery then put the javascript wherever you find it best and use $(document).ready()
to ensure that things are loaded properly before executing any functions.
On a side note: I like all my script tags in the <head>
section as that seems to be the cleanest place.
The technique I use most often is find | xargs
. For example, if you want to make every file in this directory and all of its subdirectories world-readable, you can do:
find . -type f -print0 | xargs -0 chmod go+r
find . -type d -print0 | xargs -0 chmod go+rx
The -print0
option terminates with a NULL character instead of a space. The -0
option splits its input the same way. So this is the combination to use on files with spaces.
You can picture this chain of commands as taking every line output by find
and sticking it on the end of a chmod
command.
If the command you want to run as its argument in the middle instead of on the end, you have to be a bit creative. For instance, I needed to change into every subdirectory and run the command latemk -c
. So I used (from Wikipedia):
find . -type d -depth 1 -print0 | \
xargs -0 sh -c 'for dir; do pushd "$dir" && latexmk -c && popd; done' fnord
This has the effect of for dir $(subdirs); do stuff; done
, but is safe for directories with spaces in their names. Also, the separate calls to stuff
are made in the same shell, which is why in my command we have to return back to the current directory with popd
.
The IPAddress Java library can accomplish what you are describing here.
IPv6 addresses are 16 bytes. Using that library, if you are starting with a 16-byte array you can construct the IPv6 address object:
IPv6Address addr = new IPv6Address(bytes); //bytes is byte[16]
From there you can check if the address is IPv4 mapped, IPv4 compatible, IPv4 translated, and so on (there are many possible ways IPv6 represents IPv4 addresses). In most cases, if an IPv6 address represents an IPv4 address, the ipv4 address is in the lower 4 bytes, and so you can get the derived IPv4 address as follows. Afterwards, you can convert back to bytes, which will be just 4 bytes for IPv4.
if(addr.isIPv4Compatible() || addr.isIPv4Mapped()) {
IPv4Address derivedIpv4Address = addr.getEmbeddedIPv4Address();
byte ipv4Bytes[] = derivedIpv4Address.getBytes();
...
}
The javadoc is available at the link.
// enter code here
var a = 9821099923;
var b = 91;
alert ("" + b + a);
// after concating , result is 919821099923 but its is now converted into string
console.log(Number.isInteger("" + b + a)) // false
// you have to do something like this
var c= parseInt("" + b + a)
console.log(c); // 919821099923
console.log(Number.isInteger(c)) // true
Here is a SUMMARY of all the major answers above (or maybe below later :)
For modern browsers, put css wherever you like it. They would analyze your html file (which they call speculative parsing) and start downloading css in parallel with html parsing.
For old browsers keep putting css on top (if you don't want to show a naked but interactive page first).
For all browsers, put javascript as farther down on the page as possible, since it will halt parsing of your html. Preferably, download it asynchronously (i.e., ajax call)
There are also, some experimental results for a particular case which claims putting javascript first (as opposed to traditional wisdom of putting CSS first) gives better performance but there is no logical reasoning given for it, and lacks validation regarding widespread applicability, so you can ignore it for now.
So, to answer the question: Yes. The recommendation to include the CSS before JS is invalid for the modern browsers. Put CSS wherever you like, and put JS towards the end, as possible.
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
gene_name = no_headers.iloc[1:,[1]]
This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:
gene_name[x]
you now have a Series object with a single value. You can't hash the Series.
The solution is to create Series from the start.
gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]
Also, where you have orph_dict[gene_name[x]] =+ 1
, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1
to increment the counter.
You wouldn’t: it’s messy and hard to read.
You’re looking for the switch
statement in the first case. The second is fine as it is but still could be converted for consistency
Ternary statements are much more suited to boolean values and alternating logic.
< input type="password" style='pointer-event: none' onInput= (e) => handleInput(e) />
function handleInput(e) {
e.preventDefault();
e.stopPropagation();
e.target.setAttribute('readonly', true);
setTimeout(() => {
e.target.focus();
e.target.removeAttribute('readonly');
});
}
Say you have static fields and methods inside a class called MyClass
inside a package called myPackage
and you want to access them directly by typing myStaticField
or myStaticMethod
without typing each time MyClass.myStaticField
or MyClass.myStaticMethod
.
Note : you need to do an
import myPackage.MyClass
or myPackage.*
for accessing the other resources
//if i input 9 it should go to 8?
You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).
formatDate
is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");_x000D_
_x000D_
$("#hello").append(formatDate(unformatedDate));_x000D_
function formatDate(nowDate) {_x000D_
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="hello">_x000D_
_x000D_
_x000D_
</div>
_x000D_
Use a RotateAnimation
, setting the pivot point to the centre of your image.
RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
// Start animating the image
final ImageView splash = (ImageView) findViewById(R.id.splash);
splash.startAnimation(anim);
// Later.. stop the animation
splash.setAnimation(null);
I was trying to make the calendar selects a date by default and highlights it for the user. However, i tried using all the options above but i only managed to set the calendar's selected date.
protected void Page_Load(object sender, EventArgs e)
Calendar1.SelectedDate = DateTime.Today;
}
the previous code did NOT highlight the selection, although it set the SelectedDate to today.
However, to select and highlight the following code will work properly.
protected void Page_Load(object sender, EventArgs e)
{
DateTime today = DateTime.Today;
Calendar1.TodaysDate = today;
Calendar1.SelectedDate = Calendar1.TodaysDate;
}
check this link: http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx
You can play with your array
$daysArray = array('Monday', 'Tuesday', 'Sunday');
$day = current($transport); // $day = 'Monday';
$day = next($transport); // $day = 'Tuesday';
$day = current($transport); // $day = 'Tuesday';
$day = prev($transport); // $day = 'Monday';
$day = end($transport); // $day = 'Sunday';
$day = current($transport); // $day = 'Sunday';
To get the first element of array you can use current
and for last element you can use end
Edit
Just for the sake for not getting any more down votes for the answer you can convert you key to value using array_keys
and use as shown above.
I used this command to get rid of the local files preventing me from doing a pull/merge. But be careful! Run git merge …
first to see whether there are only those files you really want to remove.
git merge origin/master 2>&1 >/dev/null | grep ^[[:space:]] | sed s/^[[:space:]]//g | xargs -L1 rm
git merge
lists among other things all those files. They are prepended by some white-space.2>&1 >/dev/null
redirects the error output to the standard one so it is picked up by grep
.grep ^[[:space:]]
filters only the lines with file names.sed s/^[[:space:]]//g
trims the white-space from the beginning.xargs -L1 rm
calls rm
on each of those files, deleting them.Handle with care: Whatever git merge
outputs, the rm
will be called for every line beginning with a white-space.
fun View.forEachChildView(closure: (View) -> Unit) {
closure(this)
val groupView = this as? ViewGroup ?: return
val size = groupView.childCount - 1
for (i in 0..size) {
groupView.getChildAt(i).forEachChildView(closure)
}
}
val layout = LinearLayout(context!!)
layout.forEachChildView { it.isEnabled = false }
val view = View(context!!)
view.forEachChildView { it.isEnabled = false }
val fragment = Fragment.instantiate(context, "fragment_id")
fragment.view?.forEachChildView { it.isEnabled = false }
Actually I would use:
df[ grep("REVERSE", df$Name, invert = TRUE) , ]
This will avoid deleting all of the records if the desired search word is not contained in any of the rows.
when we pass vector by value in a function as an argument,it simply creates the copy of vector and no any effect happens on the vector which is defined in main function when we call that particular function. while when we pass vector by reference whatever is written in that particular function, every action will going to perform on the vector which is defined in main or other function when we call that particular function.
$('#select_all').click( function() {
$('select#countries > option').prop('selected', 'selected');
});
If you use jQuery older than 1.6:
$('#select_all').click( function() {
$('select#countries > option').attr('selected', 'selected');
});
I've solved using only @JsonIgnore
like @kryger has suggested.
So your getter will become:
@JsonIgnore
public String getEncryptedPwd() {
return this.encryptedPwd;
}
You can set @JsonIgnore
of course on field, setter or getter like described here.
And, if you want to protect encrypted password only on serialization side (e.g. when you need to login your users), add this @JsonProperty
annotation to your field:
@JsonProperty(access = Access.WRITE_ONLY)
private String encryptedPwd;
More info here.
Here is a screenshot of Request.RequestUri
and all its properties for everyone's reference.
No Gemfile.lock means:
-> Always check in Gemfile.lock, make travis delete it if you want to be extra thorough https://grosser.it/2015/08/14/check-in-your-gemfile-lock/
No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.
Another simple example:
Search: style="(.+?)"
Replace: css={css`$1`}
Useful for converting HTML to JSX with emotion/css!
Version 3.5 onwards allows the use of PEP 448 - Extended Unpacking Generalizations:
>>> string = 'hello'
>>> [*string]
['h', 'e', 'l', 'l', 'o']
This is a specification of the language syntax, so it is faster than calling list
:
>>> from timeit import timeit
>>> timeit("list('hello')")
0.3042821969866054
>>> timeit("[*'hello']")
0.1582647830073256
I wanted to change the column value in a specific row. Thanks to above answers and after some serching able to come up with below,
var dataTable = $("#yourtableid");
var rowNumber = 0;
var columnNumber= 2;
dataTable[0].rows[rowNumber].cells[columnNumber].innerHTML = 'New Content';
Your formula should be of the form =IF(X2 >= 85,0.559,IF(X2 >= 80,0.327,IF(X2 >=75,0.255,0)))
. This simulates the ELSE-IF
operand Excel lacks. Your formulas were using two conditions in each, but the second parameter of the IF
formula is the value to use if the condition evaluates to true
. You can't chain conditions in that manner.
// in foo.h
class Foo {
static const unsigned char* Msg;
};
// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;
I use git log to see what has changed on a feature branch from master branch
git log does_this_branch..contain_this_branch_changes
e.g. - to see what commits are in a feature branch that has/not been merged to master:
git log master..feature_branch
You can do this with the UITableView
property separatorStyle
. Make sure the property is set to UITableViewCellSeparatorStyleNone
and you're set.
Objective-C
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
In Swift (prior to 3)
tableView.separatorStyle = .None
In Swift 3/4/5
tableView.separatorStyle = .none
To force download you may use Content-Type: application/force-download
header, which is supported by most browsers:
function downloadFile($filePath)
{
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
}
A BETTER WAY
Downloading files this way is not the best idea especially for large files. PHP will require extra CPU / Memory to read and output file contents and when dealing with large files may reach time / memory limits.
A better way would be to use PHP to authenticate and grant access to a file, and actual file serving should be delegated to a web server using X-SENDFILE method (requires some web server configuration):
X-SENDFILE
is natively supported by Lighttpd: https://redmine.lighttpd.net/projects/1/wiki/X-LIGHTTPD-send-filemod_xsendfile
module: https://tn123.org/mod_xsendfile/ On Ubuntu may be installed by: apt install libapache2-mod-xsendfile
X-Accel-Redirect
header: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/After configuring web server to handle X-SENDFILE
, just replace readfile($filePath)
with header('X-SENDFILE: ' . $filePath)
and web server will take care of file serving, which will require less resources than using PHP readfile
.
(For Nginx use X-Accel-Redirect
header instead of X-SENDFILE
)
Note: If you end up downloading empty files, it means you didn't configure your web server to handle X-SENDFILE
header. Check the links above to see how to correctly configure your web server.
Ultimately it probably doesn't have a safe .get
method because a dict
is an associative collection (values are associated with names) where it is inefficient to check if a key is present (and return its value) without throwing an exception, while it is super trivial to avoid exceptions accessing list elements (as the len
method is very fast). The .get
method allows you to query the value associated with a name, not directly access the 37th item in the dictionary (which would be more like what you're asking of your list).
Of course, you can easily implement this yourself:
def safe_list_get (l, idx, default):
try:
return l[idx]
except IndexError:
return default
You could even monkeypatch it onto the __builtins__.list
constructor in __main__
, but that would be a less pervasive change since most code doesn't use it. If you just wanted to use this with lists created by your own code you could simply subclass list
and add the get
method.
for i in $(ls); do cp -r "$i" "$i"_dev; done;
The most common use case I can think of is when working with the INotifyPropertyChanged
interface. (Basically everything related to WPF and bindings uses this interface)
Take a look at this example:
public class Model : INotifyPropertyChanged
{
// From the INotifyPropertyChanged interface
public event PropertyChangedEventHandler PropertyChanged;
private string foo;
public String Foo
{
get { return this.foo; }
set
{
this.foo = value;
// Old code:
PropertyChanged(this, new PropertyChangedEventArgs("Foo"));
// New Code:
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Foo)));
}
}
}
As you can see in the old way we have to pass a string to indicate which property has changed. With nameof
we can use the name of the property directly. This might not seem like a big deal. But image what happens when somebody changes the name of the property Foo
. When using a string the binding will stop working, but the compiler will not warn you. When using nameof you get a compiler error that there is no property/argument with the name Foo
.
Note that some frameworks use some reflection magic to get the name of the property, but now we have nameof this is no longer neccesary.
The boolean value for NO
in Swift is false
.
button.isEnabled = false
should do it.
Here is the Swift documentation for UIControl
's isEnabled
property.
If you're using .Net 3.5, you can make cleaner code using:
foreach (Record item in LookupCollection.Intersect(LargeCollection))
{
//dostuff
}
I don't have .Net 3.5 here and so this is untested. It relies on an extension method. Not that LookupCollection.Intersect(LargeCollection)
is probably not the same as LargeCollection.Intersect(LookupCollection)
... the latter is probably much slower.
This assumes LookupCollection is a HashSet
You can use the box-shadow property on a tr element as a subtitute for a border. As a plus, any border-radius property on the same element will also apply to the box shadow.
box-shadow: 0px 0px 0px 1px rgb(0, 0, 0);
I got this error message because while coding my project auto update compile version in my build.gradle
file :
android {
...
buildToolsVersion "23.0.2"
...
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0' }
Solve it by correcting the version:
android {
...
buildToolsVersion "23.0.2"
...
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
}
For it was betternet extension was causing issue. I think any kind of proxy extension installed on Chrome causing issue.
import React from 'react';
class RentalHome extends React.Component{
constructor(){
super();
this.state = {
rentals:[{
_id: 1,
title: "Nice Shahghouse Biryani",
city: "Hyderabad",
category: "condo",
image: "http://via.placeholder.com/350x250",
numOfRooms: 4,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 43
},
{
_id: 2,
title: "Modern apartment in center",
city: "Bangalore",
category: "apartment",
image: "http://via.placeholder.com/350x250",
numOfRooms: 1,
shared: false,
description: "Very nice apartment in center of the city.",
dailyPrice: 11
},
{
_id: 3,
title: "Old house in nature",
city: "Patna",
category: "house",
image: "http://via.placeholder.com/350x250",
numOfRooms: 5,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 23
}]
}
}
render(){
const {rentals} = this.state;
return(
<div className="card-list">
<div className="container">
<h1 className="page-title">Your Home All Around the World</h1>
<div className="row">
{
rentals.map((rental)=>{
return(
<div key={rental._id} className="col-md-3">
<div className="card bwm-card">
<img
className="card-img-top"
src={rental.image}
alt={rental.title} />
<div className="card-body">
<h6 className="card-subtitle mb-0 text-muted">
{rental.shared} {rental.category} {rental.city}
</h6>
<h5 className="card-title big-font">
{rental.title}
</h5>
<p className="card-text">
${rental.dailyPrice} per Night · Free Cancelation
</p>
</div>
</div>
</div>
)
})
}
</div>
</div>
</div>
)
}
}
export default RentalHome;
Array object iteration, using jQuery, (use the second parameter to print the string).
$.each(array, function(index, item) {
console.log(index, item);
});
I like simple.
HAPPY
and SAD
.IntentFactory
that creates your Intent
for you. Pass it the Mode
you want.IntentFactory
uses the name of the Mode
class as the name of the extra.IntentFactory
converts the Mode
to a String
using name()
onCreate
use this info to convert back to a Mode
.You could use ordinal()
and Mode.values()
as well. I like strings because I can see them in the debugger.
public class Fred extends Activity {
public static enum Mode {
HAPPY,
SAD,
;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.betting);
Intent intent = getIntent();
Mode mode = Mode.valueOf(getIntent().getStringExtra(Mode.class.getName()));
Toast.makeText(this, "mode="+mode.toString(), Toast.LENGTH_LONG).show();
}
public static Intent IntentFactory(Context context, Mode mode){
Intent intent = new Intent();
intent.setClass(context,Fred.class);
intent.putExtra(Mode.class.getName(),mode.name());
return intent;
}
}
in regards to the exclamation mark I just found out it's on gems fetched via :git
, e.g.
gem "foo", :git => "[email protected]:company/foo.git"
The solution is to create the php.ini file under your root directory. If the site is the wordpress installation then create the php.ini under your/path/to/wordpress/wp-admin/php.ini and add the following line of codes
[PHP]
post_max_size=120M
upload_max_filesize=132M
In my.cnf file check below 2 steps.
check this value -
old_passwords=0;
it should be 0.
check this also-
[mysqld] default_authentication_plugin= mysql_native_password Another value to check is to make sure
[mysqld] section should be like this.
Here are summarized the key differences between RESTful and RESTless web services:
1. Protocol
2. Business logic / Functionality
3. Security
4. Data format
5. Flexibility
6. Bandwidth
If s
is your string than you could do it this way:
Mid(s, index, 1)
Edit based on comment below question.
It seems that you need a bit different approach which should be easier. Try in this way:
Dim character As String 'Integer if for numbers
's = ActiveDocument.Content.Text - we don't need it
character = Activedocument.Characters(index)
I suggest to use the inherits
helper that comes with the standard util
module: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor
There is an example of how to use it on the linked page.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>fibonacci series</title>
<script type="text/javascript">
function generateseries(){
var fno = document.getElementById("firstno").value;
var sno = document.getElementById("secondno").value;
var a = parseInt(fno);
var result = new Array();
result[0] = a;
var b = ++fno;
var c = b;
while (b <= sno) {
result.push(c);
document.getElementById("maindiv").innerHTML = "Fibonacci Series between "+fno+ " and " +sno+ " is " +result;
c = a + b;
a = b;
b = c;
}
}
function numeric(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
</script>
<h1 align="center">Fibonacci Series</h1>
</head>
<body>
<div id="resultdiv" align="center">
<input type="text" name="firstno" id="firstno" onkeypress="numeric(event)"><br>
<input type="text" name="secondno" id="secondno" onkeypress="numeric(event)"><br>
<input type="button" id="result" value="Result" onclick="generateseries();">
<div id="maindiv"></div>
</div>
</body>
</html>
The characters are exactly as documented - \b
equates to a character code of 0x08
and \r
equates to 0x0d
. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.
Use the show_source();
function of PHP. Check for more details in show_source. This is a better method I guess.
In order to simulate the issue that you are facing, I created the following sample using SSIS 2008 R2
with SQL Server 2008 R2
backend. The example is based on what I gathered from your question. This example doesn't provide a solution but it might help you to identify where the problem could be in your case.
Created a simple CSV file with two columns namely order number and order date. As you had mentioned in your question, values of both the columns are qualified with double quotes (") and also the lines end with Line Feed (\n) with the date being the last column. The below screenshot was taken using Notepad++, which can display the special characters in a file. LF in the screenshot denotes Line Feed.
Created a simple table named dbo.Destination
in the SQL Server database to populate the CSV file data using SSIS package. Create script for the table is given below.
CREATE TABLE [dbo].[Destination](
[OrderNumber] [varchar](50) NULL,
[OrderDate] [date] NULL
) ON [PRIMARY]
GO
On the SSIS package, I created two connection managers. SQLServer was created using the OLE DB Connection to connect to the SQL Server database. FlatFile is a flat file connection manager.
Flat file connection manager was configured to read the CSV file and the settings are shown below. The red arrows indicate the changes made.
Provided a name to the flat file connection manager. Browsed to the location of the CSV file and selected the file path. Entered the double quote ("
) as the text qualifier. Changed the Header row delimiter from {CR}{LF} to {LF}
. This header row delimiter change also reflects on the Columns section.
No changes were made in the Columns section.
Changed the column name from Column0 to OrderNumber
.
Changed the column name from Column1 to OrderDate
and also changed the data type to date [DT_DATE]
Preview of the data within the flat file connection manager looks good.
On the Control Flow
tab of the SSIS package, placed a Data Flow Task
.
Within the Data Flow Task, placed a Flat File Source
and an OLE DB Destination
.
The Flat File Source
was configured to read the CSV file data using the FlatFile connection manager. Below three screenshots show how the flat file source component was configured.
The OLE DB Destination
component was configured to accept the data from Flat File Source and insert it into SQL Server database table named dbo.Destination
. Below three screenshots show how the OLE DB Destination component was configured.
Using the steps mentioned in the below 5 screenshots, I added a data viewer on the flow between the Flat File Source and OLE DB Destination.
Before running the package, I verified the initial data present in the table. It is currently empty because I created this using the script provided at the beginning of this post.
Executed the package and the package execution temporarily paused to display the data flowing from Flat File Source to OLE DB Destination in the data viewer. I clicked on the run button to proceed with the execution.
The package executed successfully.
Flat file source data was inserted successfully into the table dbo.Destination
.
Here is the layout of the table dbo.Destination. As you can see, the field OrderDate is of data type date and the package still continued to insert the data correctly.
This post even though is not a solution. Hopefully helps you to find out where the problem could be in your scenario.
Try removing the [Ignore]
attribute from above the test method.
open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()
This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...
pugixml - Light-weight, simple and fast XML parser for C++ Very small (comparable to RapidXML), very fast (comparable to RapidXML), very easy to use (better than RapidXML).
def permuteArray (arr):
arraySize = len(arr)
permutedList = []
if arraySize == 1:
return [arr]
i = 0
for item in arr:
for elem in permuteArray(arr[:i] + arr[i + 1:]):
permutedList.append([item] + elem)
i = i + 1
return permutedList
I intended to not exhaust every possibility in a new line to make it somewhat unique.
If using IIS 7 or IIS 7.5 you can use
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="CreateThing.aspx" />
</files>
</defaultDocument>
</system.webServer>
https://docs.microsoft.com/en-us/iis/configuration/system.webServer/defaultDocument/
file version < 5 : file -i -b /path/to/file
file version >=5 : file --mime-type -b /path/to/file
If the list is sorted (as happens to be in the example) a binary search on index certainly works.
public static Dog Find(List<Dog> AllDogs, string Id)
{
int p = 0;
int n = AllDogs.Count;
while (true)
{
int m = (n + p) / 2;
Dog d = AllDogs[m];
int r = string.Compare(Id, d.Id);
if (r == 0)
return d;
if (m == p)
return null;
if (r < 0)
n = m;
if (r > 0)
p = m;
}
}
Not sure what the LINQ version of this would be.
The i
flag is normally used for case insensitivity. You don't give a language here, but it'll probably be something like /G[ab].*/i
or /(?i)G[ab].*/
.
/*
import scanner and instantiate scanner class;
declare your method with two parameters
declare a third variable;
set condition;
swap the parameter values if condition is met;
set second conditon based on result of first condition;
divide and assign remainder to the third variable;
swap the result;
in the main method, allow for user input;
Call the method;
*/
public class gcf {
public static void main (String[]args){//start of main method
Scanner input = new Scanner (System.in);//allow for user input
System.out.println("Please enter the first integer: ");//prompt
int a = input.nextInt();//initial user input
System.out.println("Please enter a second interger: ");//prompt
int b = input.nextInt();//second user input
Divide(a,b);//call method
}
public static void Divide(int a, int b) {//start of your method
int temp;
// making a greater than b
if (b > a) {
temp = a;
a = b;
b = temp;
}
while (b !=0) {
// gcd of b and a%b
temp = a%b;
// always make a greater than b
a =b;
b =temp;
}
System.out.println(a);//print to console
}
}
DATE_FIELD_MAPPING = {
Model1: 'date',
Model2: 'pubdate',
}
def my_key_func(obj):
return getattr(obj, DATE_FIELD_MAPPING[type(obj)])
And then sorted(chain(Model1.objects.all(), Model2.objects.all()), key=my_key_func)
Quoted from https://groups.google.com/forum/#!topic/django-users/6wUNuJa4jVw. See Alex Gaynor
Just found another way to know the jboss version, so pointing out here:
In Linux
/Windows
use --version
parameter along with Jboss executable to know the Jboss Version
eg:
[immo@g012 bin]$ ./run.sh --version
========================================================================
JBoss Bootstrap Environment
JBOSS_HOME: /programs/jboss4.2-AES2.3Cert
JAVA: /programs/java/jdk1.7.0_09/bin/java
JAVA_OPTS: -server -Xms128m -Xmx512m -Dsun.rmi.dgc.client.gcInterval=3600000
CLASSPATH: /programs/jboss4.2-AES2.3Cert/bin/run.jar:/programs/java/jdk1.7.0_09/lib/tools.jar
=========================================================================
Listening for transport dt_socket at address: 8787
JBoss 4.0.4.GA (build: CVSTag=JBoss_4_0_4_GA date=200605151000)
Here JBoss 4.0.4.GA
is the Jboss version
in windows this could be
run.bat --version
Also, in new versions of jboss the executable is standalone.sh
/ standalone.bat
It is your setting as the owner of your local repo. Change it like this:
git remote set-head origin some_branch
And origin/HEAD will point to your branch instead of master. This would then apply to your repo only and not for others. By default, it will point to master, unless something else has been configured on the remote repo.
Manual entry for remote set-head provides some good information on this.
Edit: to emphasize: without you telling it to, the only way it would "move" would be a case like renaming the master branch, which I don't think is considered "organic". So, I would say organically it does not move.
var versionAttrib = new AssemblyName(Assembly.GetExecutingAssembly().FullName);
Another way is to use the -t
switch to ssh
:
ssh -t user@server "sudo script"
See man ssh
:
-t Force pseudo-tty allocation. This can be used to execute arbi-
trary screen-based programs on a remote machine, which can be
very useful, e.g., when implementing menu services. Multiple -t
options force tty allocation, even if ssh has no local tty.
^[^<>]+$
The caret in the character class ([^
) means match anything but, so this means, beginning of string, then one or more of anything except <
and >
, then the end of the string.
According to me...if you have already declared the edittext
in the XML file and set the property in the XML file "android:enabled=false"
and disable at runtime to it at that time in java file adding only 2 or 3 lines
Get by id
et1 = (EditText) FindViewById(R.id.edittext1);
et1.setEnabled(false);
You can do enable or disable to every control at run time by java file and design time by XML file.
In Spring, those objects that form the backbone of your application and that are managed by the Spring IoC container are referred to as beans. A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container;
Check out the jQuery dimensions plugin
A SELECT
in SQL Server will place a shared lock on a table row - and a second SELECT
would also require a shared lock, and those are compatible with one another.
So no - one SELECT
cannot block another SELECT
.
What the WITH (NOLOCK)
query hint is used for is to be able to read data that's in the process of being inserted (by another connection) and that hasn't been committed yet.
Without that query hint, a SELECT
might be blocked reading a table by an ongoing INSERT
(or UPDATE
) statement that places an exclusive lock on rows (or possibly a whole table), until that operation's transaction has been committed (or rolled back).
Problem of the WITH (NOLOCK)
hint is: you might be reading data rows that aren't going to be inserted at all, in the end (if the INSERT
transaction is rolled back) - so your e.g. report might show data that's never really been committed to the database.
There's another query hint that might be useful - WITH (READPAST)
. This instructs the SELECT
command to just skip any rows that it attempts to read and that are locked exclusively. The SELECT
will not block, and it will not read any "dirty" un-committed data - but it might skip some rows, e.g. not show all your rows in the table.
Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code.
yourHeightConstraintOutlet.constant = someValue
yourView.layoutIfNeeded()
Method updateConstraints()
is an instance method of UIView
. It is helpful when you are setting the constraints programmatically. It updates constraints for the view. For more detail click here.
In ---- model:
Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
Change the class ----- extends Model
to class ----- extends Eloquent
You cannot place checkbox inside select element but you can get the same functionality by using HTML, CSS and JavaScript. Here is a possible working solution. The explanation follows.
var expanded = false;_x000D_
_x000D_
function showCheckboxes() {_x000D_
var checkboxes = document.getElementById("checkboxes");_x000D_
if (!expanded) {_x000D_
checkboxes.style.display = "block";_x000D_
expanded = true;_x000D_
} else {_x000D_
checkboxes.style.display = "none";_x000D_
expanded = false;_x000D_
}_x000D_
}
_x000D_
.multiselect {_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
.selectBox {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.selectBox select {_x000D_
width: 100%;_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.overSelect {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
}_x000D_
_x000D_
#checkboxes {_x000D_
display: none;_x000D_
border: 1px #dadada solid;_x000D_
}_x000D_
_x000D_
#checkboxes label {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#checkboxes label:hover {_x000D_
background-color: #1e90ff;_x000D_
}
_x000D_
<form>_x000D_
<div class="multiselect">_x000D_
<div class="selectBox" onclick="showCheckboxes()">_x000D_
<select>_x000D_
<option>Select an option</option>_x000D_
</select>_x000D_
<div class="overSelect"></div>_x000D_
</div>_x000D_
<div id="checkboxes">_x000D_
<label for="one">_x000D_
<input type="checkbox" id="one" />First checkbox</label>_x000D_
<label for="two">_x000D_
<input type="checkbox" id="two" />Second checkbox</label>_x000D_
<label for="three">_x000D_
<input type="checkbox" id="three" />Third checkbox</label>_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
At first we create a select element that shows text "Select an option", and empty element that covers (overlaps) the select element (<div class="overSelect">
). We do not want the user to click on the select element - it would show an empty options. To overlap the element with other element we use CSS position property with value relative | absolute.
To add the functionality we specify a JavaScript function that is called when the user clicks on the div that contains our select element (<div class="selectBox" onclick="showCheckboxes()">
).
We also create div that contains our checkboxes and style it using CSS. The above mentioned JavaScript function just changes <div id="checkboxes">
value of CSS display property from "none" to "block" and vice versa.
The solution was tested in the following browsers: Internet Explorer 10, Firefox 34, Chrome 39. The browser needs to have JavaScript enabled.
CSS positioning
How to overlay one div over another div
http://www.w3schools.com/css/css_positioning.asp
CSS display property
If for matching identical images ( same size/orientation )
// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
// Calculate the L2 relative error between images.
double errorL2 = norm( A, B, CV_L2 );
// Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
double similarity = errorL2 / (double)( A.rows * A.cols );
return similarity;
}
else {
//Images have a different size
return 100000000.0; // Return a bad value
}
//Hope you find it useful, it contain too many things
string smtpAddress = "smtp.xyz.com";
int portNumber = 587;
bool enableSSL = true;
string m_userName = "[email protected]";
string m_UserpassWord = "56436578";
public void SendEmail(Customer _customers)
{
string emailID = [email protected];
string userName = DemoUser;
string emailFrom = "[email protected]";
string password = "qwerty";
string emailTo = emailID;
// Here you can put subject of the mail
string subject = "Registration";
// Body of the mail
string body = "<div style='border: medium solid grey; width: 500px; height: 266px;font-family: arial,sans-serif; font-size: 17px;'>";
body += "<h3 style='background-color: blueviolet; margin-top:0px;'>Aspen Reporting Tool</h3>";
body += "<br />";
body += "Dear " + userName + ",";
body += "<br />";
body += "<p>";
body += "Thank you for registering </p>";
body += "<p><a href='"+ sURL +"'>Click Here</a>To finalize the registration process</p>";
body += " <br />";
body += "Thanks,";
body += "<br />";
body += "<b>The Team</b>";
body += "</div>";
// this is done using using System.Net.Mail; & using System.Net;
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
There are a lot of ways to accomplish this, and this is but one of them.
$("table").find("tbody td").eq(0).children().first()
I was getting a lot of empty text nodes with the accepted filter function. If you're only interested in selecting text nodes that contain non-whitespace, try adding a nodeValue
conditional to your filter
function, like a simple $.trim(this.nodevalue) !== ''
:
$('element')
.contents()
.filter(function(){
return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
});
Or to avoid strange situations where the content looks like whitespace, but is not (e.g. the soft hyphen ­
character, newlines \n
, tabs, etc.), you can try using a Regular Expression. For example, \S
will match any non-whitespace characters:
$('element')
.contents()
.filter(function(){
return this.nodeType === 3 && /\S/.test(this.nodeValue);
});
If I remember well, some CSS properties you apply to table
are not inherited as expected. So you should indeed apply the style directly to td
,tr
and th
elements.
If you need to add styling to each column, use the <col>
element in your table.
See an example here: http://jsfiddle.net/GlauberRocha/xkuRA/2/
NB: You can't have a margin
in a td
. Use padding
instead.
Pure Bash, without an extra process:
for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
echo $COUNTER
done
Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
I had this problem on my developent environment with Visual Studio.
What helped me was to Clean Solution
in Visual Studio and then do a rebuild.
list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]
def printer(*lists):
for _list in lists:
for ele in _list:
print(ele, end = ", ")
print()
printer(list1, list2, list3)
player['score']
is your problem. player is apparently a list
which means that there is no 'score' element. Instead you would do something like:
name, score = player[0], player[1]
return name + ' ' + str(score)
Of course, you would have to know the list indices (those are the 0 and 1 in my example).
Something like player['score']
is allowed in python, but player
would have to be a dict
.
You can read more about both lists and dicts in the python documentation.
Show as decimal Select ifnull(format(100.00, 1, 'en_US'), 0) 100.0
Show as Percentage Select concat(ifnull(format(100.00, 0, 'en_US'), 0), '%') 100%
The best and easy way to get the activity context is putting .this
after the name of the Activity. For example: If your Activity's name is SecondActivity
, its context will be SecondActivity.this
For quick and simple solution Try:
set extra data to a boolean value.
extraData={this.state.refresh}
Toggle the value of boolean state when you want to re-render/refresh list
this.setState({
refresh: !this.state.refresh
})
You can create your own. For example:
Create a view with white background and rounded corners:
var view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
view.backgroundColor = UIColor.whiteColor()
view.layer.cornerRadius = 10
Add two subviews, a UIActivityIndicatorView
and a UILabel
:
var wait = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
wait.color = UIColor.blackColor()
wait.hidesWhenStopped = false
var text = UILabel(frame: CGRect(x: 60, y: 0, width: 200, height: 50))
text.text = "Processing..."
view.addSubview(wait)
view.addSubview(text)
OR
makes sense (from readability point of view), when there are less values to be compared.
IN
is useful esp. when you have a dynamic source, with which you want values to be compared.
Another alternative is to use a JOIN
with a temporary table.
I don't think performance should be a problem, provided you have necessary indexes.
You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.
I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.
In this way you can select all the options in any dropdowns.
driver.get("https://www.spectrapremium.com/en/aftermarket/north-america")
print( "The title is : " + driver.title)
inputs = Select(driver.find_element_by_css_selector('#year'))
input1 = len(inputs.options)
for items in range(input1):
inputs.select_by_index(items)
time.sleep(1)
What kind of processing are you trying to do? You can do XmlDocument doc = new XmlDocument();
followed by doc.Load(filename)
. Then the XML document can be parsed in memory.
Read here for more information on XmlDocument:
This would work just fine, set the height to desired pixel
#inner-right{
height: 100px;
overflow:auto;
}
To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).
Then I register a pre- or post-build event in Visual Studio...
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"
For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).
To start with git log -1 --pretty='%s'
But the below one covers all the cases,
git log --pretty='format:%Creset%s' --no-merges -1
Paste & see for yourself
This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like
so_far = " " * len(word)
?
Edit:
try something like
print "%d / %d" % (new, so_far)
before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.
Now dstat provides the feature to find out in your running system which process is candidate for getting killed by oom mechanism
dstat --top-oom
--out-of-memory---
kill score
java 77
java 77
java 77
and as per man page
--top-oom
show process that will be killed by OOM the first
Scrollbar CSS styles are an oddity invented by Microsoft developers. They are not part of the W3C standard for CSS and therefore most browsers just ignore them.
Finally, I found the solution to my problem.
I looked into the Magento system log file (var/log/system.log). There I saw the exact error.
The error is as below:-
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227
Actually, I had this error before. But, error display message like Error: 404 Not Found
was new to me.
The reason for this error is that store_id
and website_id
for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.
Open PhpMyAdmin and run the following query in your database:-
SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;
I have written about this problem and solution over here:-
Magento: Solution to "Error: 404 Not Found" in Admin Login Page
val() returns the value of the <select>
element, i.e. the value
attribute of the selected <option>
element.
Since you actually want the inner text of the selected <option>
element, you should match that element and use text() instead:
var nationality = $("#dancerCountry option:selected").text();
https://stackoverflow.com/a/16350929/11860907
If you add e.SuppressKeyPress = true;
as shown in the answer in this link you will suppress the annoying ding sound that occurs.
use #include "ClasseAusiliaria.c"
[Dont use angle brackets (< >) ]
and I prefer save file with .h
extension in the same Directory/folder.
#include "ClasseAusiliaria.h"
name
attribute points to the column containing the asociation, i.e. column name of the foreign keyreferencedColumnName
attribute points to the related column in asociated/referenced entity, i.e. column name of the primary keyYou are not required to fill the referencedColumnName
if the referenced entity has single column as PK, because there is no doubt what column it references (i.e. the Address
single column ID).
@ManyToOne
@JoinColumn(name="ADDR_ID")
public Address getAddress() { return address; }
However if the referenced entity has PK that spans multiple columns the order in which you specify @JoinColumn
annotations has significance. It might work without the referencedColumnName
specified, but that is just by luck. So you should map it like this:
@ManyToOne
@JoinColumns({
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
public Address getAddress() { return address; }
or in case of ManyToMany
:
@ManyToMany
@JoinTable(
name="CUST_ADDR",
joinColumns=
@JoinColumn(name="CUST_ID"),
inverseJoinColumns={
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
}
)
Two queries generated by Hibernate of the same join table mapping, both without referenced column specified. Only the order of @JoinColumn
annotations were changed.
/* load collection Client.emails */
select
emails0_.id_client as id1_18_1_,
emails0_.rev as rev18_1_,
emails0_.id_email as id3_1_,
email1_.id_email as id1_6_0_
from client_email emails0_
inner join email email1_ on emails0_.id_email=email1_.id_email
where emails0_.id_client='2' and
emails0_.rev='18'
/* load collection Client.emails */
select
emails0_.rev as rev18_1_,
emails0_.id_client as id2_18_1_,
emails0_.id_email as id3_1_,
email1_.id_email as id1_6_0_
from client_email emails0_
inner join email email1_ on emails0_.id_email=email1_.id_email
where emails0_.rev='2' and
emails0_.id_client='18'
We are querying a join table to get client's emails. The {2, 18}
is composite ID of Client. The order of column names is determined by your order of @JoinColumn
annotations. The order of both integers is always the same, probably sorted by hibernate and that's why proper alignment with join table columns is required and we can't or should rely on mapping order.
The interesting thing is the order of the integers does not match the order in which they are mapped in the entity - in that case I would expect {18, 2}
. So it seems the Hibernate is sorting the column names before it use them in query. If this is true and you would order your @JoinColumn
in the same way you would not need referencedColumnName
, but I say this only for illustration.
Properly filled referencedColumnName
attributes result in exactly same query without the ambiguity, in my case the second query (rev = 2
, id_client = 18
).
If you have a rooted device you can use kill
command
Connect to your device with adb:
adb shell
Once the session is established, you have to escalade privileges:
su
Then
ps
will list running processes. Note down the PID of the process you want to terminate. Then get rid of it
kill PID
public static void zipFromTxt(String zipFilePath, String txtFilePath) {
Assert.notNull(zipFilePath, "Zip file path is required");
Assert.notNull(txtFilePath, "Txt file path is required");
zipFromTxt(new File(zipFilePath), new File(txtFilePath));
}
public static void zipFromTxt(File zipFile, File txtFile) {
ZipOutputStream out = null;
FileInputStream in = null;
try {
Assert.notNull(zipFile, "Zip file is required");
Assert.notNull(txtFile, "Txt file is required");
out = new ZipOutputStream(new FileOutputStream(zipFile));
in = new FileInputStream(txtFile);
out.putNextEntry(new ZipEntry(txtFile.getName()));
int len;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
out.flush();
}
} catch (Exception e) {
log.info("Zip from txt occur error,Detail message:{}", e.toString());
} finally {
try {
if (in != null) in.close();
if (out != null) {
out.closeEntry();
out.close();
}
} catch (Exception e) {
log.info("Zip from txt close error,Detail message:{}", e.toString());
}
}
}
This would select 4 in your case
SELECT ID FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)
This would delete them
DELETE FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)
There are a couple of important things to know about bash's [[ ]]
construction. The first:
Word splitting and pathname expansion are not performed on the words between the
[[
and]]
; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
The second thing:
An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.
Consequently, $v
on either side of the =~
will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.
So if you write: [[ $x =~ [$0-9a-zA-Z] ]]
, the $0
inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0
ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]]
, then the right-hand side will be treated as an ordinary string, not a regex (and $0
will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]
Similarly, the expression between the [[
and ]]
is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]
. Other characters similarly need to be escaped, like #
, which would start a comment if not quoted. Of course, you can put the pattern into a variable:
pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...
For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:
# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...
Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:
valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...
!
negates the test, turning it into a "does not match" operator, and a [^...]
regex character class means "any character other than ...
".
The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ]
into $valid
, even if $valid
were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ]
in a character class, it needs to go at the beginning. -
can go at the beginning or the end, so if you need both ]
and -
, you need to start with ]
and end with -
, leading to the regex "I know what I'm doing" emoticon: [][-]
)
The syntax of the class creation statement:
class <ClassName>(superclass):
#code follows
In the absence of any other superclasses that you specifically want to inherit from, the superclass
should always be object
, which is the root of all classes in Python.
object
is technically the root of "new-style" classes in Python. But the new-style classes today are as good as being the only style of classes.
But, if you don't explicitly use the word object
when creating classes, then as others mentioned, Python 3.x implicitly inherits from the object
superclass. But I guess explicit is always better than implicit (hell)
Primitive data type
The primitive data type is a basic type provided by a programming language as a basic building block. So it's predefined data types. A primitive type has always a value. It storing simple value.
It specifies the size and type of variable values, so the size of a primitive type depends on the data type and it has no additional methods.
And these are reserved keywords in the language. So we can't use these names as variable, class or method name. A primitive type starts with a lowercase letter. When declaring the primitive types we don't need to allocate memory. (memory is allocated and released by JRE-Java Runtime Environment in Java)
+================+=========+===================================================================================+
| Primitive type | Size | Description |
+================+=========+===================================================================================+
| byte | 1 byte | Stores whole numbers from -128 to 127 |
+----------------+---------+-----------------------------------------------------------------------------------+
| short | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
+----------------+---------+-----------------------------------------------------------------------------------+
| int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
+----------------+---------+-----------------------------------------------------------------------------------+
| long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
+----------------+---------+-----------------------------------------------------------------------------------+
| float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
+----------------+---------+-----------------------------------------------------------------------------------+
| double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
+----------------+---------+-----------------------------------------------------------------------------------+
| char | 2 bytes | Stores a single character/letter or ASCII values |
+----------------+---------+-----------------------------------------------------------------------------------+
| boolean | 1 bit | Stores true or false values |
+----------------+---------+-----------------------------------------------------------------------------------+
Reference data type
Reference data type refers to objects. Most of these types are not defined by programming language(except for String, arrays in JAVA). Reference types of value can be null. It storing an address of the object it refers to. Reference or non-primitive data types have all the same size. and reference types can be used to call methods to perform certain operations.
when declaring the reference type need to allocate memory. In Java, we used new
keyword to allocate memory, or alternatively, call a factory method.
Example:
List< String > strings = new ArrayList<>() ; // Calling `new` to instantiate an object and thereby allocate memory.
Point point = Point(1,2) ; // Calling a factory method.
@chepner make a good point that logger
is dedicated to logging messages.
I do need to mention that @Thomas Haratyk simply inquired why I didn't simply use echo
.
At the time, I didn't know about echo, as I'm learning shell-scripting
, but he was right.
My simple solution is now this:
#!/bin/bash
echo "This logs to where I want, but using echo" > /var/log/mycustomlog
The example above will overwrite the file after the >
So, I can append to that file with this:
#!/bin/bash
echo "I will just append to my custom log file" >> /var/log/customlog
Thanks guys!
/var/log/
, but I'm sure there are other good ideas out there. And since I didn't create a daemon, /var/log/
probably isn't the best place for my custom log file. (just saying)Use absolute path:
extension_dir="C:\full\path\here"
Value is not null, but DBNull.Value.
object value = cmd.ExecuteScalar();
if(value == DBNull.Value)
Assuming you are using ssh to connect rsync, what about to send a ssh command before:
ssh user@server mkdir -p existingdir/newdir
if it already exists, nothing happens
You can use a lookaround:
^(?=.*[A-Za-z0-9])[A-Za-z0-9 _]*$
It will check ahead that the string has a letter or number, if it does it will check that the rest of the chars meet your requirements. This can probably be improved upon, but it seems to work with my tests.
UPDATE:
Adding modifications suggested by Chris Lutz:
^(?=.*[^\W_])[\w ]*$/
Use the format()
function:
>>> format(14, '#010b')
'0b00001110'
The format()
function simply formats the input following the Format Specification mini language. The #
makes the format include the 0b
prefix, and the 010
size formats the output to fit in 10 characters width, with 0
padding; 2 characters for the 0b
prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format()
and put the second argument for the format()
function after the colon of the placeholder {:..}
:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format()
:
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...)
communicates the intent better.
If you did not want the 0b
prefix, simply drop the #
and adjust the length of the field:
>>> format(14, '08b')
'00001110'
Just add Axios.defaults.withCredentials=true
instead of ({credentials: true}
) in client side,
and change app.use(cors())
to
app.use(cors(
{origin: ['your client side server'],
methods: ['GET', 'POST'],
credentials:true,
}
))
You should have a look on the -regextype
argument of find
, see manpage:
-regextype type
Changes the regular expression syntax understood by -regex and -iregex
tests which occur later on the command line. Currently-implemented
types are emacs (this is the default), posix-awk, posix-basic,
posix-egrep and posix-extended.
I guess the emacs
type doesn't support the [[:digit:]]
construct. I tried it with posix-extended
and it worked as expected:
find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'
You can use an object as a map:
var hasName = ({
"true" : "Y",
"false" : "N"
})[name];
This also scales nicely for many options
var hasName = ({
"true" : "Y",
"false" : "N",
"fileNotFound" : "O"
})[name];
(Bonus point for people getting the reference)
Note: you should use actual booleans instead of the string value "true" for your variables indicating truth values.
Not sure if this is cheating or not:
window.say = function(a) { alert(a); };
var a = "say('hello')";
var p = /^([^(]*)\('([^']*)'\).*$/; // ["say('hello')","say","hello"]
var fn = window[p.exec(a)[1]]; // get function reference by name
if( typeof(fn) === "function")
fn.apply(null, [p.exec(a)[2]]); // call it with params
You can activate the modal without writing any JavaScript simply via data attributes.
The option "show" set to true shows the modal when initialized:
<div class="modal fade" tabindex="-1" role="dialog" data-show="true"></div>
For Ubuntu 16: /etc/mysql/mysql.conf.d/mysqld.cnf
You can use jQuery's mouseenter and mouseleave events. You can set a flag when the mouse enters the desired area and unset the flag when it leaves the area.
Simple solution (ES6)
If you don't have duplicate element
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el === elem);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};