title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
How to display image from URL in Android | <p>I use this code to display image from url it work but the image is stored in device this is the problem because I want to display this image only if the user is connected to internet</p>
<pre><code>ImageView imageView=(ImageView) findViewById(R.id.imageView3);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);
</code></pre>
<p>How do I display image from URL in Android?</p> | 0 |
Validating a list using Java8 stream | <p>Lets say I have a <code>List<Foo></code> objects and there is a <code>User</code> object inside <code>Foo</code>:</p>
<pre><code>public class Foo {
public User user;
}
public class User {
int id;
int typeId;
}
</code></pre>
<p>Lets say I have a method that takes in a User object and a List objects. Is there an efficient way in Java8 to stream the Foo objects and return fast if any of the Foo objects' User is not the same as the User passed into the method?</p>
<pre><code>public boolean validate(User loggedInUser, List<Foo> objectsToVerify);
</code></pre>
<p>The idea I have is to do:</p>
<pre><code>return objectsToVerify.stream().filter(o -> o.user != loggedInUser).collect(Collections.toList()).isEmpty();
</code></pre> | 0 |
Generic class with generic constructor? | <p>I have a generic class. The constructor needs to accept an argument that is another instance of the same class. The problem is that the other instance can have a different generics type.</p>
<p>Looks like C# allows me to have a method with it's own generics type, but this doesn't appear allowed for the constructor.</p>
<pre><code>public class MyClass<T>
{
public MyClass<T2>(MyClass<T2> parent = null)
{
}
// ... Additional stuff
}
</code></pre>
<p>The code above tells me <code>T2</code> is undefined. It doesn't accept it as a method type.</p>
<p>One approach would be to add a second generic type to my class. But this is awkward and, in many cases, the argument will be <code>null</code> and there is not type.</p>
<p>Does anyone see a simple way around this?</p> | 0 |
Saving a base64 string as an image into a folder on server using C# and Web Api | <p>I am posting a Base64 string via Ajax to my Web Api controller. Code below</p>
<p>Code for converting string to Image</p>
<pre><code>public static Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
</code></pre>
<p>Controller Code</p>
<pre><code>public bool SaveImage(string ImgStr, string ImgName)
{
Image image = SAWHelpers.Base64ToImage(ImgStr);
String path = HttpContext.Current.Server.MapPath("~/ImageStorage"); //Path
//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = ImgName + ".jpg";
//set the image path
string imgPath = Path.Combine(path, imageName);
image.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
}
</code></pre>
<p>This is always failing with a generic GDI+ error. What am I missing ? Is there a better way to save a specific string as an image on a folder ?</p> | 0 |
[Android]-Resize image to upload to server | <p>My sever limit image size to upload image (2MB).
I want to upload image from android device to server. I want to resize image. What's the best way I can do resize image?</p> | 0 |
How to set laravel 5.3 logout redirect path? | <p>Is there no elegant solution to redirect to a specific page after logging out in Laravel 5.3? </p>
<p>The function being called is from the trait <strong>AuthenticatesUsers</strong>: </p>
<pre><code>public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/');
}
</code></pre>
<p>This is a default function from the core of laravel. So I have to override the whole function I cannot edit the core.
But isn't there a more simpler solution, cause it feel like overkill to manually logout, flush and regenerate again.</p>
<p>Worked the answers out in an article:
<a href="https://codeneverlied.com/how-to-set-logout-redirect-path-in-laravel-5-8-and-before/" rel="noreferrer">https://codeneverlied.com/how-to-set-logout-redirect-path-in-laravel-5-8-and-before/</a></p> | 0 |
Numpy Array Set Difference | <p>I have two numpy arrays that have overlapping rows:</p>
<pre><code>import numpy as np
a = np.array([[1,2], [1,5], [3,4], [3,5], [4,1], [4,6]])
b = np.array([[1,5], [3,4], [4,6]])
</code></pre>
<p>You can assume that:</p>
<ol>
<li>the rows are sorted</li>
<li>the rows within each array is unique</li>
<li>array <code>b</code> is always subset of array <code>a</code></li>
</ol>
<p>I would like to get an array that contains all rows of <code>a</code> that are not in <code>b</code>.</p>
<p>i.e.,:</p>
<pre><code>[[1 2]
[3 5]
[4 1]]
</code></pre>
<p>Considering that <code>a</code> and <code>b</code> can be very, very large, what is the most efficient method for solving this problem?</p> | 0 |
“Error HRESULT E_FAIL has been returned from a call to a COM component” windows forms c# | <p>I am making a desktop application in windows forms and i dont know why appear the error:</p>
<p>“Error HRESULT E_FAIL has been returned from a call to a COM component”</p>
<p>On the designer of all my user controls and windows.</p>
<p>I know that are others threads with this problem but i checked them and i didnt get a solution.</p>
<p>I tried deleting ProjectTemplateCache and clearing the build and rebuild but it doesnt work. I read that i can delete .suo and .user files but in my project folder doesnt exists that fields. I am using Visual Studio 2015.</p>
<p>Someone knows how to fix it?</p> | 0 |
How to disable tableView scrolling? | <p>When I add a tableView in a viewController by default the tableView scrolls, but I want it static. Is it possible?</p>
<p>Here is my code:</p>
<pre><code>func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return names.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableview.dequeueReusableCellWithIdentifier("cell") as! TableViewCell
cell.username.text = names[indexPath.row]
return cell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 50.0
}
</code></pre> | 0 |
Logical Or/bitwise OR in pandas Data Frame | <p>I am trying to use a Boolean mask to get a match from 2 different dataframes.
U</p>
<p>Using the logical OR operator:</p>
<pre><code>x = df[(df['A'].isin(df2['B']))
or df['A'].isin(df2['C'])]
Output:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>However using the bitwise OR operator, the results are returned successfully. </p>
<pre><code>x = df[(df['A'].isin(df2['B']))
| df['A'].isin(df2['C'])]
Output: x
</code></pre>
<p>Is there a difference in both and would bitwise OR be the best option here? Why doesn't the logical OR work?</p> | 0 |
Using ehcache 3 with Spring Annotations (not using Spring Boot) | <p>I'm trying to get Ehcache 3 working with Spring 4 without using Spring boot.</p>
<p><a href="http://www.ehcache.org/blog/2016/05/18/ehcache3_jsr107_spring.html" rel="noreferrer">Here is a working example out there which uses Spring Boot</a>, but I'm working on an existing application which is not using Spring Boot.</p>
<p>The problem is that spring-context-support (which adds Spring's cache annotations) expects the Ehcache's CacheManager to be on this classpath: net.sf.ehcache.CacheManager</p>
<p>However, in Ehcache 3, the CacheManager class resides on another classpath: org.ehcache.CacheManager.</p>
<p>So, basically spring-context-support does not support Ehcache 3. And you would have to use the JSR-107 annotations directly, not the annotations provided by Spring.</p>
<p>But apparently it works with Spring Boot. Perhaps there is a way to make it work with a standard Spring Application as well. That's what I'm hoping. I really want to be using Spring's own annotations instead of the JSR-107 annotations.</p> | 0 |
Using Numpy's random.choice to randomly remove item from list | <p>According to the <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html" rel="nofollow">http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html</a>, using the <code>replace = False</code> with Numpy's <code>random.choice</code> method should make the sample without replacement. However, this does not seem to work for me:</p>
<pre><code>In [33]: import numpy as np
In [34]: arr = range(5)
In [35]: number = np.random.choice(arr, replace = False)
In [36]: arr
Out[36]: [0, 1, 2, 3, 4]
</code></pre>
<p>The array <code>arr</code> is still <code>range(5)</code> after sampling, and not missing a (random) number as I would expect. How could I sample a number from <code>range(5)</code> without replacement? </p> | 0 |
what can you do when window.location.href returns null | <p>window.location.href returns null. Is there another way to get the current window url that is more solid and will work everytime?</p> | 0 |
Change language programmatically (Android N 7.0 - API 24) | <p>I'm using the following code to set specific language in my app. Language is saved into <code>SharedPreferences</code> within the app. <strong>And it works perfectly up to API level 23.</strong> With Android N <code>SharedPreferences</code> works well too, it returns the correct language code-string, but it does not change the locale (sets default language of the phone). What could be wrong?</p>
<p><strong>Update 1:</strong> When I use <code>Log.v("MyLog", config.locale.toString());</code> immediately after <code>res.updateConfiguration(config, dm)</code> it returns correct locale, but language of the app does not changed.</p>
<p><strong>Update 2:</strong> I also mentioned that if I change locale and then restart the activity (using new intent and finish on the old one), it changes the language properly, it even shows correct language after rotation. But when I close the app and open it again, I get default language. It's weird.</p>
<pre><code>public class ActivityMain extends AppCompatActivity {
//...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set locale
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
String lang = pref.getString(ActivityMain.LANGUAGE_SAVED, "no_language");
if (!lang.equals("no_language")) {
Resources res = context.getResources();
Locale locale = new Locale(lang);
Locale.setDefault(locale);
DisplayMetrics dm = res.getDisplayMetrics();
Configuration config = res.getConfiguration();
if (Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale);
} else {
config.locale = locale;
}
}
res.updateConfiguration(config, dm);
setContentView(R.layout.activity_main);
//...
}
//...
}
</code></pre>
<p><strong>Update 3:</strong> <strong>THE ANSWER IS ALSO HERE:</strong> <a href="https://stackoverflow.com/a/40849142/3935063">https://stackoverflow.com/a/40849142/3935063</a></p> | 0 |
Checking file size gt 0 in Powershell | <p>I did search for help regarding my subject but did not find something close to what I need, then here is my doubt:</p>
<p>I need to check the size of a file in a specific folder, if it´s greater than 0 bytes, it´s OK to continue the process, else, abort it writing an output message and sending fail code = 1.</p>
<p>I´ve tried the below but no success on writing the message to the log:</p>
<pre><code>$FileExists1 = "D:\TEST\FILE\test.txt"
IF (Test-Path $FileExists1) {
If ((Get-Item $FileExists1).length -gt 0kb) {
Write-Output [$(Get-Date)]:" FILE IS OK FOR PROCESSING! - RC = $rc"
}
Else {
$rc = 1
Write-Output [$(Get-Date)]:" FILE HAS 0 BYTES AT D:\TEST\FILE\"
Write-Output [$(Get-Date)]:" VALIDATION FINISHED - RC = $rc"
Exit $rc
}
}
</code></pre>
<p>Does any of you know what I could do?</p>
<p>Appreciate your help!</p> | 0 |
RecyclerView scrolling on insert | <p>I am trying to use <code>RecyclerView</code> to create a chat application. I am using a <code>LinearLayoutManager</code> with <code>setReverseLayout(true)</code>. </p>
<p>When I am scrolled all the way to the bottom (which is the dataset start = newest message) and a new message is inserted into the dataset, the item appears at the bottom of the list as expected (the view is scrolled up to make room for the new item).</p>
<p>The problem I have is when I have scrolled up to see the older messages. When a new message is inserted to the beginning of the dataset, the view is scrolled up by approximately one message height, even though that message isn't even rendered since it's out of the viewport's range.</p>
<p><strong>How can I keep the scrolling behavior, when the view is scrolled to the bottom, but disable it when I have scrolled to the older messages?</strong></p>
<p><strong>UPDATE:</strong>
I also made a small app, where this problem is reproduced:
<a href="https://github.com/ehehhh/RecyclerViewProblem" rel="noreferrer">https://github.com/ehehhh/RecyclerViewProblem</a></p>
<p><strong>UPDATE 2:</strong> I committed the fix that worked to the repo I made as well.</p>
<p>Relevant code (<em>hopefully</em>):</p>
<pre><code>compile 'com.android.support:recyclerview-v7:24.2.0'
</code></pre>
<p>XML: </p>
<pre><code><android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="8dp"
android:paddingTop="8dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</code></pre>
<p><em>RecyclerView</em> init code:</p>
<pre><code>layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setScrollContainer(true);
recyclerView.setLayoutAnimation(null);
recyclerView.setItemAnimator(null);
adapter = new ChatAdapter(...);
recyclerView.setAdapter(adapter);
</code></pre>
<p><em>Adapter</em>:</p>
<pre><code>public class ChatAdapter extends RecyclerView.Adapter<ChatViewHolder> {
private List<MessageWrapper> dataset;
public ChatAdapter(List<MessageWrapper> dataset, ...) {
this.dataset = dataset;
setHasStableIds(true);
}
...
@Override
public long getItemId(int position) {
return dataset.get(position).getId();
}
@Override
public int getItemCount() {
return dataset.size();
}
public void datasetChanged(List<MessageWrapper> dataset) {
this.dataset = dataset;
notifyDataSetChanged();
}
}
</code></pre>
<p>When a new item is added to the dataset, I just call the <code>datasetChanged</code> method in the adapter.</p> | 0 |
Vuex Action vs Mutations | <p>In Vuex, what is the logic of having both "actions" and "mutations?"</p>
<p>I understand the logic of components not being able to modify state (which seems smart), but having both actions and mutations seems like you are writing one function to trigger another function, to then alter state. </p>
<p>What is the difference between "actions" and "mutations," how do they work together, and moreso, I'm curious why the Vuex developers decided to do it this way?</p> | 0 |
Pagination at top and bottom with DataTables | <p>I'm using SB Admin 2 theme, with DataTables jQuery plugin. Is it possible to have pagination positioned at the <strong>top</strong> and at the <strong>bottom</strong> of a table, <strong>at the same time</strong>? If it is, how could I achieve it? This is what I currently have as a working code:</p>
<pre><code><script>
$('#data-table').DataTable({
responsive: true,
"pageLength": 25,
"columnDefs": [ {
"targets" : 'no-sort',
"orderable": false,
}],
"language": {
"lengthMenu": "Show _MENU_ items per page",
"zeroRecords": "Nothing found. Please change your search term",
"info": "Page _PAGE_ of _PAGES_",
"infoEmpty": "No results",
"infoFiltered": "(filtered out of _MAX_)",
"search": "Search:",
"paginate": {
"first": "First",
"last": "Last",
"next": ">>",
"previous": "<<"
}
}
});
</script>
</code></pre>
<p>I have tried using what the official site <a href="https://datatables.net/examples/advanced_init/dom_multiple_elements.html" rel="noreferrer">suggests</a> (removing the code I posted, and then doing a simple copy/paste, and changing the id), but it did absolutely nothing. I'm guessing that I'm doing something wrong, but I have no idea what.</p> | 0 |
How to access the key values in python dictionary with variables? | <p>I have a dict whose keys are numbers. It looks like this:</p>
<pre><code>{'1': 3, '2': 7, '3', 14}
</code></pre>
<p>I need to access the value of each key with a variable, but get stuck because of the quotation marks of keys. How can I do that?</p> | 0 |
Set auto height in PHPExcel not working | <p>I am generating Excel using PHPExcel.</p>
<p>All Code Works Fine.But Auto height code is not Working.</p>
<p>I have tried following code.</p>
<p>Apply row height on specific row</p>
<pre><code>$objPHPExcel->getActiveSheet()->getRowDimension('7')->setRowHeight(-1);
</code></pre>
<p>Apply row height on for all row</p>
<pre><code>$objPHPExcel->getActiveSheet()->getDefaultRowDimension(1)->setRowHeight(-1);
</code></pre>
<p>I have also tried word wrap property with it.</p>
<pre><code>$objPHPExcel->getActiveSheet()
->getStyle('B7')
->getAlignment()
->setWrapText(true);
</code></pre>
<p>But it give me result as below: </p>
<p><a href="https://i.stack.imgur.com/SQc5e.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SQc5e.png" alt="enter image description here"></a></p>
<blockquote>
<p>Note : Working in MS office,Not Working in Apache open Office and
LibreOffice</p>
</blockquote> | 0 |
Input variable in a router-outlet component | <p>I wanted to know if you guys now a way to have the @Input + ngOnChanges() combination or something doing the same inside a component in .</p>
<p>Basically, I have set a <code>logged: boolean</code> variable in my AppComponent and in my template I have :</p>
<pre><code><router-outlet></router-outlet>
<login [logged]="logged"></login>
</code></pre>
<p>What I want is to be able to <em>watch</em> that <code>logged</code> variable inside a component in the router-outlet so I make stuff here only when logged is as set as true.</p>
<p>I've tried to put <code><router-outlet [logged]="logged"></router-outlet></code> but that doesn't work, and using a variable in a service seems not to fit the ngOnChanges() watch.</p>
<p>Has anyone an idea ? Thanks !</p> | 0 |
Specifying password in .ssh/config file? | <p>Is it possible to specify password inside my .ssh/config file? Something like</p>
<pre><code>Host host1
User user1
Pass password
</code></pre>
<p>All resources I found recommend to use keys instead, but that's not an option for me, I want to use password.</p>
<p>If it's not possible with stock openssh, are there any patches laying around that would allow this?</p>
<p>EDIT: reason I need to use password is to get access to network drives when connection to cygwin sshd from linux.</p> | 0 |
Getting error while running Android Studio Default **Map Application** | <p>I am running android studio template code for Maps Application. But getting error. I am following this link to run just a simple maps application.</p>
<blockquote>
<blockquote>
<p><a href="https://developers.google.com/maps/documentation/android-api/utility/setup" rel="nofollow noreferrer">https://developers.google.com/maps/documentation/android-api/utility/setup</a></p>
</blockquote>
</blockquote>
<p>Following is the error. </p>
<blockquote>
<blockquote>
<p>Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536</p>
</blockquote>
</blockquote>
<p>My question is why I am getting this error, Since I am following all the steps provided by the official Google link above.</p>
<p>Here is my Gradle Code for app.</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "app.com.example.android.mapsnew"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
// compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.google.android.gms:play-services:9.4.0'
compile 'com.google.android.gms:play-services-maps:9.4.0'
testCompile 'junit:junit:4.12'
}
</code></pre>
<p>Here is the image of this error.</p>
<p><a href="https://i.stack.imgur.com/WzffP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WzffP.png" alt="enter image description here"></a></p>
<p>Kind Regards,
Abr.</p> | 0 |
Webpack not loading png images | <p>I have few images in src folder:</p>
<pre><code>src/img/favicon.png
src/img/profpic.png
</code></pre>
<p>In index.html file I will point as </p>
<pre><code> <link rel="shortcut icon" href="img/favicon.png" />
</code></pre>
<p>In some html files I will point as</p>
<pre><code> <img src="img/profpic.png" />
</code></pre>
<p>I am trying to load images, fonts via webpack. Below is my webpack.config</p>
<pre><code>module.exports = {
context: path.resolve('src'),
entry: {
app: ["./index.ts"]
},
output: {
path: path.resolve('build'),
filename: "appBundle.js"
},
devServer: {
contentBase: 'src'
},
watch: true,
module: {
preLoaders: [
{
test: /\.ts$/,
loader: "tslint"
}
],
loaders: [
{test: /\.ts(x?)$/, exclude: /node_modules/,loaders: ['ng-annotate-loader','ts-loader']},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.scss$/,
loader: 'style!css!sass'
}, {
test: /\.html$/,
exclude: /node_modules/,
loader: 'raw'
}, {
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=1000000&mimetype=application/font-woff'
}, {
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader'
}, {
test: /\.json$/,
loader: "json-loader"
}, {
test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'
}
];
}
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
inject: 'body',
hash: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.jquery': 'jquery'
})
],
resolve: {
extensions: ['', '.js', '.es6', '.ts']
}
}
</code></pre>
<p>Trying to load the images/fonts to webpack output folder. Its not throwing any error. Its successfully building but in build which is my webpack output folder font is loading fine but images are not loading</p>
<p><a href="https://i.stack.imgur.com/YKhvK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YKhvK.png" alt="Build Folder after running webpack"></a></p> | 0 |
how to convert formcollection to model in mvc | <p>Is it possible to convert <code>formcollection</code> to a 'model' known?</p>
<pre><code>[HttpPost]
public ActionResult Settings(FormCollection fc)
{
var model=(Student)fc; // Error: Can't convert type 'FormCollection' to 'Student'
}
</code></pre>
<p>NOTE : for some reasons i can't use ViewModel instead.</p>
<p>Here is my code VIEW: Settings.cshtml</p>
<pre><code>@model MediaLibrarySetting
@{
ViewBag.Title = "Library Settings";
var extensions = (IQueryable<MediaLibrarySetting>)(ViewBag.Data);
}
@helper EntriForm(MediaLibrarySetting cmodel)
{
<form action='@Url.Action("Settings", "MediaLibrary")' id='[email protected]' method='post' style='min-width:170px' class="smart-form">
@Html.HiddenFor(model => cmodel.MediaLibrarySettingID)
<div class='input'>
<label>
New File Extension:@Html.TextBoxFor(model => cmodel.Extention, new { @class = "form-control style-0" })
</label>
<small>@Html.ValidationMessageFor(model => cmodel.Extention)</small>
</div>
<div>
<label class='checkbox'>
@Html.CheckBoxFor(model => cmodel.AllowUpload, new { @class = "style-0" })<i></i>&nbsp;
<span>Allow Upload.</span></label>
</div>
<div class='form-actions'>
<div class='row'>
<div class='col col-md-12'>
<button class='btn btn-primary btn-sm' type='submit'>SUBMIT</button>
</div>
</div>
</div>
</form>
}
<tbody>
@foreach (var item in extensions)
{
if (item != null)
{
<tr>
<td>
<label class="checkbox">
<input type="checkbox" value="@item.MediaLibrarySettingID"/><i></i>
</label>
</td>
<td>
<a href="javascript:void(0);" rel="popover" class="editable-click"
data-placement="right"
data-original-title="<i class='fa fa-fw fa-pencil'></i> File Extension"
data-content="@EntriForm(item).ToString().Replace("\"", "'")"
data-html="true">@item.Extention</a></td>
</tr>
}
}
</tbody>
</code></pre>
<p>CONTROLLER:</p>
<pre><code>[HttpPost]
public ActionResult Settings(FormCollection fc)//MediaLibrarySetting cmodel - Works fine for cmodel
{
var model =(MediaLibrarySetting)(fc);// Error: Can't convert type 'FormCollection' to 'MediaLibrarySetting'
}
</code></pre>
<p><code>data-content</code> and <code>data-</code> attributes are bootstrap popover.</p> | 0 |
How to share a folder between my Mac and a Docker container | <p>Been spending some time trying to setup a Docker container with access to a folder on my Mac.</p>
<p>I know that you can use Docker Volumes to connect to a folder in the host, which on Mac ends up being Linux in VirtualBox, with the -v argument to docker run.</p>
<p>And given that, I figured that I could setup a shared folder in VirtualBox, which could then be mapped to the Docker container.</p>
<p>However, I've not been able to get the Shared Folder I've added to VB to show up.</p>
<p>Here's what I've done:</p>
<p>1) Added a Shared Folder in the VB admin </p>
<p><a href="https://i.stack.imgur.com/LVZtG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LVZtG.jpg" alt="VirtualBox Shared Folder config"></a></p>
<p>2) Restarted the VB OS with both docker-machine restart and via the VB app itself</p>
<p>3) Logged into the VB OS via docker-machine ssh</p>
<p>4) Did an ls -l of the root directory </p>
<p>The Users folder (which was there already in VB) shows up, but the folder I added (Projects) does not.</p>
<p>I can't figure out any reason why both folders would not appear. Anyone else having this problem?</p>
<p>Seems like with so many people talking about doing local Development with Docker, and so many devs using Macs, this would be a simple problem. But... alas...not for me so far.</p>
<p>Thanks for any help.</p> | 0 |
How to update image using controller in laravel? | <p>I want to update user image but it's not getting updated. I have used following controller for updating the image.. Can you suggest what's the mistake in controller function? </p>
<p>View part :</p>
<pre><code><div class="form-group">
<label>Image Upload</label>
<input type="file" name="image" id="image"><img src="{{ asset('public/images/' . $course->image) }}" width="200px"/></br>
</div>
</code></pre>
<p>Controller function :</p>
<pre><code>public function update(Request $request, $id)
{
$data=Course::findOrFail($id);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$data->image = $name;
$file->move(public_path().'/images/', $name);
}
$data->course_code = $request['course_code'];
$data->course_title = $request['course_title'];
$data->course_credit = $request['course_credit'];
$data->save();
return redirect('course');
}
</code></pre> | 0 |
How to capture multiple groups in regex? | <p>I am trying to capture following word, number:</p>
<pre><code>stxt:usa,city:14
</code></pre>
<p>I can capture usa and 14 using:</p>
<pre><code>stxt:(.*?),city:(\d.*)$
</code></pre>
<p>However, when text is; </p>
<pre><code>stxt:usa
</code></pre>
<p>The regex did not work. I tried to apply or condition using <strong>|</strong> but it did not work.</p>
<pre><code>stxt:(.*?),|city:(\d.*)$
</code></pre> | 0 |
Install python modules in mac osx | <p>I am new to python. I am using python 3.5 on mac os x el capitan.
I tried using the command 'pip install requests' in the python interpreter IDLE. But it throws invalid 'syntax error'.</p>
<p>I read about installing modules is only possible in the command line.
So I moved to TERMINAL, but no command is working here also.
(I tried 'python -m pip install requests')</p>
<p>I read that mac os x comes with python 2.7 already installed and I ran 'easy_install pip' but it also works on the 2.7 version.
Then there's discussion about the PATH settings also.</p>
<p>Can please anybody explain to me how I can use my current version in TERMINAL window and what is the PATH scenario.</p>
<p>I am familiar with the environment variable settings and adding pythonpath in windows but not on mac.</p> | 0 |
Access to the script '/path/to/script.php' has been denied (see security.limit_extensions) | <p>before let me list what I have tried:</p>
<ul>
<li><a href="https://serverfault.com/questions/402009/fastcgi-error-access-to-the-script-denied">This Answer on ServerFault</a></li>
<li>chmoded /Users/user/portal3 to 777 to see if executes</li>
<li>Created two pools one with root and another with current user</li>
<li>googled </li>
<li>entered ##php in freenode </li>
<li>and lot of other ideas.</li>
</ul>
<p>i have a problem executing php code on a subdirectory inside my home directory.
On Nginx i get this</p>
<pre><code>2016/08/23 09:13:40 [error] 39170#0: *13 FastCGI sent in stderr: "Access to the script
'/Users/user/portal3' has been denied (see security.limit_extensions)" while reading
response header from upstream, client: 127.0.0.1, server: localhost, request:
"GET /portal/v3/index.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9001", host: "localhost"
</code></pre>
<p>On php-fpm this shows </p>
<pre><code>[23-Aug-2016 09:13:40] WARNING: [pool dev] child 8305 said into stderr: "NOTICE: Access to the script '/Users/user/portal3' has been denied (see security.limit_extensions)"
</code></pre>
<p>I have tried everything but I don't have any success running php with Nginx / PHP-FPM on Mac</p>
<p>Ngnix adn PHP-FPM runs as root</p>
<p>PHP-FPM it's configured with two pools:</p>
<ul>
<li>[www]: run as root and works fine, execute php code but their www-root subdirectory is in /var/www</li>
<li>[dev] pool that runs as my current user on MacOS X, listen on port 9001, and is configured to run code in /Users/user/portal3.</li>
</ul>
<h2>php-fpm.ini</h2>
<pre><code>[dev]
user=user
group=staff
listen=127.0.0.1:9001
listen.mode = 0666
pm = ondemand
pm.max_children = 10
pm.process_idle_timeout = 10s
pm.status_path = /status_user
catch_workers_output = yes
security.limit_extensions = .php
</code></pre>
<h2>default (on sites-available) Nginx</h2>
<pre><code>server {
listen 80;
server_name localhost;
###root /var/www/;
access_log /usr/local/etc/nginx/logs/default.access.log main;
access_log /usr/local/etc/nginx/logs/default.scripts.log scripts;
location /portal/v3 {
alias /Users/user/portal3;
location ~ ^/portal/v3/(.+\.php)(/.*)$ {
#alias /Users/user/portal3;
index index.php;
# Mitigate https://httpoxy.org/ vulnerabilities
fastcgi_param HTTP_PROXY "";
fastcgi_pass 127.0.0.1:9001;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$2;#$fastcgi_script_name;
include fastcgi_params;
}
}
location = /info {
allow 127.0.0.1;
deny all;
rewrite (.*) /.info.php;
}
location / {
root /var/www/;
index index.php index.html index.htm;
include /usr/local/etc/nginx/conf.d/php-fpm;
}
error_page 404 /404.html;
error_page 403 /403.html;
}
</code></pre>
<p>i have installed everything using homebrew. Now i'm running out of ideas, i came here to get some help.</p> | 0 |
No 'Access-Control-Allow-Origin' header with ExpressJS to local server | <p>I know that this subject seems to be already answered many time but i really don't understand it.</p>
<ul>
<li>I have an local angular-fullstack app (Express, NodeJs) which has his
<strong>server A</strong> (<em>localhost:9000/</em>).</li>
<li>i have an another local <strong>front app B</strong> (BlurAdmin done with
generator-gulp-angular) (<em>localhost:3000/</em>)</li>
</ul>
<p>My server A was autogenerate with Express and Nodejs:</p>
<pre><code> app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', false);
next();
});
</code></pre>
<p>In my app B, a GET request to my API of serveur A works </p>
<pre><code>$http.get('http://localhost:9000/api/shows')
</code></pre>
<p>But with a PUT request:</p>
<pre><code>$http.put('http://localhost:9000/api/shows/1', object)
</code></pre>
<p>i have the following error:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="http://localhost:9000/api/shows/1" rel="nofollow">http://localhost:9000/api/shows/1</a>. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '<a href="http://localhost:3000" rel="nofollow">http://localhost:3000</a>' is therefore not allowed
access. The response had HTTP status code 403.</p>
</blockquote>
<p>I try with:</p>
<pre><code> $http({
method: "PUT",
url:'http://localhost:9000/api/shows/1',
headers: {
'Content-type': 'application/json'
},
data:object
});
</code></pre>
<p>Not working,</p>
<p>I try with:</p>
<pre><code>res.header('Access-Control-Allow-Origin', '*');
</code></pre>
<p>Not working,</p>
<p>I have installed *ExtensionAllow-Control-Allow-Origin: ** for chrome and that has done nothing (that return just not all the code but only error 403 (forbidden)</p>
<p>I don't really know why this is not working for PUT when it's working with GET.</p>
<p>Have you already had this problem? Thanks!</p>
<p><strong>Updated:1</strong> The result in my Browser:
<strong>for GET</strong> </p>
<pre><code>General:
Request URL:http://localhost:9000/api/shows/1
Request Method:OPTIONS
Status Code:200 OK
Request header:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de-DE;q=0.2,de;q=0.2
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:PUT
Connection:keep-alive
Host:localhost:9000
Origin:http://localhost:3000
Referer:http://localhost:3000/
Response header:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With,content-type
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin:http://localhost:3000
Allow:GET,HEAD,PUT,PATCH,DELETE
Connection:keep-alive
Content-Length:25
Content-Type:text/html; charset=utf-8
</code></pre>
<p><strong>For PUT</strong> request:</p>
<pre><code>general:
Request URL:http://localhost:9000/api/shows/1
Request Method:PUT
Status Code:403 Forbidden
Response Header:
Connection:keep-alive
Content-Encoding:gzip
Content-Type:application/json; charset=utf-8
Date:Thu, 25 Aug 2016 16:29:44 GMT
set-cookie:connect.sid=s%3AsVwxxbO-rwLH-1IBZdFzZK1xTStkDUdw.xuvw41CVkFCRK2lHNlowAP9vYMUwoRfHtc4KiLqwlJk; Path=/; HttpOnly
set-cookie:XSRF-TOKEN=toaMLibU5zWu2CK19Dfi5W0k4k%2Fz7PYY%2B9Yeo%3D; Path=/
Strict-Transport-Security:max-age=31536000; includeSubDomains; preload
Request header:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de-DE;q=0.2,de;q=0.2
Connection:keep-alive
Content-Length:27
Content-Type:application/json
Host:localhost:9000
Origin:http://localhost:3000
Referer:http://localhost:3000/
Request Payload:
{url_name: "myData"}
url_name
:
"myData"
</code></pre>
<p>Thanks for helping</p>
<p><strong>Update 2:</strong> with <em><a href="https://github.com/troygoode/node-cors-server/blob/master/app.js" rel="nofollow">https://github.com/troygoode/node-cors-server/blob/master/app.js</a></em> and the work of @Chris Foster
I have install <code>npm cors --save</code>
in my app.js,
i have now the following code:</p>
<pre><code>import express from 'express';
import cors from 'cors';
var app = express()
var corsOptions = {
origin: 'http://localhost:3000'
}
var issuesoption = {
origin: true,
methods: ['PUT'],
credentials: true,
};
app.use(cors(corsOptions))
app.options('*', cors(issuesoption));
app.put('/api/shows/:id',cors(issuesoption) ,function(req,res){
res.json({
data: 'Issue #2 is fixed.'
});
});
</code></pre>
<p>And that is still not working with:</p>
<pre><code>$http.put("http://localhost:9000/api/shows/1",object)
</code></pre>
<p><strong>BUT</strong> i don't have any 403 error, I have now,</p>
<pre><code>Request URL:http://localhost:9000/api/shows/1
Request Method:PUT
Status Code:200 OK
</code></pre>
<p><strong>But</strong> that doesn't put the data into the server and i have in Preview:</p>
<pre><code>{data: "Issue #2 is fixed."}
</code></pre> | 0 |
Node.js doesnot connect with MySQL, PHPMyAdmin | <p>I'm trying to login to a system which uses mysql to store username and password but the login page is in manager.js file as below:</p>
<pre><code>var express = require('express');
var router = express.Router();
var async = require('async');
var util = require('../utils/util');
var db = require('../utils/database');
var connection = db.connection();
router.get('/login', function (req, res) {
if (req.session.manager) {
return res.redirect('/');
}
if (req.query.tip == 'error') {
var tip = 'username or password incorrect!';
} else {
var tip = null;
}
res.render('login', { tip: tip });
});
router.post('/login', function (req, res) {
var username = req.body.username;
var password = req.body.password;
var sql = 'SELECT * FROM restaurant_accounts WHERE ra_name=?';
connection.query(sql, [username], function (err, result) {
if (err) throw err;
if (result.length == 0) {
return res.redirect('/manager/login?tip=error');
}
var account = result[0];
if (!util.checkHash(password, account.ra_password)) {
return res.redirect('/manager/login?tip=error');
}
connection.query('SELECT * FROM restaurants WHERE rest_owner_id=?', [account.ra_id], function (err, result) {
if (err) throw err;
var restaurant = result[0];
req.session.manager = {
id: account.ra_id,
name: account.ra_name,
rest_id: restaurant.rest_id,
rest_name: restaurant.rest_name
};
res.redirect('/');
});
});
});
router.get('/logout', function (req, res) {
req.session.destroy();
res.redirect('/manager/login');
});
module.exports = router;
</code></pre>
<p>When I type localhost:80 on my browser and run the express server it displays the following screen:</p>
<p><a href="https://i.stack.imgur.com/vKrWG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vKrWG.jpg" alt="enter image description here"></a></p>
<p>Now the username and password are supposed to be stored in mysql database created by somebody else and I use phpmyadmin to add database and have full access to it. But ofcourse since the database is not linked, I can't get past this login page and it shows the "<strong>localhost</strong> refused to connect" error!</p>
<p>Following is my console output <strong>before I try to login to the page</strong>:</p>
<pre><code>C:\Mrestro\RESTaurant_backend-master\rest-server>node bin\www
Express server listening on port 80
GET /manager/login 304 23ms
GET /css/bootstrap.css 304 7ms
GET /css/main.css 304 6ms
GET /js/jquery.min.js 304 11ms
GET /images/bg.jpg 304 2ms
</code></pre>
<p>and when I type random username and password following is the output:</p>
<pre><code>C:\Mrestro\RESTaurant_backend-master\rest-server>node bin\www
Express server listening on port 80
GET /manager/login 304 23ms
GET /css/bootstrap.css 304 7ms
GET /css/main.css 304 6ms
GET /js/jquery.min.js 304 11ms
GET /images/bg.jpg 304 2ms
C:\Mrestro\RESTaurant_backend-master\rest-server\web\manager.js:27
if (err) throw err;
^
Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'bjtu'@'localhost' (using password: YES)
at Handshake.Sequence._packetToError (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\sequences\Sequence.js:51:14)
at Handshake.ErrorPacket (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\sequences\Handshake.js:103:18)
at Protocol._parsePacket (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Protocol.js:280:23)
at Parser.write (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Parser.js:74:12)
at Protocol.write (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\Connection.js:109:28)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
--------------------
at Protocol._enqueue (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Protocol.js:141:48)
at Protocol.handshake (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\protocol\Protocol.js:52:41)
at Connection.connect (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\Connection.js:136:18)
at Connection._implyConnect (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\Connection.js:467:10)
at Connection.query (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\mysql\lib\Connection.js:212:8)
at Object.handle (C:\Mrestro\RESTaurant_backend-master\rest-server\web\manager.js:26:14)
at next_layer (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\express\lib\router\route.js:103:13)
at Route.dispatch (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\express\lib\router\route.js:107:5)
at C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\express\lib\router\index.js:195:24
at Function.proto.process_params (C:\Mrestro\RESTaurant_backend-master\rest-server\node_modules\express\lib\router\index.js:251:12)
C:\Mrestro\RESTaurant_backend-master\rest-server>
</code></pre>
<p>So, my question is what username and password should I use? Where can I find the correct one in the database?</p>
<p><strong>EDIT:</strong> database.js</p>
<pre><code>var mysql = require('mysql');
var c = mysql.createConnection({
host : 'localhost',
// port : '3306',
user : 'root',
password : 'root',
database : 'restaurant'
});
// enable error logging for each connection query
c.on('error', function(err) {
console.log(err.code); // example : 'ER_BAD_DB_ERROR'
});
exports.connection = function() {
return c;
};
</code></pre> | 0 |
Spring Boot + Hibernate One To One Mapping | <p>I need an example on CRUD Operations on two tables with one-to-one mapping using</p>
<p>Hibernate.</p>
<p>I want to learn how this is done in Spring Boot.</p>
<p>I already referred [this][1]</p>
<p>link, but it shows only one table.</p>
<p>If anyone has such a link to a website/github, it will be tremendously helpful.</p>
<p>Thanks in advance</p>
<p><strong>My working code</strong></p>
<p>/////////////////////////Main App//////////////////////////////</p>
<pre><code>package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SuppressWarnings("deprecation")
@SpringBootApplication
public class SpringBootWeb1Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(SpringBootWeb1Application.class, args);
}
}
</code></pre>
<p>////////////////////////////////IndexController////////////////////</p>
<pre><code>package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/")
String index(){
return "index";
}
}
</code></pre>
<p>////////////////////////PersonController///////////////////</p>
<pre><code>package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.model.Person;
import com.service.PersonService;
@Controller
public class PersonController {
@Autowired
private PersonService personService;
@Autowired
public void setPersonService(PersonService personService) {
this.personService = personService;
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String list(Model model){
model.addAttribute("persons", personService.listAllPersons());
return "persons";
}
@RequestMapping("person/{id}")
public String showPerson(@PathVariable Integer id, Model model){
model.addAttribute("person", personService.getPersonById(id));
return "personshow";
}
@RequestMapping("person/edit/{id}")
public String edit(@PathVariable Integer id, Model model){
model.addAttribute("person", personService.getPersonById(id));
return "personform";
}
@RequestMapping("person/new")
public String newPerson(Model model){
model.addAttribute("person", new Person());
return "personform";
}
@RequestMapping(value = "person", method = RequestMethod.POST)
public String saveProduct(Person person){
personService.savePerson(person);
return "redirect:/person/" + person.getId();
}
@RequestMapping("person/delete/{id}")
public String delete(@PathVariable Integer id){
personService.deletePerson(id);
/*return "redirect:/products";*/
return "personform";
}
}
</code></pre>
<p>/////////////////////////////////Person//////////////////////////</p>
<pre><code>package com.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</code></pre>
<p>/////////////////////////////PersonDetail/////////////////////////////</p>
<pre><code>package com.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "PersonDetail", catalog = "myschema")
public class PersonDetail {
@Id
@GeneratedValue
private Integer id;
private String address;
private Integer age;
@OneToOne(fetch=FetchType.LAZY)
@PrimaryKeyJoinColumn
private Person person;
public PersonDetail(){}
public PersonDetail(Integer id,String address,Integer age)
{
this.id=id;
this.address=address;
this.age=age;
}
@GenericGenerator(name = "generator", strategy = "foreign")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "address", nullable = false, length = 20)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Column(name = "age", nullable = false)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
</code></pre>
<p>/////////////////////////////PersonRepository//////////////////////////////</p>
<pre><code>package com.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.model.Person;
@Repository
public interface PersonRepository extends CrudRepository<Person, Integer>{
}
</code></pre>
<p>//////////////////////////PersonDetailRepository/////////////////////</p>
<pre><code>package com.repository;
import org.springframework.data.repository.CrudRepository;
import com.model.PersonDetail;
public interface PersonDetailRepository extends CrudRepository<PersonDetail, Integer>{
}
</code></pre>
<p>///////////////////////////////Service///////////////////////</p>
<pre><code>package com.service;
import com.model.Person;
public interface PersonService {
Iterable<Person> listAllPersons();
Person getPersonById(Integer id);
Person savePerson(Person person);
void deletePerson(Integer id);
}
</code></pre>
<p>///////////////////////////////ServiceImpl/////////////////////</p>
<pre><code>package com.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.Person;
import com.repository.PersonRepository;
@Service
public class PersonServiceImpl implements PersonService{
private PersonRepository personRepository;
@Autowired
public void setPersonRepository(PersonRepository personRepository) {
this.personRepository = personRepository;
}
@Override
public Iterable<Person> listAllPersons() {
// TODO Auto-generated method stub
return personRepository.findAll();
}
@Override
public Person getPersonById(Integer id) {
// TODO Auto-generated method stub
return personRepository.findOne(id);
}
@Override
public Person savePerson(Person person) {
// TODO Auto-generated method stub
return personRepository.save(person);
}
@Override
public void deletePerson(Integer id) {
personRepository.delete(id);
}
}
</code></pre>
<p>////////////////////////index.jsp/////////////////////////////</p>
<pre><code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Spring Boot Example</title>
<!-- <th:block th:include="fragments/headerinc :: head"></th:block> -->
</head>
<body>
<div class="container">
<div th:fragment="header">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#" th:href="@{/}">Home</a>
<ul class="nav navbar-nav">
<li><a href="#" th:href="@{/persons}">Persons</a></li>
<li><a href="#" th:href="@{/person/new}">Create Person</a></li>
</ul>
</div>
</div></nav></div>
<!-- <div class="container"> -->
<!-- <th:block th:include="fragments/header :: header"></th:block> -->
</div>
</body>
</html>
</code></pre>
<p>/////////////////////////personform.jsp///////////////////////////</p>
<pre><code> <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Spring Boot Example</title>
<th:block th:include="fragments/headerinc :: head"></th:block>
</head>
<body>
<div class="container">
<th:block th:include="fragments/header :: header"></th:block>
<h2>Person Details</h2>
<div>
<form class="form-horizontal" th:object="${person}" th:action="@{/person}" method="post">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Person Id:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{id}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{name}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{address}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Age:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{age}"/>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
</div>
</body>
</html>
</code></pre>
<p>/////////////////////////persons//////////////////////</p>
<pre><code> <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Spring Boot Example</title>
<th:block th:include="fragments/headerinc :: head"></th:block>
</head>
<body>
<div class="container">
<!--/*/ <th:block th:include="fragments/header :: header"></th:block> /*/-->
<div th:if="${not #lists.isEmpty(persons)}">
<h2>Person List</h2>
<table class="table table-striped">
<tr>
<th>Id</th>
<th>Person Id</th>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>View</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr th:each="person : ${persons}">
<td th:text="${person.id}"><a href="/person/${id}">Id</a></td>
<td th:text="${person.id}">Person Id</td>
<td th:text="${person.name}">description</td>
<td th:text="${person.personDetail.address}">Address</td>
<td th:text="${person.personDetail.age}">Age</td>
<!-- <td th:text="${product.price}">price</td> -->
<td><a th:href="${ '/person/' + person.id}">View</a></td>
<td><a th:href="${'/person/edit/' + person.id}">Edit</a></td>
<td><a th:href="${'/person/delete/' + person.id}">Delete</a></td>
</tr>
</table>
</div>
</div>
</body>
</html>
</code></pre>
<p>//////////////////////////personshow/////////////////////////////</p>
<pre><code> <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Person Details</title>
<th:block th:include="fragments/headerinc :: head"></th:block>
</head>
<body>
<div class="container">
<!--/*/ <th:block th:include="fragments/header :: header"></th:block> /*/-->
<h2>Person Details</h2>
<div>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">Person Id:</label>
<div class="col-sm-10">
<p class="form-control-static" th:text="${person.id}">Person Id</p></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<p class="form-control-static" th:text="${person.name}">name</p>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Address:</label>
<div class="col-sm-10">
<p class="form-control-static" th:text="${person.personDetail.address}">address</p>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<p class="form-control-static" th:text="${person.personDetail.address}">age</p>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
</code></pre> | 0 |
React-native: How to control what keyboard pushes up | <p>The structure of the app is fairly simple: A searchbar, a listview and react-native-tabs at the bottom. The problem: If I click on the searchbar on Android it pushes the whole app up, so I see the tabs directly over the keyboard. But on iOS the keyboard overlays the whole app, without pushing anything up. Is there any way to control that?<br />
I'm happy to share code / screenshots if the question isn't clear.<br />
Thanks</p>
<p>edit:</p>
<pre class="lang-js prettyprint-override"><code><View style={{flex:1, backgroundColor:'#f2f2f2'}}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderSearchResults.bind(this)}
style={styles.listView}/>
<KeyboardAvoidingView
style={styles.addQuestionBar}
behavior={'position'}>
<Text>
Don't see your question?
</Text>
<TouchableOpacity>
<Text>
Add it
</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
</code></pre> | 0 |
Does service worker runs on background even if browser is closed? | <p>I see push notification for Facebook web in chrome only when I open chrome. I know that this notification are sent through <strong>service worker</strong>. I am wondering whether this background sync goes on even though browser is closed or only on opening chrome only these service-worker sync process get started and start sending push notification.</p> | 0 |
Awk replace string in line | <p>NOTE:
This question looks like a <a href="https://stackoverflow.com/questions/39273660/awk-sed-replace-in-each-line-with-previous-string-in-the-line/39273912#39273912">previously posted one</a>, but as mentioned in the comments, it turned out to be a <a href="https://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions">chameleon question.</a>
I accepted the answer, and I'm posting here the same problem but with slightly different "solution conditions".</p>
<hr>
<p>I have a file <code>test.txt</code> like this (but containing many more lines)</p>
<pre><code>/foo/bar/how /SOME_TEXT_HERE/hello
/foo/bar/are hello/SOME_OTHER_TEXT
/foo/bar/you hello
</code></pre>
<p>I want to get this output:</p>
<pre><code>/foo/bar/how /SOME_TEXT_HERE/how
/foo/bar/are are/SOME_OTHER_TEXT
/foo/bar/you you
</code></pre>
<p>I have tried this:</p>
<pre><code>while read line
do
bla=$(echo $line | cut -f4 -d"/" | cut -f1 -d" ")
sed -i "s/hello/$bla/" test.txt
done <test.txt
</code></pre>
<p>But the output is:</p>
<pre><code>/foo/bar/how /SOME_TEXT_HERE/how
/foo/bar/are how/SOME_OTHER_TEXT
/foo/bar/you how
</code></pre>
<p><strong>NOTE</strong>:</p>
<p>I would like the solution to:</p>
<ol>
<li><p>allow me to define a variable (here, <code>bla</code>) that I will define manually and differently from one file to the other (so not using sthg like basic field position), but using <code>cut</code> or other command as in my example)</p></li>
<li><p>replace a specific string somewhere else in the line by this variable (so not a field position like <code>$2</code>, but really something like <code>s/hello/$bla</code>)</p></li>
</ol>
<p>I'm not sure of this is possible though (obviously I don't know how to do this by myself...), but thanks for your time trying! :)</p> | 0 |
Qt installer stuck | <p>I'm running the <em>Qt Open Source</em> installer on Windows 7.</p>
<p>It's at 46% during the "Retrieving meta information from remote repository" step. It quickly got there and got stuck there 55 minutes already.</p>
<p>I tried restarting the installer and this time it got stuck again at the same step, but at 64%.</p>
<p>Any ideas?</p>
<p><em>Notes:</em></p>
<ul>
<li>The installer name is <code>qt-unified-windows-x86-2.0.3-1-online.exe</code></li>
<li>I believe the Qt version it's going to install is <em>Qt 5.7</em>, as that's the latest Qt version as of now</li>
<li>I'm going to try the offline installer now</li>
</ul> | 0 |
How to close DialogBox programmatically | <p>I create a simple form that pops up a dialog box when you run it, but i cannot close it programmatically.
Can anyone help me with that?</p>
<pre><code>Label lb = new Label();
Form frm = new Form();
lb.Left = 100;
lb.Top = 44;
frm.Controls.Add(lb);
frm.ShowDialog();
System.Threading.Thread.Sleep(2000);
</code></pre>
<p>After ..Sleep(2000) i want it to close.
I tried:</p>
<pre><code> frm.close();frm.dispose();frm.visible = false;
</code></pre>
<p>Thanks in advance!</p> | 0 |
User input if statements in Java not working | <p>I am using scanner to take user input.</p>
<pre><code>Scanner scanner = new Scanner(System.in);
Int choice = scanner.nextInt();
if(choice==1) {
System.out.println(" you chosed number 1!")
}
if(choice==2) {
System.out.println(" you chosed number 2!")
}
if(choice==3) {
System.out.println(" you chosed number 3!")
}
if(choice==q) {
System.out.println("the game will end now!");
}
</code></pre>
<p>So when you enter the game you have a menu that pops up. You can chose between 1, 2, 3 or q. If you press any of the numbers the game will take you to those sections.
But if you press q the game will end.</p>
<p>I don't know how to fix so that I can enter q and game ends.</p> | 0 |
Passing Values from one Form to another Form in a Button click | <p>These are my 2 Forms.
<a href="https://i.stack.imgur.com/9h8NB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9h8NB.png" alt="enter image description here"></a></p>
<p>These are the codes for Form 1--></p>
<pre><code>namespace Passing_Values
{
public partial class Form1 : Form
{
string a="preset value";
public Form1()
{
InitializeComponent();
}
private void btnOpenF2_Click(object sender, EventArgs e)
{
new Form2().Show();
}
public void set(string p)
{
MessageBox.Show("This is Entered text in Form 2 " + p);
a = p;
MessageBox.Show("a=p done! and P is: " + p + "---and a is: " + a);
textBox1.Text = "Test 1";
textBox2.Text = a;
textBox3.Text = p;
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(a);
}
}
}
</code></pre>
<p>These are the codes for Form 2--></p>
<pre><code>namespace Passing_Values
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string g;
g = textBox1.Text;
Form1 j = new Form1();
j.set(g);
}
}
}
</code></pre>
<p>See the picture.You can understand the design.</p>
<p>This is what I want to do. 1st I open Form2 using button in Form1. Then I enter a text and click the button("Display in Form1 Textbox"). When it's clicked that value should be seen in the 3 Textboxes in Form1.I used Message Boxes to see if the values are passing or not. Values get passed from Form2 to Form1. But those values are not displays in those 3 Textboxes but the passed values are displayed in Message Boxes. Reason for the 3 Text Boxes can be understood by looking at the code. So what's the error?</p> | 0 |
Access Token missing or malformed when calling Graph API | <p>Following this guide: <a href="https://azure.microsoft.com/en-us/documentation/articles/resource-manager-api-authentication/#_get-objectid-of-application-service-principal-in-user-azure-ad">https://azure.microsoft.com/en-us/documentation/articles/resource-manager-api-authentication/#_get-objectid-of-application-service-principal-in-user-azure-ad</a></p>
<p>I've reached the stage where I call graph.windows.net to Get the ObjectId of the service principal in user Azure AD.</p>
<p>When I do the call, however, I'm getting the following message:</p>
<pre><code>{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"values":null}}
</code></pre>
<p>I've already tried replacing the clientId with the 'onmicrosoft.com' address too (so <em>graph.windows.net/appname.onmicrosoft.com/...</em>), still got the same message.</p> | 0 |
Add one section separator for Navigation Drawer in Android | <p>I have a navigation drawer like this image. I want to add a section separator . It seems simple but I can't find anything on the web that was useful for my case.</p>
<h1>- <strong>Add a line separator below Express</strong></h1>
<h2><strong>Add a line separator below My Information</strong></h2>
<p><a href="https://i.stack.imgur.com/7I5PQ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/7I5PQ.jpg" alt="enter image description here"></a></p>
<pre><code> <menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Express">
<menu>
<group
android:id="@+id/me"
android:checkableBehavior="single">
<item
android:id="@+id/nav_balance_transfer"
android:icon="@mipmap/icon_wallet_transfer"
android:title="Balance Transfer" />
<item
android:id="@+id/nav_load_money"
android:icon="@mipmap/icon_load_money"
android:title="Load Money" />
<item
android:id="@+id/nav_report"
android:icon="@mipmap/icon_history"
android:title="Report" />
</group>
</menu>
</item>
<item android:title="My Information">
<menu>
<group
android:id="@+id/menu_nav_temp_gid"
android:checkableBehavior="none">
<item
android:id="@+id/nav_profile"
android:icon="@mipmap/icon_profile"
android:title="My Account" />
<item
android:id="@+id/nav_changePassword"
android:icon="@mipmap/icon_change"
android:title="Change Password" />
<item
android:id="@+id/nav_ViewUser"
android:icon="@mipmap/ic_view_user"
android:title="View User" />
<item
android:id="@+id/nav_addUser"
android:icon="@mipmap/icon_adduser"
android:title="Add User" />
<item
android:id="@+id/nav_addScheme"
android:icon="@mipmap/icon_add_scheme"
android:title="Add Scheme" />
<item
android:id="@+id/nav_logout"
android:icon="@mipmap/icon_logout"
android:title="Log Out" />
</group>
</menu>
</item>
</code></pre>
<p></p>
<p>i had done this code
if i takes express and my info in a separate group than it takes padding </p>
<p>suggest me how to achive this ..</p> | 0 |
How to call super of enclosing class in a mixin in Python? | <p>I have the following code, in Django:</p>
<pre><code>class Parent(models.Model):
def save(self):
# Do Stuff A
class Mixin(object):
def save(self):
# Do Stuff B
class A(Parent, Mixin):
def save(self):
super(A, self).save()
# Do stuff C
</code></pre>
<p>Now, I want to use the mixin without blatting the behaviour of the save in Parent. So I when I save, I want to do stuff C, B, and A. I've read <a href="https://stackoverflow.com/questions/27664632/calling-the-setter-of-a-super-class-in-a-mixin">Calling the setter of a super class in a mixin</a> however I don't get it and having read the super docs it doesn't seem to answer my question.</p>
<p>THe question is, what do I put in the mixin to make sure it does stuff B and doesn't stop Stuff A from happening?</p> | 0 |
Unable to use an existing Hive permanent UDF from Spark SQL | <p>I have previously registered a UDF with hive. It is permanent not <code>TEMPORARY</code>. It works in beeline.</p>
<pre><code>CREATE FUNCTION normaliseURL AS 'com.example.hive.udfs.NormaliseURL' USING JAR 'hdfs://udfs/hive-udfs.jar';
</code></pre>
<p>I have spark configured to use the hive metastore. The config is working as I can query hive tables. I can see the UDF;</p>
<pre><code>In [9]: spark.sql('describe function normaliseURL').show(truncate=False)
+-------------------------------------------+
|function_desc |
+-------------------------------------------+
|Function: default.normaliseURL |
|Class: com.example.hive.udfs.NormaliseURL |
|Usage: N/A. |
+-------------------------------------------+
</code></pre>
<p>However I cannot use the UDF in a sql statement;</p>
<pre><code>spark.sql('SELECT normaliseURL("value")')
AnalysisException: "Undefined function: 'default.normaliseURL'. This function is neither a registered temporary function nor a permanent function registered in the database 'default'.; line 1 pos 7"
</code></pre>
<p>If I attempt to register the UDF with spark (bypassing the metastore) it fails to register it, suggesting that it does already exist.</p>
<pre><code>In [12]: spark.sql("create function normaliseURL as 'com.example.hive.udfs.NormaliseURL'")
AnalysisException: "Function 'default.normaliseURL' already exists in database 'default';"
</code></pre>
<p>I'm using Spark 2.0, hive metastore 1.1.0. The UDF is scala, my spark driver code is python.</p>
<p>I'm stumped.</p>
<ul>
<li>Am I correct in my assumption that Spark can utilise metastore-defined permanent UDFs?</li>
<li>Am I creating the function correctly in hive?</li>
</ul> | 0 |
What is the time complexity of dict.keys() in Python? | <p>I came across a question when I solved <a href="https://leetcode.com/problems/insert-delete-getrandom-o1/" rel="noreferrer">this LeetCode problem</a>. Although my solution got accepted by the system, I still do not have any idea after searching online for the following question:</p>
<p><code>What is the time complexity of dict.keys() operation?</code></p>
<p>Does it return a view of the keys or a real list (stores in memory) of the keys?</p> | 0 |
Min positive value for float? | <p>I'm new to C++!</p>
<p><a href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format" rel="noreferrer">Wiki says</a> this about <code>float</code>: The minimum positive normal value is 2^−126 ≈ 1.18 × 10^−38 and the minimum positive (denormal) value is 2^−149 ≈ 1.4 × 10^−45.</p>
<p>But if a float can have max 7 digit (<code>≈ 7.225</code>), the min is it not just <code>0,0000001</code>? I'm confused :)</p> | 0 |
What does the regex [^\s]*? mean? | <p>I am starting to learn python spider to download some pictures on the web and I found the code as follows. I know some basic regex.
I knew <code>\.jpg</code> means <code>.jpg</code> and <code>|</code> means <code>or</code>. what's the meaning of <code>[^\s]*?</code> of the first line? I am wondering why using <code>\s</code>?
And what's the difference between the two regexes?</p>
<pre><code>http:[^\s]*?(\.jpg|\.png|\.gif)
http://.*?(\.jpg|\.png|\.gif)
</code></pre> | 0 |
How to force application version on AWS Elastic Beanstalk | <p>I'm trying to deploy a new version of my Python/Django application using <code>eb deploy</code>.</p>
<p>It unfortunately fails due to unexpected version of the application. The problem is that somehow <code>eb deploy</code> screwed up the version and I don't know how to override it. The application I upload is working fine, only the version number is not correct, hence, Elastic Beanstalk marks it as <em>Degraded</em>. </p>
<p>When executing eb deploy, I get this error:</p>
<blockquote>
<p>"Incorrect application version "app-cca6-160820_155843" (deployment
161). Expected version "app-598b-160820_152351" (deployment 159). "</p>
</blockquote>
<p>The same says in the health status at AWS Console.</p>
<p>So, my question is the following: How can I force Elastic Beanstalk to make the uploaded application version the current one so it doesn't complain?</p> | 0 |
Laravel issue with loginUsingId (Manual Authentication) | <p>I am trying to implement a <strong>single signon on multiple domains</strong>. The concept is pretty simple i.e to send unique user tokens and then verify these tokens to find the user and then log him in.</p>
<p>Now after verifying the token and then grabbing the user, i do something like this</p>
<pre><code>$loggedInUser = Auth::loginUsingId($user->id, true);
</code></pre>
<p>Now i have a custom middleware where it first checks for a logged in user, i.e</p>
<pre><code>Auth::Check()
</code></pre>
<p>The above works fine for the first time. But on refresh Auth::check() is not validated. I have also tried using all different session drivers but still doesn't work.</p>
<p>I used a similar code on laravel 5.2, and it did work. But on laravel 5.3 its not validating on persistent requests. </p>
<p><strong>Edit: Let me show you my Code</strong>
I have not modified AuthServiceProvider or any other guard. I do have the user model inside a directory but i have modified the path in auth.php.</p>
<p>Here is the route that domain1 points to:</p>
<p><a href="http://domain2.com/">http://domain2.com/</a>{{$role}}/{{$route}}/singlesignon/{{$token}}</p>
<p>This is then picked up by verifySingleSignOn method inside the loginController which takes in the role, route that the user came in from other domain and the token. The user is then redirected to the same routes, but on domain2. Here i can successfully recieve the user id before manually logging in.</p>
<pre><code>public function verifySingleSignOn($role, $route, $token)
{
// Fetch Single Signon
$userRepository = new UserRepository();
$user = $userRepository->checkForSingleSignOnToken($token, ['id']);
// Check if Token Exists
if (isset($user->id) && is_int($user->id) && $user->id != 0) {
// Manually Logging a user (Here is successfully recieve the user id)
$loggedInUser = Auth::loginUsingId($user->id);
if (!$loggedInUser) {
// If User not logged in, then Throw exception
throw new Exception('Single SignOn: User Cannot be Signed In');
}
$redirectTo = $role . '/' . $route;
return redirect($redirectTo);
} else {
return Auth::logout();
}
}
</code></pre>
<p>Then i have this GlobalAdminAuth middleware</p>
<pre><code> // Check if logged in
if( Auth::Check() ){
$user = Auth::User();
// Check if user is active and is a globaladmin
if( !$user->isGlobalAdmin() || !$user->isActive() ){
return redirect()->guest('login');
}
}else{
return redirect()->guest('login');
}
return $next($request);
</code></pre>
<p>Now the first time everything works fine and the user moves through the middleware successfully . but the second time the else statement is triggered.</p>
<p><strong>Edit: Code for checkForSingleSignOnToken</strong></p>
<pre><code>public function checkForSingleSignOnToken($token, $columns = array('*'))
{
return User::where('single_signon', $token)->first($columns);
}
</code></pre> | 0 |
Testing that custom Spring Boot AutoConfiguration is valid | <p>I've decided to write quite a trivial test to check that my Spring Boot auto-configuration works - all the needed beans are created along with their dependencies.</p>
<p>AutoConfiguration is:</p>
<pre><code>package org.project.module.autoconfigure;
import org.project.module.SomeFactory;
import org.project.module.SomeProducer;
import org.project.module.SomeServiceClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Spring Boot simple auto-configuration.
*
* @author istepanov
*/
@Configuration
@ComponentScan("org.project.module.support")
public class SomeAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SomeFactory someFactory() {
return new SomeFactory();
}
@Bean
@ConditionalOnMissingBean
public SomeServiceClient someServiceClient() {
return new SomeServiceClient();
}
@Bean
@ConditionalOnMissingBean
public SomeProducer someProducer() {
return new SomeProducer();
}
}
</code></pre>
<p>And test is:</p>
<pre><code>package org.project.module.autoconfigure;
import org.project.module.SomeFactory;
import org.project.module.SomeProducer;
import org.project.module.SomeServiceClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@code SomeAutoConfiguration}.
*
* @author istepanov
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {SomeAutoConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class SomeAutoConfigurationTest {
@Autowired
private SomeFactory someFactory;
@Autowired
private SomeServiceClient someServiceClient;
@Autowired
private SomeProducer someProducer;
@Test
public void someFactory_isNotNull() {
assertThat(someFactory).isNotNull();
}
@Test
public void someServiceClient_isNotNull() {
assertThat(someServiceClient).isNotNull();
}
@Test
public void someProducer_isNotNull() {
assertThat(someProducer).isNotNull();
}
}
</code></pre>
<p>But actually test fails with exception - dependent beans, which are expected to be loaded with <code>@ComponentScan</code>, are actually missing:</p>
<pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener.prepareTestInstance(AutoConfigureReportTestExecutionListener.java:49)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someFacade': Unsatisfied dependency expressed through method 'setSomeMetrics' parameter 0: Error creating bean with name 'someMetrics': Unsatisfied dependency expressed through method 'setCounterService' parameter 0: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someMetrics': Unsatisfied dependency expressed through method 'setCounterService' parameter 0: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:648)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 22 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someMetrics': Unsatisfied dependency expressed through method 'setCounterService' parameter 0: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:648)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1214)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 40 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.metrics.CounterService] found for dependency [org.springframework.boot.actuate.metrics.CounterService]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1406)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1057)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1019)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 54 more
</code></pre>
<p>Any ideas what have I missed?</p>
<p>P.S.: Also adding the missing SomeMetrics:</p>
<pre><code>package org.project.module.support.metrics;
import org.project.module.support.SomeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import static org.mockito.Mockito.mock;
/**
* Customization for Spring Actuator, defines application-specific counters and metrics.
*
* @author istepanov
*/
@Component
public class SomeMetrics {
@Value("${const.metrics.some.connections.current:some.connections.created}")
private String connectorsCurrent;
@Value("${const.metrics.some.connections.idle:some.connections.idle}")
private String connectorsIdle;
@Value("${const.metrics.some.connections.max:some.connections.max}")
private String connectorsMax;
private CounterService counterService;
private GaugeService gaugeService;
private SomeProperties someProperties;
@Autowired
public void setSomeProperties(SomeProperties someProperties) {
this.someProperties = someProperties;
}
@Autowired
public void setCounterService(CounterService counterService) {
this.counterService = counterService;
}
@Autowired
public void setGaugeService(GaugeService gaugeService) {
this.gaugeService = gaugeService;
}
/**
* Use mocks for {@link CounterService} and {@link GaugeService} if CRMBO is not configured properly.
*/
@PostConstruct
public void init() {
if (someProperties.isMock()) {
counterService = mock(CounterService.class);
gaugeService = mock(GaugeService.class);
}
}
public void decrementConnectorsCurrent() {
this.counterService.decrement(connectorsCurrent);
}
public void incrementConnectorsCurrent() {
this.counterService.increment(connectorsCurrent);
}
public void decrementConnectorsIdle() {
this.counterService.decrement(connectorsIdle);
}
public void incrementConnectorsIdle() {
this.counterService.increment(connectorsIdle);
}
public void decrementConnectorsMax() {
this.counterService.decrement(connectorsMax);
}
public void incrementConnectorsMax() {
this.counterService.increment(connectorsMax);
}
}
</code></pre> | 0 |
node-sass command not found when compiling | <p>I have a problem with SASS for node.js on Mac (OS X El Capitan)</p>
<p>When i trying compile a scss file to css using command 'node-sass -o css sass/style.scss' I get the following error:</p>
<blockquote>
<p>node-sass: command not found</p>
</blockquote>
<p>What's the problem and how i can solve it?</p> | 0 |
Caused by: java.lang.LinkageError: Failed to link com/--- | <p>Below is my maven configuration </p>
<pre><code><modelVersion>4.0.0</modelVersion>
<groupId>com.trbrew.commerce.brewtique</groupId>
<artifactId>BrewtiqueProject</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<modules>
<module>ejb</module>
<module>ear</module>
<module>web</module>
</modules>
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
</dependencies>
</code></pre>
<p>And children pom</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.trbrew.commerce</groupId>
<artifactId>TrBrewCommerce</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>TrBrewCommerce</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>com.koinplus</groupId>
<artifactId>KoinPlusCommons</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>C://Users/trbrewjars/KoinPlusCommons-1.0.jar</systemPath>
</dependency>
<dependency>
<groupId>com.trbrew.common</groupId>
<artifactId>TrBrewCommons</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>C://Users/trbrewjars/TrendBrewCommons-1.0.jar</systemPath>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>Pom of ear module </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>BrewtiqueProject</artifactId>
<groupId>com.tbrew.commerce.brewtique</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Brewtique</artifactId>
<packaging>ear</packaging>
<dependencies>
<dependency>
<groupId>com.trbrew.commerce.brewtique</groupId>
<artifactId>ejb</artifactId>
<version>1.0</version>
<type>ejb</type>
</dependency>
<dependency>
<groupId>com.trbrew.commerce.brewtique</groupId>
<artifactId>web</artifactId>
<version>1.0</version>
<type>war</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-ear-plugin</artifactId>
<version>2.10.1</version>
<configuration>
<!--<defaultLibBundleDir>lib</defaultLibBundleDir>-->
<modules>
<webModule>
<groupId>com.trbrew.commerce.brewtique</groupId>
<artifactId>web</artifactId>
</webModule>
<ejbModule>
<groupId>com.trbrew.commerce.brewtique</groupId>
<artifactId>ejb</artifactId>
</ejbModule>
</modules>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>Pom of ejb module</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>BrewtiqueProject</artifactId>
<groupId>com.trbrew.commerce.brewtique</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ejb</artifactId>
<packaging>ejb</packaging>
<dependencies>
<dependency>
<groupId>com.trbrew.commerce</groupId>
<artifactId>TrBrewCommerce</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<ejbVersion>3.0</ejbVersion>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>and the error I ran into while running the ear file generated is </p>
<pre><code>17:31:09,694 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC000001: Failed to start service jboss.deployment.subunit."Brewtique-1.0.ear"."ejb-1.0.jar".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.subunit."Brewtique-1.0.ear"."ejb-1.0.jar".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of subdeployment "ejb-1.0.jar" of deployment "Brewtique-1.0.ear"
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:163)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.LinkageError: Failed to link com/trendbrew/commerce/brewtique/catalog/CatalogManagementService (Module "deployment.Brewtique-1.0.ear.ejb-1.0.jar:main" from Service Module Loader)
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:437)
at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:269)
at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:77)
at org.jboss.modules.Module.loadModuleClass(Module.java:560)
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:197)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.jboss.as.server.deployment.reflect.DeploymentClassIndex.classIndex(DeploymentClassIndex.java:54)
at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.processComponentConfig(InterceptorAnnotationProcessor.java:85)
at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.deploy(InterceptorAnnotationProcessor.java:77)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:156)
... 5 more
Caused by: java.lang.NoClassDefFoundError: com/koinplus/common/GenericKoinPlusService
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:353)
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:432)
... 19 more
Caused by: java.lang.ClassNotFoundException: com.koinplus.common.GenericKoinPlusService from [Module "deployment.Brewtique-1.0.ear.ejb-1.0.jar:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
... 23 more
17:31:09,725 INFO [org.jboss.weld.deployer] (MSC service thread 1-2) WFLYWELD0003: Processing weld deployment web-1.0.war
17:31:09,804 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "Brewtique-1.0.ear")]) - failure description: {
"WFLYCTL0080: Failed services" => {"jboss.deployment.subunit.\"Brewtique-1.0.ear\".\"ejb-1.0.jar\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.subunit.\"Brewtique-1.0.ear\".\"ejb-1.0.jar\".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of subdeployment \"ejb-1.0.jar\" of deployment \"Brewtique-1.0.ear\"
Caused by: java.lang.LinkageError: Failed to link com/trendbrew/commerce/brewtique/catalog/CatalogManagementService (Module \"deployment.Brewtique-1.0.ear.ejb-1.0.jar:main\" from Service Module Loader)
Caused by: java.lang.NoClassDefFoundError: com/koinplus/common/GenericKoinPlusService
Caused by: java.lang.ClassNotFoundException: com.koinplus.common.GenericKoinPlusService from [Module \"deployment.Brewtique-1.0.ear.ejb-1.0.jar:main\" from Service Module Loader]"},
"WFLYCTL0180: Services with missing/unavailable dependencies" => [
"jboss.deployment.unit.\"Brewtique-1.0.ear\".batch.environment is missing [jboss.deployment.unit.\"Brewtique-1.0.ear\".beanmanager]",
"jboss.deployment.unit.\"Brewtique-1.0.ear\".weld.weldClassIntrospector is missing [jboss.deployment.unit.\"Brewtique-1.0.ear\".beanmanager]",
"jboss.deployment.subunit.\"Brewtique-1.0.ear\".\"web-1.0.war\".batch.environment is missing [jboss.deployment.subunit.\"Brewtique-1.0.ear\".\"web-1.0.war\".beanmanager]",
"jboss.persistenceunit.\"Brewtique-1.0.ear/ejb-1.0.jar#tbCommPersistence\".__FIRST_PHASE__ is missing [jboss.naming.context.java.jboss.datasource.wishinity]",
</code></pre>
<p>The ear file deployed on Wildfly and not able to crack the reason. Any clues ?</p>
<p>Tried reinstall ... repackage, maven update/refresh with no luck.</p> | 0 |
Laravel dd function limitations | <p>I have an array of 320 arrays, while regular <code>var_dump</code> shows me exactly 320 elements with all nested elements, Laravel's <code>dd</code> helper truncates the nested element at index <strong>147</strong> and all the further elements are truncated with no option to expand them, see the example below</p>
<pre><code> 146 => array:17 [▼
"total_unconfirmed_subscribers" => 0
"total_subscribers_subscribed_yesterday" => 0
"unique_list_id" => "24324"
"http_etag" => ""fbb6febfca8af5541541ea960aaedb""
"web_form_split_tests_collection_link" => "https://api.com/1.0/"
"subscribers_collection_link" => "https://api.com/1.0/"
"total_subscribers_subscribed_today" => 0
"id" => 23432
"total_subscribed_subscribers" => 0
"total_unsubscribed_subscribers" => 0
"campaigns_collection_link" => "https://api.com/1.0/"
"custom_fields_collection_link" => "https://api.com/1.0/accounts"
"self_link" => "https://api.com/1.0/accounts"
"total_subscribers" => 0
"resource_type_link" => "https://api.com/1.0/#list"
"web_forms_collection_link" => "https://api.com/"
"name" => "dccode"
]
147 => array:17 [▼
"total_unconfirmed_subscribers" => 0
…16
]
148 => array:17 [ …17]
149 => array:17 [ …17]
</code></pre>
<p>Why is it limited to 147 full records and how to increase the limit?
The related topic <a href="https://stackoverflow.com/questions/34400997/is-laravels-dd-helper-function-working-properly">Is Laravels' DD helper function working properly?</a> doesn't actually explain the limits.</p>
<p>This is pretty consistent behavior, I've tested with Laravel 5.2 and php7 on</p>
<ul>
<li>Linux (Laravel Forge, DO droplet, Ubuntu)</li>
<li>Mac (Laravel Valet)</li>
<li>Windows (valet4windows)</li>
</ul>
<p>Everywhere got exactly the same cut on element #147. Using CLI <code>php artisan tinker</code> outputs the same cut</p>
<pre><code>...
"name" => "dccode" ] 147 => array:17 [
"total_unconfirmed_subscribers" => 0
16 ] 148 => array:17 [ 17]
...
</code></pre> | 0 |
Inserting an Image into a sheet using Base64 in VBA? | <p>I'm trying to insert an image into a sheet with VBA using Base64 but I can't find any examples of how to do it correctly anywhere.</p>
<p>I have a string setup for the image, something like:</p>
<p><code>vLogo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZoAAABfCAY"</code></p>
<p>I just want to do the following, but instead of looking for an image file store the image in the VBA.</p>
<p><code>Sheets("Sheet1").Pictures.Insert (Application.ActiveWorkbook.Path & "\vLogo.png")</code></p>
<p>I've even looked at doing something like:</p>
<pre><code>' Write the image to file
Dim myFile As String
myFile = Application.ActiveWorkbook.Path & "\temp.png"
Open myFile For Output As #1
Write #1, vLogo
Close #1
' Insert the image
Sheets("Sheet1").Pictures.Insert (Application.ActiveWorkbook.Path & "\temp.png")
' Delete the temp file
Kill Application.ActiveWorkbook.Path & "\temp.png"
</code></pre>
<p>But I can't figure out how to write the base64 encoded image to file.</p> | 0 |
C# async within an action | <p>I would like to write a method which accept several parameters, including an action and a retry amount and invoke it.</p>
<p>So I have this code:</p>
<pre><code>public static IEnumerable<Task> RunWithRetries<T>(List<T> source, int threads, Func<T, Task<bool>> action, int retries, string method)
{
object lockObj = new object();
int index = 0;
return new Action(async () =>
{
while (true)
{
T item;
lock (lockObj)
{
if (index < source.Count)
{
item = source[index];
index++;
}
else
break;
}
int retry = retries;
while (retry > 0)
{
try
{
bool res = await action(item);
if (res)
retry = -1;
else
//sleep if not success..
Thread.Sleep(200);
}
catch (Exception e)
{
LoggerAgent.LogException(e, method);
}
finally
{
retry--;
}
}
}
}).RunParallel(threads);
}
</code></pre>
<p>RunParallel is an extention method for Action, its look like this:</p>
<pre><code>public static IEnumerable<Task> RunParallel(this Action action, int amount)
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < amount; i++)
{
Task task = Task.Factory.StartNew(action);
tasks.Add(task);
}
return tasks;
}
</code></pre>
<p>Now, the issue: The thread is just disappearing or collapsing without waiting for the action to finish.</p>
<p>I wrote this example code:</p>
<pre><code>private static async Task ex()
{
List<int> ints = new List<int>();
for (int i = 0; i < 1000; i++)
{
ints.Add(i);
}
var tasks = RetryComponent.RunWithRetries(ints, 100, async (num) =>
{
try
{
List<string> test = await fetchSmthFromDb();
Console.WriteLine("#" + num + " " + test[0]);
return test[0] == "test";
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
return false;
}
}, 5, "test");
await Task.WhenAll(tasks);
}
</code></pre>
<p>The <code>fetchSmthFromDb</code> is a simple Task> which fetches something from the db and works perfectly fine when invoked outside of this example.</p>
<p>Whenever the <code>List<string> test = await fetchSmthFromDb();</code> row is invoked, the thread seems to be closing and the <code>Console.WriteLine("#" + num + " " + test[0]);</code> not even being triggered, also when debugging the breakpoint never hit.</p>
<p><strong>The Final Working Code</strong></p>
<pre><code>private static async Task DoWithRetries(Func<Task> action, int retryCount, string method)
{
while (true)
{
try
{
await action();
break;
}
catch (Exception e)
{
LoggerAgent.LogException(e, method);
}
if (retryCount <= 0)
break;
retryCount--;
await Task.Delay(200);
};
}
public static async Task RunWithRetries<T>(List<T> source, int threads, Func<T, Task<bool>> action, int retries, string method)
{
Func<T, Task> newAction = async (item) =>
{
await DoWithRetries(async ()=>
{
await action(item);
}, retries, method);
};
await source.ParallelForEachAsync(newAction, threads);
}
</code></pre> | 0 |
Can't install SSH.NET on Visual Studio 2012 Ultimate | <p>No matter which framework version I use (tried with 3.5, 4 and 4.5).</p>
<p>I always get a message which says 'SSH.NET' already has a defined dependency on 'SshNet.Security.Cryptography'. But if I try to install 'SshNet.Security.Cryptography', I get another message which says it already has a defined dependency for 'System.IO', and so on...</p>
<p>I've tried through the nuget packet manager and the nuget command line as well.</p>
<p>Any clue on what's happening?
Regards</p> | 0 |
How to set ANDROID_NDK_HOME so that Android Studio does not ask for ndk location? | <p>My ndk is located at <code>C:\Users\X\AppData\Local\Android\ndk</code>. Now each time I create a new native android project and try to import into Android Studio, it asks me for the location of ndk. I can manually set the ndk in <code>local.properties</code> also.</p>
<p>But I am looking for a way to set this ndk path, so that Android Studio does not ask me to set this path each time.</p>
<p>I have already set <strong>ANDROID_NDK_HOME</strong>, as well as <strong>NDK_HOME</strong> in system environment variable on Windows 10 machine, but Android Studio is still not able to find it. I have restarted my machine as well, still no luck.</p>
<p>I have not tried it on mac, but your answers for both windows and mac are welcome.</p> | 0 |
"Microsoft.ACE.OLEDB.12.0” not recognized in Windows 10 | <p><strong>Background</strong></p>
<p>I'm developing a Windows Form application which connects to a Microsoft Access database.</p>
<p>This is a sample code that I use in the development:</p>
<pre><code>try
{
string AccessFilePath = @"\.myDataBase.mdb"; // Path of the Access database.
string sqlStatement = "SELECT * FROM myTable WHERE IdTable = 5;";
string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AccessFilePath;
OleDbConnection conn = new OleDbConnection(connstr);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStatement;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox("Error: " + ex.Message);
}
</code></pre>
<p>The following list describes the environment of my development:</p>
<ul>
<li>Visual Studio 2015 Community</li>
<li>Solution created in Framework .NET 4.0</li>
<li>Operating system: Windows 10 Pro - 64 bits.</li>
<li>This development must work on Windows XP, Windows 7 and upper versions.</li>
</ul>
<p>I had already installed:</p>
<ul>
<li><a href="https://www.microsoft.com/en-us/download/details.aspx?id=23734" rel="nofollow noreferrer">2007 Office System Driver: Data Connectivity Components</a></li>
<li><a href="https://www.microsoft.com/en-US/download/details.aspx?id=17851" rel="nofollow noreferrer">Microsoft .NET 4.0</a> <em>(in Windows XP and other computers who needs it)</em></li>
</ul>
<p><strong>Issues</strong></p>
<p>In my PC <em>which has Windows 10 Pro OS</em>, I search in the <em>C:/</em> Hard Disk and I found that <strong>ACEOLEDB.DLL</strong> is already installed in the following locations:</p>
<p><em>This is <strong>before</strong> install the Data Connectivity Components:</em></p>
<pre><code>- C:\Program Files (x86)\Microsoft Office\root\VFS\ProgramFilesCommonX86\Microsoft Shared\OFFICE16
- C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE15
- C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE14
</code></pre>
<p><em>Click to enlarge the image:</em></p>
<p><a href="https://i.stack.imgur.com/pUuXo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pUuXo.png" alt="Previous to install Data Connectivity Components"></a></p>
<p>When I installed the Data Connectivity Components in my PC, the <strong>ACEOLEDB.DLL</strong> is located at:</p>
<pre><code>- C:\Program Files (x86)\Microsoft Office\root\VFS\ProgramFilesCommonX86\Microsoft Shared
</code></pre>
<p>I really don't know why <em>even after install Data Connectivity Components</em> I'm still getting this error:</p>
<blockquote>
<p>"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine"</p>
</blockquote>
<hr>
<p><strong>Questions</strong></p>
<ul>
<li>How Data Connectivity Components are handled by the OS?</li>
<li>How can validate correctly if OS has the Data Connectivity Components installed?</li>
</ul> | 0 |
Function chaining in Python | <p>On <a href="https://www.codewars.com/" rel="noreferrer">Codewars.com</a> I encountered the following task:</p>
<blockquote>
<p>Create a function <code>add</code> that adds numbers together when called in succession. So <code>add(1)</code> should return <code>1</code>, <code>add(1)(2)</code> should return <code>1+2</code>, ...</p>
</blockquote>
<p>While I'm familiar with the basics of Python, I've never encountered a function that is able to be called in such succession, i.e. a function <code>f(x)</code> that can be called as <code>f(x)(y)(z)...</code>. Thus far, I'm not even sure how to interpret this notation.</p>
<p>As a mathematician, I'd suspect that <code>f(x)(y)</code> is a function that assigns to every <code>x</code> a function <code>g_{x}</code> and then returns <code>g_{x}(y)</code> and likewise for <code>f(x)(y)(z)</code>.</p>
<p>Should this interpretation be correct, Python would allow me to dynamically create functions which seems very interesting to me. I've searched the web for the past hour, but wasn't able to find a lead in the right direction. Since I don't know how this programming concept is called, however, this may not be too surprising.</p>
<p>How do you call this concept and where can I read more about it?</p> | 0 |
How do I put my image inside my footer tag? | <p>I have a pretty basic problem with html & css. I've created a footer with a <code><p></code> tag and an <code><li></code> tag. Inside the <code><li></code> tag I have an image, this image however goes outside of the footer. <strong>How can I make the image go inside the footer tag?</strong></p>
<p><strong>HTML</strong></p>
<pre><code><footer class="footer">
<p class="footerP">© Axel Halldin 2016 ©</p>
<li class="socialMedias"> <img class="facebook" src="facebook.jpg" href="https://www.facebook.com/axel.halldin1?fref=ts"/>
</li>
</footer>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.footer{
background-color:#003366;
margin:0;
padding:0;
width:90vw;
height:22.5vh;
float:right;
}
.footerP{
color:white;
font-family:FiraSans-Regular, sans-serif;
font-size:16px;
margin:0;
line-height:22.5vh;
}
.socialMedias{
float:right;
}
.facebook{
width:5vw;
height:10vh;
}
</code></pre> | 0 |
Javascript function document.createElement(tagName[, options]) doesn't work as intended | <p>I need to create <code><a href="http://someurl.com"></a></code> element <strong>in one js code line</strong></p>
<p>this doesn't work:</p>
<p><code>var gg = document.createElement("a", {href : "http://someurl.com"})</code></p>
<p>this result in: <code><a is="[object Object]"></a></code></p>
<p>Thought MDN says:
<code>var element = document.createElement(tagName[, options]);</code></p>
<p>options is an optional ElementCreationOptions object. If this object is defined and has an <code>is</code> property, the <code>is</code> attribute of the created element is initalized with the value of this property. If the object has no <code>is</code> property, the value is null.
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement</a></p>
<p>is this ElementCreationOptions object some sort of exotic object? I tried many various combinations around this object but nothing works and always in results i see that strange <code>is</code> property! I also found it in specification: <a href="https://www.w3.org/TR/custom-elements/#attr-is" rel="noreferrer">https://www.w3.org/TR/custom-elements/#attr-is</a> but no idea how it actually works.</p>
<p>ps:
this doesn't work either:</p>
<p><code>var gg = document.createElement("a").setAttribute("href" , "someurl.com")</code></p>
<p>result in undefined.</p> | 0 |
Is it still relevant to specify width and heigth attribute on images in HTML? | <p>I found <a href="https://stackoverflow.com/questions/1247685/should-i-specify-height-and-width-attributes-for-my-imgs-in-html">a similar question here</a>, with the answer: "<em>you should always define the width and height in the image tag</em>." But it is from 2009.</p>
<p>In the meantime, many things has changed on frontend. We are all doing responsive page design now, for many devices and sizes simultaneously (mobile, tablet, desktop...).</p>
<p>So, I wonder is it still necessary to specify the width and height attributes, and for what reason (for responsive, page speed, SEO...)?</p> | 0 |
Why does pip freeze list "pkg-resources==0.0.0"? | <p>On Ubuntu 16.04 with virtualenv 15.0.1 and Python 3.5.2 (both installed with <code>apt</code>) when I create and activate new Python virtual environment with</p>
<pre class="lang-sh prettyprint-override"><code>virtualenv .virtualenvs/wtf -p $(which python3) --no-site-packages
source .virtualenvs/wtf/bin/activate
</code></pre>
<p>I get the following output:</p>
<pre class="lang-none prettyprint-override"><code>Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /home/das-g/.virtualenvs/wtf/bin/python3
Also creating executable in /home/das-g/.virtualenvs/wtf/bin/python
Installing setuptools, pkg_resources, pip, wheel...done.
</code></pre>
<p>Indeed <code>pip freeze --all</code> lists these 4 packages:</p>
<pre><code>pip==8.1.2
pkg-resources==0.0.0
setuptools==25.2.0
wheel==0.29.0
</code></pre>
<p>Though, I'd expect <code>pip freeze</code> (without <code>--all</code>) to omit these implicitly installed packages. It does omit some of them, but not <code>pkg-resources</code>:</p>
<pre><code>pkg-resources==0.0.0
</code></pre>
<p>(Same btw. for <code>pip freeze --local</code>)</p>
<p>While this is consistent with the help text</p>
<pre class="lang-sh prettyprint-override"><code>$> pip freeze --help | grep '\--all'
--all Do not skip these packages in the output: pip, setuptools, distribute, wheel
</code></pre>
<p>having <code>pkg-resources</code> in the <code>pip freeze</code> output doesn't seem very useful and might even be harmful. (I suspect it's why running <code>pip-sync</code> from <a href="https://github.com/nvie/pip-tools">pip-tools</a> uninstalls pkg-resources from the virtual environment, subtly breaking the environment thereby.) <strong>Is there any good reason why <code>pip freeze</code> lists <code>pkg-resources</code> instead of omitting it, too?</strong> As far as I remember, it didn't list it on Ubuntu 14.04 (with Python 3.4).</p> | 0 |
Python: Append a list with a newline | <p>In the following code I am updating a list with two items by appending to it from within a for loop. I need a newline to be added after appending each string but I can't seem to be able to do it.</p>
<p>I thought it would have been:</p>
<pre><code>lines = []
for i in range(10):
line = ser.readline()
if line:
lines.append(line + '\n') #'\n' newline
lines.append(datetime.now())
</code></pre>
<p>But this only adds the '\n' as a string. I have also tried the same without without the quotes, but no luck.</p>
<p>I am getting this:</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 517000), '\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 519000), '\r\x00leftRaw; 928091; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00)]
</code></pre>
<p>But I want this:</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 517000),
'\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 519000)]
</code></pre>
<p>Any ideas?</p> | 0 |
In Git, list names of branches with unpushed commits | <p>Given a project with several local branches, each tracking some remote branch, is there a command that lists all branches that have unpushed commits? (That is, even if none of those branches are checked out.)</p>
<p>I don't want to see the commits themselves, nor do I want to see branches that are up-to-date, I just want to see which branches are ahead of their remotes.</p>
<p>I have tried <code>git log --branches --not --remotes --simplify-by-decoration --decorate --oneline</code>, but it doesn't seem to show what I need. Running it on my current repo gives no output, but running <code>git status</code> on my current branch shows <code>Your branch is ahead of 'origin/branchname' by 2 commits.</code></p>
<p><code>git for-each-ref --format="%(refname:short) %(push:track)" refs/heads</code> and <code>git branch -v</code> both show branches that are up to date as well as ones that need pushing. However, they <em>do</em> both show my current branch as <code>[ahead 2]</code>.</p>
<p>Other commands I have found eg. <code>git log @{u}..</code>, <code>git cherry -v</code> list the commits themselves, not the branches.</p>
<p><strong>Side question:</strong> why would the output from <code>git log --branches --not --remotes --simplify-by-decoration --decorate --oneline</code> not include branches that <code>git branch -v</code> shows as ahead? Isn't the former command just looking at which <code>refs/heads</code> do not correspond to a known remote; so wouldn't a branch listed as <code>[ahead 2]</code> meet this criteria?</p> | 0 |
MongoDB Date range query for past hour | <p>I'm trying to write MongoDB query which will be return data from one hour ago.
There is a column <code>time</code> with timestamps (<code>"time" : NumberLong("1471953787012")</code>) and this is how it looks in SQL:</p>
<pre><code>select name from table
where time between (NOW() - INTERVAL 1 HOUR) AND (NOW())
</code></pre>
<p>How do I write a MongoDB query to find a date range from one hour ago?
I'm trying with <code>new Date()</code> function but it doesn't work.
Does anyone know what I'm doing wrong?</p>
<pre><code>db.coll.find({
"time" : {
$lt: new Date(),
$gte: new Date(new Date().setDate(new Date().getDate()-1))
}
})
</code></pre> | 0 |
composer update without dependencies | <p><a href="https://i.stack.imgur.com/PKlCN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PKlCN.png" alt="enter image description here"></a>I am using yii2 framework since last few weeks. But now I am getting some issues with composer itself.</p>
<p>Just for info, I am using ubuntu 14.04</p>
<p>When I require some new package / extensions, I do the composer add by using composer require command. But I noticed that sometimes it's removing few of the existing packages from my vendor and project.</p>
<p>I tried with following commands.</p>
<pre><code>composer require dmstr/yii2-adminlte-asset "*"
composer require 2amigos/yii2-file-upload-widget:~1.0
</code></pre>
<p>And also tried with some googling.</p>
<p><a href="http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/" rel="nofollow noreferrer">http://www.yiiframework.com/wiki/672/install-specific-yii2-vendor-extension-dependency-without-updating-other-packages/</a></p>
<p>But it's not working.</p>
<p>Is there a way to add a new package / extension into your existing yii 2 project without removing existing packages or without any composer update command?</p>
<p><strong>Composer.json</strong></p>
<pre><code>{
"name": "sganz/yii2-advanced-api-template",
"description": "Improved Yii 2 Advanced Application Template By Sandy Ganz, Original by Nenad Zivkovic",
"keywords": ["yii2", "framework", "advanced", "improved", "application template", "nenad", "sganz"],
"type": "project",
"license": "BSD-3-Clause",
"support": {
"tutorial": "http://www.freetuts.org/tutorial/view?id=6",
"source": "https://github.com/sganz/yii2-advanced-api-template.git"
},
"minimum-stability": "dev",
"prefer-stable":true,
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "*",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "*",
"nenad/yii2-password-strength": "*",
"mihaildev/yii2-ckeditor": "*",
"dmstr/yii2-adminlte-asset": "*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
"yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"codeception/specify": "*",
"codeception/verify": "*"
},
"config": {
"vendor-dir": "protected/vendor",
"process-timeout": 1800
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "protected/vendor/npm",
"bower-asset-library": "protected/vendor/bower"
}
}
}
</code></pre>
<p>Any help on this would be greatly appreciated.</p> | 0 |
System.OutOfMemoryException occurs frequently after Upgrading SQL Server 2016 to version 13.0.15700.28 | <p>I am running Windows 10 Pro 64 bit on a dev box that has multiple monitors, 16 gigs DDR4 RAM, 4 Ghz I7, GTX 970. I run SQL Management Studio with SQL Server 2016 Developer Edition along with VS 2015 Enterprise Update 3. </p>
<p>Yesterday I upgraded Sql Management Studio 2016 to 13.0.15700.28 and it was like a poison pill for my machine. Now after an hour or two it will throw an out of memory except:</p>
<blockquote>
<p>An error occurred while executing batch. Error message is: Exception
of type 'System.OutOfMemoryException' was thrown</p>
</blockquote>
<p>Now this is sometimes typical if you are doing very large return sets of over a few million rows. NOT if you are doing</p>
<pre><code>Select Top 10 * from SmallObject
</code></pre>
<p>I was doing some new table and procedure creation for new objects to an existing development system. And this just occurs out of the blue for no rhyme or reason. It also appears to be a partial blocking error for SSMS as it now freezes the system and attempts to bring up a connection dialog window like I am first starting SSMS and attempting to connect to a datasource. Thus far it goes to a crawl until I kill it from task manager. I am also running Redgate's SQL Prompt 7.2.0.241. Things I have tried:</p>
<ol>
<li>Attempted to keep tabs under five at a time and close them as I am done.</li>
<li>Do not break off the tabs from one screen to another.</li>
<li>Turn off Redgate and see if it is the culprit</li>
<li>Check memory use as I go</li>
</ol>
<p>I know it blew up last night as I came into work and SSMS let me know it had crashed. This may be an MS bug but there may be a bug in Redgate or some other config I have so I thought it best to ask SO and see what others have seen. This build of SSMS is as of 8/15/2016 so it is very new.</p>
<p>Two errors from stack traces of Application Event Logs: Event 1026</p>
<blockquote>
<p>Application: ssms.exe Framework Version: v4.0.30319 Description: The
process was terminated due to an unhandled exception. Exception Info:</p>
<p>System.ComponentModel.Win32Exception at
System.Windows.Forms.NativeWindow.CreateHandle(System.Windows.Forms.CreateParams)
at System.Windows.Forms.Control.CreateHandle() at
System.Windows.Forms.ComboBox.CreateHandle() at
System.Windows.Forms.Control.CreateControl(Boolean) at
System.Windows.Forms.Control.CreateControl(Boolean) at
System.Windows.Forms.Control.CreateControl(Boolean) at
System.Windows.Forms.Control.CreateControl(Boolean) at
System.Windows.Forms.Control.CreateControl(Boolean) at
System.Windows.Forms.Control.CreateControl() at
System.Windows.Forms.Control.WmShowWindow(System.Windows.Forms.Message
ByRef) at
System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message
ByRef) at
System.Windows.Forms.ScrollableControl.WndProc(System.Windows.Forms.Message
ByRef) at
System.Windows.Forms.Form.WmShowWindow(System.Windows.Forms.Message
ByRef) at
System.Windows.Forms.Form.WndProc(System.Windows.Forms.Message ByRef)
at
System.Windows.Forms.Control+ControlNativeWindow.OnMessage(System.Windows.Forms.Message
ByRef) at
System.Windows.Forms.Control+ControlNativeWindow.WndProc(System.Windows.Forms.Message
ByRef) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr,
Int32, IntPtr, IntPtr)</p>
</blockquote>
<p>The other one was an event log 1002 error 'Application Hang' and has no real meaningful help that I can see:</p>
<blockquote>
<p>
Ssms.exe
2015.130.15700.28
68ac
01d1f98d17a32d16
4294967295
C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\Ssms.exe
62a64950-658b-11e6-a2c8-f832e4a07fda
</p>
<p>54006F00700020006C006500760065006C002000770069006E0064006F0077002000690073002000690064006C00650000000000</p>
<p></p>
</blockquote>
<p><strong>Updated 8-23-2016:</strong></p>
<p>Still get this error from time to time:</p>
<blockquote>
<p>The program Ssms.exe version 2015.130.15700.28 stopped interacting
with Windows and was closed. To see if more information about the
problem is available, check the problem history in the Security and
Maintenance control panel. Process ID: 35f8 Start Time:
01d1fca7e48da2da Termination Time: 4294967295 Application Path:
C:\Program Files (x86)\Microsoft SQL
Server\130\Tools\Binn\ManagementStudio\Ssms.exe Report Id:
4e8b6ab9-693f-11e6-a2cb-f832e4a07fda Faulting package full name:<br>
Faulting package-relative application ID:</p>
</blockquote>
<p>Clearly this is an issue for people other than me as I am getting votes on it here:
<a href="https://connect.microsoft.com/SQLServer/feedback/details/3062914/system-outofmemoryexception-thrown-by-even-small-selects-randomly-now" rel="noreferrer">https://connect.microsoft.com/SQLServer/feedback/details/3062914/system-outofmemoryexception-thrown-by-even-small-selects-randomly-now</a></p>
<p>If you have this happen to you or know a potential fix, please let me know. At this point if I have to do heavy SQL work coming up I am thinking of downgrading at this point. Again I am on Windows 10 64 bit machine and this only happened after upgrading to the most recent SSMS build.</p>
<p><strong>Update 8-24-2016</strong></p>
<p>MS appears to acknowledge this bug now. If you have this happen to you PLEASE go to this link and upvote:
<a href="https://connect.microsoft.com/SQLServer/feedback/details/3074856" rel="noreferrer">https://connect.microsoft.com/SQLServer/feedback/details/3074856</a></p>
<p><strong>Update 8-31-2016</strong></p>
<p>Latest from MS on exception:</p>
<blockquote>
<p>Posted by Microsoft on 8/29/2016 at 10:21 AM turns out there's a
thread leak in a utility class. The number of threads leaked will be
proportional to the number of registered servers you have, among other
things. A fix is coming in the next release</p>
</blockquote>
<p>I downgraded as doing work got more important than figuring out what was blowing up. Downgrade for me is working fine now. I gave MS SQL dumps so hopefully they can get a new build in the coming weeks. If you are curious I am on version 13.0.15600.2 and stable thus far as I downgraded two days ago.</p> | 0 |
Convert.ToDateTime('Datestring') to required dd-MM-yyyy format of date | <p>I have string of Date which can be in any format of date but I wanted to convert it to <code>dd-MM-yyyy</code> format.<br>
I have tried every <code>Convert.ToDatetime</code> option which converts only to the System format. I want it to convert <code>dd-MM-yyyy</code> format. <br></p>
<p>Please reply. Thanks in Advance.</p> | 0 |
How to check if, elif, else conditions at the same time in django template | <p>I have 3 category in category field. I want to check it in django template and assign appropirte urls for 3 distinct category.</p>
<p>I tried:</p>
<pre><code>{% for entry in entries %}
{% if entry.category == 1 %}
<a href="{% url 'member:person-list' %}"><li>{{ entry.category }}</li></a>
{% elif entry.category == 2 %}
<a href="{% url 'member:execomember-list' %}"><li>{{ entry.category}}</li></a>
{% else %}
<a href="{% url 'member:lifemember-list' %}"><li>{{ entry.category}}</li></a>
{% endif %}
{% empty %}
<li>No recent entries</li>
{% endfor %}
</code></pre>
<p>But I know python only check first matching condition with if. Therefore it gave only one desired result. How do I get all three entries with their correct links?</p>
<p><strong>Edit:</strong></p>
<p>Though python only check first matching if condition, when use elif within for loop it check each condition until endfor loop. Therefore my answer below worked fine. </p> | 0 |
What measuring unit is used for file sizes in javascript? | <p>am trying to validate file size on the client side before uploading to server. However I think i need to calculate max-size in javascript.</p>
<p>So how do i write <strong>4MB</strong> in javascript ?
I would also want to know basically in what measuring unit is javascript calculated in terms of file size.</p>
<p>below is my colde:</p>
<pre><code>//Grab the file list
var files = e.target.files;
$.each(files,function(i,file){
//check for the correct file extensiton
var n = file.name,
s = file.size
t = file.type;
if(s > 4MB){
console.log("File is greater than 4MB");
}
}
</code></pre>
<p>Please help.Thank you.</p> | 0 |
How can I recreate a fragment? | <p>I'm using a widget called SwipeRefreshLayout, to refresh my fragment when someone pushes the view.</p>
<p>To recreate the activity I have to use:</p>
<pre><code>SwipeRefreshLayout mSwipeRefreshLayout;
public static LobbyFragment newInstance() {
return new LobbyFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_lobby, container, false);
receiver = new MySQLReceiver();
rlLoading = (RelativeLayout) view.findViewById(R.id.rlLoading);
gvLobby = (GridView) view.findViewById(R.id.gvLobby);
updateList();
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.mSwipeRefreshLayout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.pDarkGreen, R.color.pDarskSlowGreen, R.color.pLightGreen, R.color.pFullLightGreen);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getActivity().recreate();
}
});
return view;
}
</code></pre>
<p>But I don't want to recreate the full activity that contains the view pager, I would like to recreate the fragment. How can I do that?</p> | 0 |
qualified-id in declaration before '(' token | <p>This is some crazy error and is giving me a lot of trouble. </p>
<pre><code>#include <iostream>
using namespace std;
class Book {
private:
int bookid;
char bookname[50];
char authorname[50];
float cost;
public:
void getinfo(void) {
for (int i = 0; i < 5; i++) {
cout << "Enter Book ID" <<endl;
cin >> bookid;
cout << "Enter Book Name" << endl;
cin >> bookname;
cout << "Enter Author Name" << endl;
cin >> authorname;
cout << "Enter Cost" << endl;
cin >> cost;
}
}
void displayinfo(void);
};
int main()
{
Book bk[5];
for (int i = 0; i < 5; i++) {
bk[i].getinfo();
}
void Book::displayinfo() {
for(int i = 0; i < 5; i++) {
cout << bk[i].bookid;
cout << bk[i].bookname;
cout << bk[i].authorname;
cout << bk[i].cost;
}
}
return 0;
}
</code></pre>
<p>The error, as noted in the title is expected declaration before '}' token at the line void Book::displayinfo() in main</p>
<p>Also this error is coming expected '}' at end of input</p> | 0 |
MariaDB Insert BLOB Image | <p><strong>What I want to do?</strong> </p>
<ul>
<li>I want to insert a picture into a MariaDB database using the command line, using the LOAD_FILE fuction.</li>
</ul>
<p><strong>What's wrong?</strong></p>
<ul>
<li>I always get a NULL return.</li>
<li>I <strong>don't</strong> want a solution like: This is bad style and I haven't seen this so far - try to store the full path! I <strong>want</strong> to store this picture in this database and <strong>not</strong> the path.</li>
</ul>
<p><strong>System</strong></p>
<ul>
<li><p><em>mysql</em> Ver 15.1 Distrib 10.1.17-MariaDB, for Linux (x86_64) using readline 5.1</p></li>
<li><p><em>ArchLinux</em> 4.7.2-1-ARCH</p></li>
<li><p>A picture called <em>Test.jpg</em> (817KB) under <code>/home/user/Blob/Test.jpg</code>, <code>/tmp/Test.jpg</code> and even under <code>/var/lib(mysql/images/Test.jpg</code> </p></li>
<li><p>The picture belongs to the user and group mysql and has every permission I could imagine</p>
<pre><code>-rwxrwxrwx 1 mysql mysql 836508 20. Feb 2016 Test.jpg
</code></pre></li>
<li>I tested several users i.e. <em>mysql</em> and <em>root</em></li>
</ul>
<p><strong>Database</strong></p>
<p>I have created a database called <em>Blobtest</em> with a table called <em>Test</em> with a Blob and a Longblob variable. </p>
<pre><code>CREATE TABLE Test (id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,longblobimg LONGBLOB NOT NULL, blobimg BLOB NOT NULL, PRIMARY KEY(id));
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| longblobimg | longblob | NO | | NULL | |
| blobimg | blob | NO | | NULL | |
+-------------+------------------+------+-----+---------+----------------+
</code></pre>
<p><strong>Insert Statement</strong></p>
<p>(in this case with the /home/user/directory)</p>
<pre><code>INSERT INTO Test VALUES (1, LOAD_FILE('/home/user/Blob/Test.jpg'), LOAD_FILE('/home/user/Blob/Test.jpg'));
</code></pre>
<p><strong>Approach to solving this problem</strong></p>
<p>I followed the instructions at this link <a href="https://stackoverflow.com/questions/18069054/mysql-load-file-loads-null-values">MySQL LOAD_FILE() loads null values</a></p>
<ul>
<li>I have execute permission on the parent directory</li>
<li>The FILE privilege is explicily granted. (GRANT FILE on . TO mysql@localhost)</li>
<li>I have flushed privileges</li>
<li>I have logged out and logged back in</li>
<li>I have tested several directories, belonging to <em>mysql</em> or <em>user</em> via <code>chmod</code> and <code>chown</code> command</li>
<li><code>SHOW VARIABLES LIKE 'max_allowed_packet';</code> is set to 16 MB or 16777216, picture is 817KB <em>big</em></li>
<li><code>select HEX(LOAD_FILE('/home/user/Blob/Test.jpg'));</code> returns NULL</li>
</ul>
<p><strong>Solutions?</strong></p>
<p>I don't know if this is a bug in MariaDB or if I'm the only one who has this problem.
To point this out again: I <strong>want</strong> to store the picture within this database. I <strong>don't</strong> want to store the path. This is an experiment, I have to store the picture in the database.</p>
<p>It would be awesome if somebody can help me with this problem!</p> | 0 |
Custom View - self.frame is not correct? | <p>So I have a custom UIView class</p>
<pre><code>class MessageBox: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
createSubViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createSubViews()
}
func createSubViews() {
let testView = UIView(frame: self.frame)
testView.backgroundColor = UIColor.brown
self.addSubview(testView)
}
}
</code></pre>
<p>I added a UIView inside the storyboard and gave it some constraints:</p>
<blockquote>
<p>100 from the top (superview), 0 from the left and right, height is 180</p>
</blockquote>
<p>But when I run the app the brown subview I created in the code is way to big. I printed <code>self.frame</code> in my custom view and it turns out that the frame is <code>(0,0,1000,1000)</code>. But why? I set constraints, it should be something like <code>(0,0,deviceWith, 180)</code>.</p>
<p><a href="https://i.stack.imgur.com/6BH5s.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6BH5s.png" alt="enter image description here"></a></p>
<p>What did I do wrong?</p>
<p>EDIT: That's my Storyboard setup:</p>
<p><a href="https://i.stack.imgur.com/gXHj2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gXHj2.png" alt="enter image description here"></a></p> | 0 |
PySpark: TypeError: 'Column' object is not callable | <p>I'm loading data from HDFS, which I want to filter by specific variables. But somehow the Column.isin command does not work. It throws this error:</p>
<blockquote>
<p>TypeError: 'Column' object is not callable</p>
</blockquote>
<pre><code>from pyspark.sql.functions import udf, col
variables = ('852-PI-769', '812-HC-037', '852-PC-571-OUT')
df = sqlContext.read.option("mergeSchema", "true").parquet("parameters.parquet")
same_var = col("Variable").isin(variables)
df2 = df.filter(same_var)
</code></pre>
<p>The schema looks like this:</p>
<pre><code>df.printSchema()
root
|-- Time: timestamp (nullable = true)
|-- Value: float (nullable = true)
|-- Variable: string (nullable = true)
</code></pre>
<p>Any idea what am I doing wrong? PS: It's Spark 1.4 with Jupyter Notebook.</p> | 0 |
RecyclerView with GridLayoutManager inside RecyclerView with LinearLayoutManager | <p>I am basically trying the achieve this design principle (<a href="https://material.google.com/components/cards.html#cards-actions" rel="nofollow noreferrer">from Google's Material Design</a>):
<a href="https://i.stack.imgur.com/bz59T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bz59T.png" alt="enter image description here"></a>
Thus I've made a parent <code>RecyclerView</code> with a <code>LinearLayoutManager</code>, then in the <code>RecyclerView</code> adapter, I've put the child <code>RecyclerView</code> with a <code>GridLayoutManager</code> for the "rich media" section (Action area 2). Everything works fine, except for the fact that I've set the internal <code>RecyclerView</code> grid to have a <code>match_parent</code> width and a <code>wrap_content</code> height, but it won't calculate the size of the content properly, seemingly leaving it at 0 & thus hidden. If I set the child <code>RecyclerView</code> to a specific height, the items show within, but are then of course cut off at the bottom.
Others seem to have come across this problem, <a href="https://stackoverflow.com/questions/32011995/how-to-have-a-listview-recyclerview-inside-a-parent-recyclerview-i-have-a-pare">but in their case, both have linear layouts</a>. (Also see <a href="https://stackoverflow.com/questions/34569217/how-to-add-a-recyclerview-inside-another-recyclerview">"Khay's" answer here</a>.)</p>
<p>Now my question is, how would one override the <code>onMeasure</code> method as "pptang" did in the accepted answer of the linked question above, but within a custom <code>GridLayoutManager</code> instead of a custom <code>LinearLayoutManager</code>? I haven't posted my code here, because it's essentially the identical to the one linked, only that I need to make a custom <code>GridLayoutManager</code> instead for the child <code>RecyclerView</code>, so that it measures correctly as "pptang's" answer states.</p>
<p>Otherwise, is there a better way than to use 1 RecyclerView inside a 2nd RecyclerView? Can only 1 RecyclerView populate an activity/fragment both with a list of the above <code>CardViews</code> and a grid of unique items within each <code>CardView</code>? </p> | 0 |
How to correctly configure the property "sonar.java.binaries"? | <p>We are using SonarQube 5.1.2 using Ant runner 2.2 and Java pluging 3.12 for the analysis. I can succesfully analyse my project. I just keep getting this error:</p>
<pre><code>Java bytecode has not been made available to the analyzer. The org.sonar.java.bytecode.visitor.DependenciesVisitor@d678716, org.sonar.java.checks.unused.UnusedPrivateMethodCheck@58e28efd, CycleBetweenPackages rule are disabled.
</code></pre>
<p>So I need to configure my sonar.java.binaries and sonar.java.test.binaries properties (following <a href="http://docs.sonarqube.org/display/PLUG/Java+Plugin+and+Bytecode" rel="noreferrer">http://docs.sonarqube.org/display/PLUG/Java+Plugin+and+Bytecode</a>). </p>
<p>Which I think I have done correctly:</p>
<pre><code><property name="project.dir" value="${basedir}/xalg.prj/h3_service_fo" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main" />
<property name="sonar.java.test.binaries" value="${project.build.dir}/classes/test" />
</code></pre>
<p>Which resolve to the following valid directories for the above properties:</p>
<pre><code>basedir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj
project.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo
sonar.java.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\xalg.prj\\h3_service_fo\\build\\classes\\main
sonar.java.test.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/classes/test
</code></pre>
<p>But I keep getting:</p>
<pre><code>Java bytecode has not been made available to the analyzer. The org.sonar.java.bytecode.visitor.DependenciesVisitor@d678716, org.sonar.java.checks.unused.UnusedPrivateMethodCheck@58e28efd, CycleBetweenPackages rule are disabled.
</code></pre>
<p>And for the life of me, I can not figure out what values I need to give the sonar.java.binaries and sonar.java.test.binaries properties. I even tried using sonar.binaries, which gave me the following output:</p>
<pre><code>Binary dirs: xalg.prj/h3_service_fo/build/classes
</code></pre>
<p>Which I did not get using either sonar.java.binaries or sonar.java.test.binaries. I also got:</p>
<pre><code>JavaClasspath initialization...
sonar.binaries and sonar.libraries are deprecated since version 2.5 of sonar-java-plugin, please use sonar.java.binaries and sonar.java.libraries instead
</code></pre>
<p>Which is to be expected for a deprecated property. But using the sonar.java.binaries property I did not get the "Binary dirs" line in my log.</p>
<p>Using sonar.java.binaries:</p>
<pre><code>Language is forced to java
Load rules
Load rules (done) | time=761ms
Code colorizer, supported languages: cs,plsql
Initializers :
Base dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj
Working dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj\.sonar
Source paths: xalg.prj/h3_service_fo/src/main/java
Test paths: xalg.prj/h3_service_fo/src/test/java
Source encoding: windows-1252, default locale: en_US
Index files
</code></pre>
<p>Versus using sonar.binaries:</p>
<pre><code>Language is forced to java
Load rules
Load rules (done) | time=736ms
Code colorizer, supported languages: cs,plsql
Initializers :
Base dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj
Working dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj\.sonar
Source paths: xalg.prj/h3_service_fo/src/main/java
Test paths: xalg.prj/h3_service_fo/src/test/java
Binary dirs: xalg.prj/h3_service_fo/build/classes
Source encoding: windows-1252, default locale: en_US
Index files
</code></pre>
<p>I also looked into the source code of SonarQube, SonarQube Java Plugin and the SonarQube Scanner for instances of either "Java bytecode has not been made available to the analyzer." or sonar.java.binaries. I found plenty on sonar.java.binaries, but nothing on "Java bytecode has not been made available to the analyzer." So I have no clue what conditions exactly trigger that error.</p>
<p>I also tried the following permutations on sonar.java.binaries:</p>
<pre><code><property name="sonar.java.binaries" location="${project.build.dir}/classes" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main/nl" />
</code></pre>
<p>But that did nothing either.</p>
<p>What is weird is that Squid seems to resolve the classpath just fine:</p>
<pre><code>----- Classpath analyzed by Squid:
D:\appl\BuildAgent\work\H3\src.prj\java.prj\xalg.prj\h3_service_fo\build\classes\main
</code></pre>
<p>So, what am I missing? What am I doing wrong? Thanks in advance.</p>
<p><strong>Update 2016-09-08</strong>:<br>
Removed the entire log, the post become to long.</p>
<p>A subset with the (I think) relevant paths:</p>
<pre><code>project.build.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build
project.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo
project.src.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/src
sonar.dir=D\:/appl/sonarqube-5.1.2
sonar.working.directory=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\.sonar
sonar.projectBaseDir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj
sonar.jacoco.reportPath=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/jacoco/test.exec
sonar.junit.reportsPath=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/test-results
sonar.sources=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/src/main/java
sonar.java.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\xalg.prj\\h3_service_fo\\build\\classes\\main
sonar.java.libraries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_deploy/*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_repos/lib/*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_repos/provided/*.jar
sonar.tests=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/src/test/java
sonar.java.test.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/classes/test
sonar.java.test.libraries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_deploy/*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_repos/lib/*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_repos/provided/*.jar
</code></pre>
<p>The paths have exactly the same format as in my post. Could it be that the Sonar Ant runner can't figure out a path with both backslashes and slashes?</p>
<p><strong>Update 2016-09-16</strong>:<br>
Removed the entire log, the post become to long.</p>
<p>A subset with the (I think) relevant paths:</p>
<pre><code>project.build.dir=xalg.prj\\\\h3_service_fo\\\\build
project.dir=xalg.prj\\\\h3_service_fo
project.src.dir=xalg.prj\\\\h3_service_fo\\\\src
sonar.dir=D\:\\\\appl\\\\sonarqube-5.1.2
sonar.working.directory=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\.sonar
sonar.projectBaseDir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj
sonar.jacoco.reportPath=xalg.prj\\\\h3_service_fo\\\\build\\\\jacoco/test.exec
sonar.junit.reportsPath=xalg.prj\\\\h3_service_fo\\\\build\\\\test-results
sonar.sources=xalg.prj\\\\h3_service_fo\\\\src\\\\main\\\\java
sonar.java.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\xalg.prj\\h3_service_fo\\build\\classes\\main
sonar.java.libraries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_deploy\\\\*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_repos\\\\lib\\\\*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_repos\\\\provided\\\\*.jar
sonar.tests=xalg.prj\\\\h3_service_fo\\\\src\\\\test\\\\java
sonar.java.test.binaries=xalg.prj\\\\h3_service_fo\\\\build\\\\classes\\\\test
sonar.java.test.libraries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_deploy\\\\*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_repos\\\\lib\\\\*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_repos\\\\provided\\\\*.jar
</code></pre>
<p>Some paths have become relative, but I think that is because TeamCity changed the Ant file to the file in SVN.
The sonar.java.binaries is absolute and it <strong>definitely</strong> points to the correct directory. </p>
<p>But I still get this error:</p>
<pre><code>09:17:52.299 INFO - Java Main Files AST scan done: 1579 ms
09:17:52.301 INFO - 2/2 source files have been analyzed
09:17:52.305 WARN - Java bytecode has not been made available to the analyzer. The org.sonar.java.bytecode.visitor.DependenciesVisitor@757a48f9, org.sonar.java.checks.unused.UnusedPrivateMethodCheck@1adf492b, CycleBetweenPackages rule are disabled.
</code></pre>
<p>The classpath is still interpreted just fine:</p>
<pre><code>[sonar:sonar] 09:17:51.971 DEBUG - ----- Classpath analyzed by Squid:
[sonar:sonar] 09:17:51.972 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\xalg.prj\h3_service_fo\build\classes\main
[sonar:sonar] 09:17:51.973 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\batch.daemon.jar
[sonar:sonar] 09:17:51.974 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\buildinfo.jar
[sonar:sonar] 09:17:51.975 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h2_shared.jar
[sonar:sonar] 09:17:51.975 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_generator.jar
[sonar:sonar] 09:17:51.976 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_loadtest.jar
[sonar:sonar] 09:17:51.977 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_common.jar
[sonar:sonar] 09:17:51.977 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg.jar
[sonar:sonar] 09:17:51.978 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_dao.jar
[sonar:sonar] 09:17:51.979 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_mappers.jar
[sonar:sonar] 09:17:51.979 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_procedures.jar
[sonar:sonar] 09:17:51.980 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare.jar
[sonar:sonar] 09:17:51.981 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_dao.jar
[sonar:sonar] 09:17:51.982 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_mappers.jar
[sonar:sonar] 09:17:51.982 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_procedures.jar
</code></pre>
<p>Could the Sonar Ant runner have a problem with the escaped back slashes?</p> | 0 |
React Native, Android Log. | <p>Is there a way in react native to see the log from native (java) modules of android?</p>
<p>I'm using javas log module <a href="https://developer.android.com/reference/android/util/Log.html" rel="noreferrer">https://developer.android.com/reference/android/util/Log.html</a> - but I'm not getting anything from there. and to be honest I'm not sure how to use it if it's at all possible. atm there isn't much code - it's just </p>
<pre><code> Log.d("Notification","Notify App");
</code></pre>
<p>Because I want to see if I can see the notifications somewhere - I do know the java module is registered correctly as I'm calling other functions from it.</p>
<p>Thanks!</p> | 0 |
Write col names while writing csv files in R | <p>What is the proper way to append col names to the header of csv table which is generated by <code>write.table</code> command?
For example <code>write.table(x, file, col.names= c("ABC","ERF"))</code> throws error saying <code>invalid col.names specification</code>.Is there way to get around the error, while maintaining the function header of <code>write.table</code>.</p>
<p>Edit:
I am in the middle of writing large code, so exact data replication is not possible - however, this is what I have done:
<code>write.table(paste("A","B"), file="AB.csv", col.names=c("A1","B1"))</code> , I am still getting this error <code>Error in write.table(paste("A","B"), file="AB.csv", col.names=c("A", : invalid 'col.names' specification.</code></p> | 0 |
ERROR ITMS-90023: "Missing required icon file" | <p>Hi i try to submit my app to iTunes connect but Application Loader displays the following errors:</p>
<blockquote>
<p>ERROR ITMS-90023: "Missing required icon file. The bundle does not contain an app icon for iPad of exactly '76x76' pixels, in .png format for iOS versions >= 7.0."</p>
<p>ERROR ITMS-90023: "Missing required icon file. The bundle does not contain an app icon for iPad of exactly '76x76' pixels, in .png format for iOS versions >= 7.0."</p>
<p>ERROR ITMS-90023: "Missing required icon file. The bundle does not contain an app icon for iPad of exactly '167x167' pixels, in .png format for iOS versions supporting iPad Pro."</p>
</blockquote>
<p>I really don't understand why i'm getting those error, all my images are in places, I use asset catalog and I never encountered the problem before.</p>
<p><a href="https://i.stack.imgur.com/r7bK0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/r7bK0.png" alt="AppIcons in my Asset Catalog"></a></p>
<p><a href="https://i.stack.imgur.com/285to.png" rel="noreferrer"><img src="https://i.stack.imgur.com/285to.png" alt="attributes inspector"></a></p>
<p>If someone can help me,... thanks a lot</p> | 0 |
How to set the row index name in R? (Like DF.index.name in Pandas) | <p><strong>How can I set the row index name in a <code>R</code> <code>data.frame</code> object?</strong> </p>
<p>I tried looking on stackoverflow for the answer but I couldn't figure out how to even search for it? <a href="https://stackoverflow.com/search?q=set+row+index+name+dataframe+R">https://stackoverflow.com/search?q=set+row+index+name+dataframe+R</a></p>
<p>This one kind of explains it but they are converting it to a matrix?
<a href="https://stackoverflow.com/questions/17514648/how-do-i-name-the-row-names-column-in-r">How do I name the "row names" column in r</a></p>
<pre><code>> dimnames(DF_c) = c("sample","cluster")
Error in `dimnames<-.data.frame`(`*tmp*`, value = c("sample", "cluster" :
invalid 'dimnames' given for data frame
</code></pre>
<p>In Python <code>Pandas</code>, I would simply do <code>DF_c.index.name = "samples"</code> but I don't know how to do it in <code>R</code>. I noticed that when I saved it <code>write.table(DF_c, "output.tsv", sep="\t")</code> It puts my column label as the row name but I can't do something like <code>colnames(DF_c) = c( "samples","cluster")</code> since there is only 1 column? </p>
<pre><code># Clusters
DF_c = data.frame(last_iter$c)
rownames(DF_c) = row_labels
colnames(DF_c) = c( "cluster")
</code></pre>
<p>Bonus:
How to not include the <code>"</code> when it's writing table to output?</p>
<p><a href="https://i.stack.imgur.com/SlF8Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SlF8Q.png" alt="enter image description here"></a></p> | 0 |
Grab last n items from C# list | <p>I have a C# <code>List<T></code> of items. I want to iterate from a certain index to the end of the <code>List<T></code> of items. Can I do this using the <em>foreach</em> syntax? </p>
<pre><code> List<T> list = ...
foreach (var item in ???)
{
...
}
</code></pre>
<p>or any other method?</p>
<p>e.g. from <code>List.Count - 50</code> until the end (I only want the <em>last</em> <code>50</code> items)</p> | 0 |
Can´t run .bat file under windows 10 | <p>I have few <code>.bat</code> files that I used under Windows XP. Now I want to use them under Windows 10, but when I run one of the files (even as administrator) it shows the command prompt screen for 1 second and nothing happens.</p>
<p>Can someone help me please?</p> | 0 |
Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) in Java RESTful web service call | <p>I have the following javascript in my test html page to send ajax requests to a java restful web service I built with netbeans (mostly auto generated by using 'Restful web services from database' function).
Here is the ajax query from my test html page:</p>
<pre><code>$(function(){
$('.message-button').on('click', function(e){
var resultDiv = $("#resultDivContainer");
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': 'http://localhost:8080/xxxAPI/api/activity',
'data': { "baseItemId": "2" },
'dataType':'json',
'success': function(data) {
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
$("#resultDivContainer").text(xmlstr);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert(' Error in processing! '+textStatus + 'error: ' + errorThrown);
}
});
})
});
</code></pre>
<p>Also here is the part of my java code that accepts post requests:</p>
<pre><code>@POST
@Override
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(XxxxxActivity entity) {
super.create(entity);
}
</code></pre>
<p>When I request from the test page (for this version of the test page), I get this error: </p>
<blockquote>
<p>Failed to load resource: the server responded with a status of 415
(Unsupported Media Type)</p>
</blockquote>
<p>or this error:</p>
<blockquote>
<p>POST <a href="http://localhost:8080/xxxAPI/api/activity" rel="nofollow">http://localhost:8080/xxxAPI/api/activity</a> 415 (Unsupported
Media Type)</p>
</blockquote>
<p>So far I have tried making various changes to the ajax request as advised on similar questions on stackoverflow, including changing type to <code>jsonp</code>, putting json data in double quotes, adding headers and changing data type to xml. None of them have worked. </p>
<p>Also since I manage to get a response from the server at times, I wonder if the issue is with xml parsing in the java code. I believe a potential fix would be to add the jackson jar files, but I have no idea how to add them on netbeans as there is no lib folder in WEB_INF. </p>
<p>I would also like to know if there is any issue with the jquery ajax request. This issue has been bugging me for days.</p>
<p><strong>PS</strong>: Also note that GET requests from the browser work fine. I have not used maven in this project. </p> | 0 |
MSCOMCTL.ocx missing Windows 10 | <p>I have some vb6 applications that i'm trying to move from Windows 7 to Windows 10. I have the .exe file, but when I tried to open it - it tells me that:</p>
<blockquote>
<p>C:\App_1\MSCOMCTL.OCX could not be loaded - Continue Loading Project?</p>
</blockquote>
<p>I searched for this file in <code>C:\Windows\SysWow64</code> and found that the file is actually there as <code>Type: ActiveX Control</code>.</p>
<p>Any reason why I'm still getting the error?</p> | 0 |
Center position of current screen position | <p>Is there an option to find center position (top and left) of an actual screen position?</p>
<p>My main goal is to show div in the center of the screen no matter where i scroll or click</p> | 0 |
Update if the name exists else insert - in SQL Server | <p>I want update in my table if my given filename is already in my database else I want to insert a new row. I try this code but the <code>EXISTS</code> shown error please give me the correct way beacuse iam fresher in SQL </p>
<pre><code>public void SaveData(string filename, string jsonobject)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=;Integrated Security=True");
SqlCommand cmd;
SqlCommand cmda;
if EXISTS("SELECT * FROM T_Pages WHERE pagename = '" + filename + "") {
cmda = new SqlCommand("UPDATE T_Pages SET pagename='" + filename + "',pageinfo='" + jsonobject + "' WHERE pagename='" + filename + "'", con);
cmda.ExecuteNonQuery();
}
else {
cmd = new SqlCommand("insert into T_Pages (pagename,pageinfo) values('" + filename + "','" + jsonobject + "')", con);
cmd.ExecuteNonQuery();
}
con.Close();
}
</code></pre> | 0 |
exclude search pattern with select-string in powershell | <p>I'm using select string to search a file for errors. Is it possible to exclude search patterns as with grep. Ex:</p>
<pre><code>grep ERR* | grep -v "ERR-10"
select-string -path logerror.txt -pattern "ERR"
</code></pre>
<p>logerror.txt</p>
<pre><code>OK
ERR-10
OK
OK
ERR-20
OK
OK
ERR-10
ERR-00
</code></pre>
<p>I want to get all the ERR lines, but not the ERR-00 and ERR-10</p> | 0 |
Html.TextBoxFor only accepting a number greater than zero | <p>I've made an form and I want the <code>@Html.TextBoxFor</code> to accept values equal or higher than <code>1</code>. That means: the value can't be 0 or lower.</p>
<p><strong>Model:</strong></p>
<pre><code>[Required(ErrorMessage = "//")]
[RegularExpression(@"^[0-9]{1,3}$", ErrorMessage = "//")]
public string Time { get; set; }
</code></pre>
<p><strong>View:</strong></p>
<pre><code>@Html.TextBoxFor(model => model.Time)
</code></pre>
<p>Can I do this with a DataAnnotation, or is there an other way?</p> | 0 |
Apache CXF: A SOAP 1.2 message is not valid when sent to a SOAP 1.1 only endpoint | <p>first of all, I know that there are already some questions on SO about this topic but none of them solved my problem (or I am too stupid to understand them, that's a possibility as well).</p>
<p>So, I have a WSDL. From the WSDL I've generated a Java client using Eclipse CXF plugin. Now I'm doing this:</p>
<pre><code>JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(MyServiceInterface.class);
factory.setAddress("myEndpoint");
List<Interceptor<? extends Message>> interceptors = new ArrayList<Interceptor<? extends Message>>();
interceptors.add(new HeaderOutInterceptor());
factory.setOutInterceptors(interceptors);
MyServiceInterface service = (MyServiceInterface) factory.create();
</code></pre>
<p>The interceptor only adds an header to the requests I'm sending through the client:</p>
<pre><code>message.put(Message.CONTENT_TYPE, "application/soap+xml");
</code></pre>
<p>I'm adding this manually since by default the content type is text/xml and I get a 415 error.</p>
<p>The problem is that with this configuration I get this exception:</p>
<pre><code>org.apache.cxf.binding.soap.SoapFault: A SOAP 1.2 message is not valid when sent to a SOAP 1.1 only endpoint.
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:178)
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:69)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
</code></pre>
<p>I've tried adding this annotation to the generated client interface:</p>
<pre><code>@BindingType(javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
</code></pre>
<p>But nothing changed. Can anybody help me?</p>
<p><strong>EDIT</strong></p>
<p>I've added a cxf.xml file under the classpath. This is the content:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:soap="http://cxf.apache.org/bindings/soap"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/bindings/soap
http://cxf.apache.org/schemas/configuration/soap.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">
<jaxws:endpoint serviceName="ClabService" endpointName="ClabServicePort">
<jaxws:binding>
<soap:soapBinding version="1.2" mtomEnabled="true" />
</jaxws:binding>
</jaxws:endpoint>
</beans>
</code></pre>
<p>However, now I get this exception:</p>
<pre><code>Exception in thread "main" java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.apache.cxf.jaxws.EndpointImpl---51955260': Invocation of init method failed; nested exception is javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException: serviceClass must be set to a valid service interface or class
</code></pre>
<p>I've tried to add this during the factory configuration:</p>
<pre><code>factory.setServiceClass(MyServiceInterface_Service.class);
</code></pre>
<p>but nothing changed.</p> | 0 |
Where does GitHub store my code and files? | <p>I have tried to found out, where does <a href="https://github.com/" rel="nofollow noreferrer">GitHub</a> store the code and files I commit? After a lot of search I found only that it is stored in the Cloud. This is too broad for me. I don't have (or don't know) the method, how to found exact answer.</p>
<p>Where does GitHub store my code and other data I commit? What is the hosting of GitHub?</p> | 0 |
How to Use MVC Controller and WebAPI Controller in same project | <p>I am trying to use an MVC Controller and a Web API controller in the same project, but I get 404 errors for the Web API. I started the project as an MVC project in VS 2015, but then added the Web API controller, and with the default code it is giving a 404 error.</p>
<p>What could be the possible solution? I have tried some solutions on Stack Overflow, but they didn't work. One I tried is the accepted answer from this question: <a href="https://stackoverflow.com/questions/15556035/all-asp-net-web-api-controllers-return-404">All ASP.NET Web API controllers return 404</a></p>
<p><strong>Global.asax:</strong></p>
<pre><code>protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);//WEB API 1st
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
</code></pre>
<p><strong>WebApiConfig:</strong> </p>
<pre><code>public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
</code></pre>
<p><strong>RouteConfig</strong>:</p>
<pre><code>public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
</code></pre>
<p><strong>Web API Controller:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using O365_APIs_Start_ASPNET_MVC.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using O365_APIs_Start_ASPNET_MVC.Helpers;
using System.Threading.Tasks;
namespace O365_APIs_Start_ASPNET_MVC.Controllers
{
public class MAILAPIController : ApiController
{
private MailOperations _mailOperations = new MailOperations();
//async Task<BackOfficeResponse<List<Country>>>
// GET: api/MAILAPI
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/MAILAPI/5
public string Get(int id)
{
return "value";
}
// POST: api/MAILAPI
public void Post([FromBody]string value)
{
}
// PUT: api/MAILAPI/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/MAILAPI/5
public void Delete(int id)
{
}
}
}
</code></pre>
<p>I'm also getting an error restoring NuGet packages in the same solution:</p>
<blockquote>
<p>An error occurred while trying to restore packages: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.</p>
</blockquote> | 0 |
What is a Blob used in Jquery | <p>I came across <code>blob</code> while searching some stuff in jQuery. Googled about it but could not exactly figure out what kind of concept it is.</p>
<p>I found this code for downloading a pdf file through Ajax.</p>
<pre><code>$.ajax({
method: 'GET',
dataType: 'blob',
data: { report_type: report_type, start_date: start_date, end_date: end_date, date_type: date_type },
url: '/reports/generate_pdf.pdf',
success: function(data) {
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Report_"+new Date()+".pdf";
link.click();
console.log("pdf printed");
}
});
</code></pre>
<p>This code is working fine but printing empty pdf without the content either static or dynamic. But with a strange behaviour. I.e. if the dynamic data calculated is too big, it is generating multiple pages.</p>
<p>I just want to figure out the concept of <code>blob</code> so that I can figure out myself what this piece of code is doing and how does <code>blob</code> work.</p>
<p>Any proper guide or help would be really appreciated. Thanks in advance!</p> | 0 |
Jquery change select value not working | <p>I'm trying to set the select option with jquery but it's not working properly. It actually set the value but the text is not updated.</p>
<p>I have tried with <code>.prop('selected',true)</code>, <code>.attr('selected',true)</code>, <code>.prop('selected','selected')</code>, <code>.val()</code> and <code>.val().change()</code> but nothig seems to work</p>
<p>Here is the select</p>
<pre><code><select class="input-field" id="equip_type" name="equip_type">
<option value="" disabled selected>Tipo de Equipo </option>
<option value="0">equip_type_other</option>
<option value="1">equip_type_desktop</option>
<option value="2">equip_type_laptop</option>
<option value="3">equip_type_tablet</option>
<option value="4">equip_type_printer</option>
</select>
</code></pre>
<p>I'm going to set the option within an ajax function, so the value came from the function. This is what I'm currently trying</p>
<pre><code>$('#equip_type').val(data.equipType).change();
</code></pre>
<p>I have use the same method with other forms, but just this one is causing this truble. Is there something I'm missing?</p> | 0 |
android - Firebase Notification Push Notification not working | <p><strong>UPDATE</strong></p>
<blockquote>
<p><em>Unfortunately, I didn't solve this issue and what I did is create a new project. Fortunately my new project works. One thing I noticed
from my newly created project, when I am sending notification
messages, some messages didn't arrive to my device. So I think its my
Internet connection problem (my idea only).</em></p>
</blockquote>
<p>I am trying to implement basic receiving of Push Notifications using Firebase. I based this tutorial:</p>
<p><a href="https://www.codementor.io/android/tutorial/send-push-notifications-to-android-with-firebase" rel="nofollow">https://www.codementor.io/android/tutorial/send-push-notifications-to-android-with-firebase</a></p>
<p>My Problem is I don't receive any messages at all. I have sent more than 5 messages using the Firebase Console and still nothing happens. </p>
<p>Here is my implementation of FirebaseInstanceIdService:</p>
<pre><code>public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
public static final String debugTag = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token in logcat
Log.e(debugTag, "Refreshed token: " + refreshedToken);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
}
}
</code></pre>
<p>My FirebaseMessagingService implementation:</p>
<pre><code>public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String debugTag = "MyFirebaseApp";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(debugTag, "Notification Received!");
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
//This method is only generating push notification
private void sendNotification(String title, String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
</code></pre>
<p>My Manifest file:</p>
<p></p>
<pre><code><uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".messagingservice.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".tokenservice.MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
</code></pre>
<p></p>
<p>What am I doing wrong? Or what am I lacking to implement? </p>
<p>I am really needing some help with this one. Any help will be greatly appreciated. Thank you very much!</p> | 0 |
C++ system() function header file | <p>for system() function in c++, which header file to be used in code::Blocks ? please help me !</p> | 0 |
Can a Static method access a private method of the same class? | <p>I have this question because of the singleton/named constructor. In both cases, the real constructors are protected or private, neither of which can be accessed from outside. </p>
<p>For example, a short named constructor is this:</p>
<pre><code> class A
{
public:
static A createA() { return A(0); } // named constructor
private:
A (int x);
};
int main(void)
{
A a = A::createA();
}
</code></pre>
<p>I thought static method can only access static data member, or access private data/method via an existing object.
However, in the above code, private constructor <code>A()</code> isn't static, and at the time it is being called, no object exists either.
So the only explanation I can think of is that static method can access non-static private method of the same class. Can anyone please either affirm or negate my thought, possibly with some lines of explanations? </p>
<p>I apologize if this is too trivial however the key words are too common and I wasn't able to find an answer in dozens of google pages. Thanks in advance.</p> | 0 |
Excel VBA If cell.value = .. then Range(selection).offset().value issue | <p>I am getting an error on the code below:</p>
<pre><code>For Each cell In Range("H2", Selection.End(xlDown).End(xlDown).End(xlUp)).SpecialCells(xlCellTypeVisible)
If cell.Value = Range(Sheets("Mapping").Cells(4, x)).Value Then
Range(Selection).Offset(0, -7).Value = "=IF(LEFT(RC9,8)=Mapping!R8C1,""YES"",""NO"")"
Else
End If
</code></pre>
<p>This is part of a larger code where I am trying to have each visible cell in Column H compared to a cell on the mapping sheet and if correct then the if statement will be added into column A.</p>
<p>I am having a similar issue when attempting to use cell.value in another if statement where I include an AND statement, see below. Same type of FOR statement for Column I in this case. Comparing each value in column I to two different cells on the mapping sheet and if correct the changing column A's value to YES. Both lines break on the 3rd line and the second code breaks on the second line as well.</p>
<pre><code>For Each cell In Range("I2", Selection.End(xlDown).End(xlDown).End(xlUp)).SpecialCells(xlCellTypeVisible)
If cell.Value = Range(Sheets("Mapping").Cells(4, x)).Value And cell.Value = Range(Sheets("Mapping").Cells(9, 1)).Value Then
Range(Selection).Offset(0, -7).Value = "YES"
Else
'do nothing
</code></pre>
<p>Any help would be greatly appreciated.
Thanks.</p> | 0 |
How to use Distinct function in influxDB | <p>I am using influx DB and issuing command,</p>
<pre><code>SELECT * FROM interface
</code></pre>
<p>Below is the out put-</p>
<pre><code>interface
time element path value
2016-08-24T21:22:16.7080877Z "link-layer-address0" "key:/arp-information/link-layer-address0" "3c:61:04:48:df:91"
2016-08-24T21:22:17.9090527Z "link-layer-address0" "key:/arp-information/link-layer-address0" "3c:61:04:48:df:92"
2016-08-24T21:22:19.8584133Z "link-layer-address1" "key:/arp-information/link-layer-address1" "3c:61:04:48:df:97"
2016-08-24T21:22:20.3377847Z "link-layer-address2" "key:/arp-information/link-layer-address2" "3c:61:04:48:df:90"
</code></pre>
<p>When issue command it works fine. </p>
<pre><code>SELECT distinct(value) FROM interface
</code></pre>
<p>But When issue command for path column there is no out put. Wondering what i am missing?</p>
<pre><code>SELECT distinct(path) FROM interface
</code></pre> | 0 |