title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
aligning div at center text-align not working
<p>I want the circle to be aligned in center in 768 grid </p> <p><a href="http://jsfiddle.net/8dEN3/1/" rel="nofollow"><strong>Demo</strong></a></p> <h2>HTML</h2> <pre><code>&lt;div class="About_Container"&gt; &lt;div class="Icon_Wrapper"&gt; &lt;div class="Circle"&gt; &lt;div class="CircleWrapper"&gt; &lt;span class="Icon"&gt; &lt;img src="http://livedemo00.template-help.com/drupal_50108/sites/default/files/icon-service-3.png" /&gt; &lt;/span&gt; &lt;span class="Text"&gt; CUSTOMER GUARANTEEE &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="Text_Wrapper"&gt; Vestibulum quis felis ut enim aliquam iaculis. Nullam pharetra tortor at quam viverra volutpat. Phasellus vel faucibus dolor. Curabitur ac ni i non metus dignissim dapibus eu vel nibh. Phasellus &lt;/div&gt; &lt;div class="Link_Wrapper"&gt; &lt;a href="#"&gt;READ MORE&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <h2>CSS</h2> <pre><code>@media ( min-width: 120px) and (max-width:768px) { #Container_About { min-height: 1291px; background: #404040; width: 100%; float: left; } .TradeSlogan { font-size: 60px; line-height: 66px; font-family: 'Open Sans', sans-serif; color: #fff; margin-bottom: 25px; font-weight: 800; margin: 0; outline: 0; padding: 0; vertical-align: baseline; } .SomeTextWrapper { color: #949393; margin: 10px; } .SomeTextWrapper .SomeTextWrapper:before, .SomeTextWrapper:after { content: " "; /* 1 */ display: table; /* 2 */ } .SomeTextWrapper:after { clear: both; } /** * For IE 6/7 only * Include this rule to trigger hasLayout and contain floats. */ .SomeTextWrapper { *zoom: 1; } .About_Container { height: 100%; width: 100%; } .Circle { margin: 10px; height: 170px; width: 170px; border-radius: 170px; background: #949393; display: table-cell; vertical-align: middle; text-align: center; } .Icon_Wrapper { text-align: left; height: 100%; width: 100%; } .CircleWrapper { padding: 10px; } .CircleWrapper Icon, Text { float: left; height: 44%; width: 100%; margin: 3%; } .Text { display: table-cell; vertical-align: middle; text-align: center; color: #03c7de; font-weight: 600; font-size: 15px; letter-spacing: 1.5px; } .Text_Wrapper { margin: 25px; color: #03c7de; font-weight: 300; font-size: 11px; letter-spacing: 1.5px; } .Link_Wrapper { padding: 20px; text-align: right; } .Link_Wrapper a { color: #03c7de; font-weight: 300; font-size: 17px; letter-spacing: 1.5px; } </code></pre>
3
1,238
Matplotlib hangs when plotting
<p>I am trying to plot some datetime objects in Python with Matplotlib, <a href="https://stackoverflow.com/questions/7684475/plotting-labeled-intervals-in-matplotlib-gnuplot">just as I have seen at this question</a>.</p> <p>But when it gets to the savefig call, it gets stuck. This is my code:</p> <pre><code>import matplotlib as mpl mpl.use('Agg') # Matplotlib backend to use without an X-server import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, MinuteLocator from datetime import datetime from datetime import timedelta def plot_scenario(outages_start, outages_end, prediction_start, prediction_end, filepath=None): fig = plt.figure() ax = fig.add_subplot(111) y = [0.3, 0.7] timelines(ax, y[0], prediction_start, prediction_end, color='r') for xstart, xstop in zip(outages_start, outages_end): timelines(ax, y[1], xstart, xstop) ax.xaxis_date() myFmt = DateFormatter('%d %H:%M') ax.xaxis.set_major_formatter(myFmt) ax.xaxis.set_major_locator(MinuteLocator(0, interval=15)) # Delta needed to adjust the xlimits delta = (prediction_end - prediction_start) / 10 #ax.set_yticks(['Prediction', 'Outages']) #Not working ax.set_ylim(0, 1) ax.set_xlim(prediction_start - delta, prediction_end + delta) ax.set_xlabel('Time') if filepath is None: fig.show() else: # Save plot as PNG fig.savefig(filepath) # Gets stuck here print 'PGN file saved at ' + filepath # plot timelines at y from xstart to xstop with a given color def timelines(current_axis, y, xstart, xstop, color='b'): current_axis.hlines(y, xstart, xstop, color, lw=4) current_axis.vlines(xstart, y+0.03, y-0.03, color, lw=2) current_axis.vlines(xstop, y+0.03, y-0.03, color, lw=2) if __name__ == '__main__': prediction_start = datetime(2014, 3, 20) + timedelta(hours=12) prediction_end = prediction start + timedelta(hours=10) outages_start = [] outages_end = [] outages_start.append(datetime(2014, 3, 20) + timedelta(hours=14)) outages_end.append(datetime(2014, 3, 20) + timedelta(hours=15)) outages_start.append(datetime(2014, 3, 20) + timedelta(hours=17)) outages_end.append(datetime(2014, 3, 20) + timedelta(hours=18)) path = '/home/myuser/test.png' plot_scenario(outages_start, outages_end, prediction_start, prediction_end, path) </code></pre> <p>I'm using Agg since I'm working without X-server into an Ubuntu Server machine, but this can't be the problem because I made a simple range plot and the figure was saved correctly, so I must be making some mistake at the code.</p> <p>Any help?</p>
3
1,024
How to combine multiple object in Laravel
<p>I want to combine my ordered products and display the order list.</p> <p>Controller :</p> <pre><code>$orders = Order::where('customer_id', 1)-&gt;pluck('products'); print_r($orders); </code></pre> <p>This is what I receive:</p> <pre><code>Array ( [0] =&gt; [ {&quot;id&quot;:3,&quot;product_id&quot;:3,&quot;size&quot;:&quot;47&quot;,&quot;quantity&quot;:7,&quot;name&quot;:&quot;Simple Regular T-shirt&quot;,&quot;price&quot;:2200,&quot;thumbnail&quot;:&quot;Thumbnail_614291597.jpg&quot;}, {&quot;id&quot;:7,&quot;product_id&quot;:4,&quot;size&quot;:&quot;47&quot;,&quot;quantity&quot;:8,&quot;name&quot;:&quot;Simple Regular Shirt&quot;,&quot;price&quot;:123,&quot;thumbnail&quot;:&quot;Thumbnail_91520734.jpg&quot;} ] [1] =&gt; [ {&quot;id&quot;:9,&quot;product_id&quot;:3,&quot;size&quot;:&quot;45&quot;,&quot;quantity&quot;:2,&quot;name&quot;:&quot;Simple Regular T-shirt&quot;,&quot;price&quot;:2200,&quot;thumbnail&quot;:&quot;Thumbnail_614291597.jpg&quot;} ] ) </code></pre> <p>But I want.</p> <pre><code>Array ( [0] =&gt; [ {&quot;id&quot;:3,&quot;product_id&quot;:3,&quot;size&quot;:&quot;47&quot;,&quot;quantity&quot;:7,&quot;name&quot;:&quot;Simple Regular T-shirt&quot;,&quot;price&quot;:2200,&quot;thumbnail&quot;:&quot;Thumbnail_614291597.jpg&quot;}, {&quot;id&quot;:7,&quot;product_id&quot;:4,&quot;size&quot;:&quot;47&quot;,&quot;quantity&quot;:8,&quot;name&quot;:&quot;Simple Regular Shirt&quot;,&quot;price&quot;:123,&quot;thumbnail&quot;:&quot;Thumbnail_91520734.jpg&quot;}, {&quot;id&quot;:9,&quot;product_id&quot;:3,&quot;size&quot;:&quot;45&quot;,&quot;quantity&quot;:2,&quot;name&quot;:&quot;Simple Regular T-shirt&quot;,&quot;price&quot;:2200,&quot;thumbnail&quot;:&quot;Thumbnail_614291597.jpg&quot;} ] ) </code></pre> <p>How I can do this?</p> <p>I already tried a different way, but I can't do this. Firstly I was trying to convert it array and then use the array_marge() function for those arrays. but that array needs only two arrays but for my case, it is not specified how many arrays the user has given. And try to solve it with a loop (I just tried). I am new in this field.</p>
3
1,070
Why data is not being added to database? Entity Framework, Blazor wasm
<p>I have 3 tables in my database: <code>Ingredient</code>, <code>IngredientRecipe</code> and <code>Recipe</code>. Adding data to <code>Ingredient</code> works correctly. <code>IngredientRecipe</code> is for making relation between <code>Ingredient</code> and <code>Recipe</code>. When I want to add a <code>Recipe</code> to database, nothing happens. No errors, no data in the database.</p> <p>My error message:</p> <pre><code>System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. </code></pre> <p><code>DbContext</code> class:</p> <pre><code>public class AppDbContext : DbContext { public AppDbContext(DbContextOptions options) : base(options) { } public DbSet&lt;Ingredient&gt; IngredientsTable { get; set; } public DbSet&lt;IngredientRecipe&gt; IngredientRecipesTable { get; set; } public DbSet&lt;Recipe&gt; RecipesTable { get; set; } } </code></pre> <p>Ingredient, IngredientRecipe and Recipe:</p> <pre><code>public class Ingredient : BaseEntity { public string Name { get; set; } public int Kcal { get; set; } public virtual ICollection&lt;IngredientRecipe&gt; IngredientRecipe { get; set; } } public class IngredientRecipe : BaseEntity { public int IngredientId { get; set; } public int RecipeId { get; set; } public int Amount { get; set; } public Ingredient Ingredient { get; set; } public Recipe Recipe { get; set; } } public class Recipe : BaseEntity { public string Name { get; set; } public List&lt;IngredientRecipe&gt; ListOfIngredients { get; set; } } </code></pre> <p>And here is my form code:</p> <pre><code>@page &quot;/recipes/create&quot; @inject IIngredientRepository ingredientRepository @inject IRecipeRepository recipeRepository @inject NavigationManager navManager &lt;div class=&quot;container col-12&quot;&gt; &lt;EditForm Model=&quot;Recipe&quot; OnValidSubmit=&quot;SaveRecipe&quot;&gt; &lt;button class=&quot;btn btn-primary&quot;&gt;Save recipe&lt;/button&gt; &lt;div class=&quot;col-4&quot;&gt; &lt;div class=&quot;form-control&quot;&gt; &lt;InputText @bind-Value=&quot;Recipe.Name&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/EditForm&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-6&quot;&gt; &lt;TableTemplate Items=&quot;ListOfIngredients&quot;&gt; &lt;TableHeader&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Kcal&lt;/th&gt; &lt;th&gt;Action&lt;/th&gt; &lt;/TableHeader&gt; &lt;RowTemplate Context=&quot;ingredient&quot;&gt; &lt;td&gt;@ingredient.Name&lt;/td&gt; &lt;td&gt;@ingredient.Kcal&lt;/td&gt; &lt;td&gt; &lt;button class=&quot;btn btn-primary&quot; @onclick=&quot;@(()=&gt;SetTheAmount(ingredient))&quot;&gt;Add&lt;/button&gt; &lt;/td&gt; &lt;/RowTemplate&gt; &lt;/TableTemplate&gt; &lt;/div&gt; &lt;div class=&quot;col-6&quot;&gt; List of ingredients &lt;br /&gt; @if (ListOfIngredientAmounts.Any()) { &lt;TableTemplate Items=&quot;ListOfIngredientAmounts&quot;&gt; &lt;TableHeader&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Amount&lt;/th&gt; &lt;th&gt;Action&lt;/th&gt; &lt;/TableHeader&gt; &lt;RowTemplate Context=&quot;ingredient&quot;&gt; &lt;td&gt;@ingredient.Ingredient.Name&lt;/td&gt; &lt;td&gt;@ingredient.Amount&lt;/td&gt; &lt;td&gt; &lt;button class=&quot;btn btn-primary&quot;&gt;Delete&lt;/button&gt; &lt;/td&gt; &lt;/RowTemplate&gt; &lt;/TableTemplate&gt; } &lt;/div&gt; &lt;/div&gt; @if (IngredientAmount.Ingredient != null) { &lt;p&gt;Ingredient Id: @IngredientAmount.IngredientId | Name: @IngredientAmount.Ingredient.Name | Amount: @IngredientAmount.Amount&lt;/p&gt; &lt;EditForm Model=&quot;IngredientAmount&quot; OnValidSubmit=&quot;AddIngredientToIngredientAmountList&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; Value &lt;InputNumber @bind-Value=&quot;IngredientAmount.Amount&quot; /&gt; &lt;/div&gt; &lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot;&gt;Add to list&lt;/button&gt; &lt;/EditForm&gt; } @code{ public Recipe Recipe { get; set; } = new Recipe(); public List&lt;Ingredient&gt; ListOfIngredients { get; set; } = new List&lt;Ingredient&gt;(); public IngredientRecipe IngredientAmount { get; set; } = new IngredientRecipe(); public List&lt;IngredientRecipe&gt; ListOfIngredientAmounts { get; set; } = new List&lt;IngredientRecipe&gt;(); protected override async Task OnInitializedAsync() { ListOfIngredients = await ingredientRepository.GetListOfIngredients(); } private void SetTheAmount(Ingredient ingredient) { IngredientAmount = new IngredientRecipe(); IngredientAmount.IngredientId = ingredient.Id; IngredientAmount.Recipe = Recipe; IngredientAmount.RecipeId = Recipe.Id; IngredientAmount.Ingredient = ingredient; } private void AddIngredientToIngredientAmountList() { ListOfIngredientAmounts.Add(IngredientAmount); IngredientAmount = new IngredientRecipe(); } private async void SaveRecipe() { if (ListOfIngredientAmounts.Any()) { Recipe.ListOfIngredients = ListOfIngredientAmounts; await recipeRepository.CreateRecipe(Recipe); ListOfIngredientAmounts = new List&lt;IngredientRecipe&gt;(); Recipe = new Recipe(); navManager.NavigateTo(&quot;/recipes&quot;); } } } </code></pre> <p>And my repository and controller responsible for post:</p> <pre><code>public async Task CreateRecipe(Recipe recipe) { var response = await httpClient.PostAsJsonAsync(url, recipe); if (!response.IsSuccessStatusCode) { throw new ApplicationException(await response.Content.ReadAsStringAsync()); } } [HttpPost] public async Task&lt;ActionResult&lt;int&gt;&gt; Post(Recipe recipe) { context.RecipesTable.Add(recipe); await context.SaveChangesAsync(); return recipe.Id; } </code></pre> <p>And here is link to GitHub <a href="https://github.com/szymonJag/CookBook" rel="nofollow noreferrer">https://github.com/szymonJag/CookBook</a></p>
3
3,099
AWS CloudFormation Create-Stack Service Resource Hanging at 'CREATE_IN_PROGRESS'
<p>I have the below cloudformation script that is running fine with my create-stack command other than the service resource hanging at 'CREATE_IN_PROGRESS.' Hoping you all can see some kind of glaring issue that I'm missing. </p> <p>I'm not seeing any way to dig deeper into details on where it's at in the process other than the 'Events' page which just shows this hung status line, but happy to provide more info if I'm able.</p> <pre class="lang-yaml prettyprint-override"><code>AWSTemplateFormatVersion: '2010-09-09' Description: container on ecs cluster Resources: # Defines container. This is a simple metadata description of what # container to run, and what resource requirements it has. Task: Type: AWS::ECS::TaskDefinition Properties: Family: apis Cpu: 256 Memory: 512 NetworkMode: awsvpc RequiresCompatibilities: - FARGATE ExecutionRoleArn: 'iamRoleHere' ContainerDefinitions: - Name: booksapi # this is the image name from our repo that we made early on: aws ecr describe-repositories Image: 'imageHere' Cpu: 256 Memory: 512 PortMappings: - ContainerPort: 50577 Protocol: tcp # The service. The service is a resource which allows you to run multiple # copies of a type of task, and gather up their logs and metrics, as well # as monitor the number of running tasks and replace any that have crashed. # defines how the task or container will be scheduled and deployed in the cluster and how the container instances will be registered with load balancer Service: Type: AWS::ECS::Service DependsOn: ListenerRule Properties: #if using param for servicename: !Ref 'ServiceName' ServiceName: booksapi TaskDefinition: !Ref 'Task' Cluster: !ImportValue 'ECSCluster' LaunchType: FARGATE DesiredCount: 2 DeploymentConfiguration: MaximumPercent: 200 MinimumHealthyPercent: 70 NetworkConfiguration: AwsvpcConfiguration: AssignPublicIp: ENABLED Subnets: - 'subnet-abctyui' - 'subnet-poyfdha' SecurityGroups: - !ImportValue ContainerSecurityGroup LoadBalancers: - ContainerName: booksapi ContainerPort: 50577 TargetGroupArn: !Ref TargetGroup # A target group. This is used for keeping track of all the tasks, and # what IP addresses / port numbers they have. You can query it yourself, # to use the addresses yourself, but most often this target group is just # connected to an application load balancer, or network load balancer, so # it can automatically distribute traffic across all the targets. # add 443 after POC. remove health check for now as it is buggy at the moment in our template TargetGroup: Type: AWS::ElasticLoadBalancingV2::TargetGroup Properties: Name: books-tg VpcId: 'vpc-ljhdfrr' Port: 80 Protocol: HTTP Matcher: HttpCode: 200-299 HealthCheckIntervalSeconds: 10 HealthCheckPath: /stat HealthCheckProtocol: HTTP HealthCheckTimeoutSeconds: 5 HealthyThresholdCount: 10 TargetType: ip ListenerRule: Type: AWS::ElasticLoadBalancingV2::ListenerRule Properties: ListenerArn: !ImportValue Listener Priority: 2 Conditions: - Field: path-pattern Values: - /v1/books* Actions: - TargetGroupArn: !Ref TargetGroup Type: forward Outputs: ApiEndpoint: Description: Tests API Endpoint Value: !Join ['', ['http://', !ImportValue DomainName, '/v1/books']] Export: Name: 'BooksApiEndpoint' </code></pre>
3
1,391
SQLite query failing but only when offline
<p>I have a simple SQLite method which returns a class given two parameters - the type T and the parameter value to be searched</p> <pre><code>public T GetSingleObject&lt;T&gt;(string id) where T:IIdentity, new() { lock (dbLock) { using (var sqlCon = new SQLiteConnection(DBPath)) { sqlCon.Execute(Constants.DBClauseSyncOff); sqlCon.BeginTransaction(); string sql = string.Format("SELECT * FROM {0} WHERE id=\"{1}\"", GetName(typeof(T).ToString()), id); var data = sqlCon.Query&lt;T&gt;(sql); return data[0]; } } } </code></pre> <p>I also have another method that takes 3 parameters, T, the parameter to be seated and the value to search for</p> <pre><code>public T GetSingleObject&lt;T&gt;(string para, string val) where T:IIdentity, new() { lock (dbLock) { using (var sqlCon = new SQLiteConnection(DBPath)) { sqlCon.Execute(Constants.DBClauseSyncOff); sqlCon.BeginTransaction(); string sql = string.Format("SELECT * FROM {0} WHERE {1}=\"{2}\"", GetName(typeof(T).ToString()), para, val); var data = sqlCon.Query&lt;T&gt;(sql).FirstOrDefault(); return data; } } } </code></pre> <p>These methods work without an issue and return the values expected, but with one caveat - there is a single table which works fine when the phone has a connection, but not when it's in aeroplane mode. The table has nothing more in it than strings, doubles, ints, DateTime and bool values. </p> <p>GetName is a simple method that removes the assembly bits and pieces and leave just the classname</p> <pre><code> private string GetName(string name) { var list = name.Split('.').ToList(); if (list.Count == 1) return list[0]; var last = list[list.Count - 1]; return last; } </code></pre> <p>I have tried every way I can think of to access this table - including a straight</p> <pre><code>sqlCon.ExecuteScalar&lt;MyClass&gt;("SELECT * FROM MyClass"); </code></pre> <p>and nothing offline, perfect data online.</p> <p>The class itself looks like this</p> <pre><code>using System; using System.Runtime.Serialization; using System.Collections.Generic; using SQLite; namespace Models { public class MyClass : IIdentity { [PrimaryKey] public string id { get; set; } public string home_id { get; set; } public string username { get; set; } public string password { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string email { get; set; } public bool syncenabled { get; set; } public string tradingname { get; set; } public string address { get; set; } public string town { get; set; } public string state { get; set; } public string country { get; set; } public string securitystamp { get; set; } public string password_question { get; set; } public string password_answer { get; set; } public string mobileServiceAuthenticationToken { get; set; } public string providerUserKey { get; set; } public string mobiledeviceid { get; set; } public DateTime last_login { get; set; } public DateTime __createdAt { get; set; } public DateTime __updatedAt { get; set; } public string user_type { get; set; } public bool is_deleted { get; set; } public bool account_enabled { get; set; } public string subscription_id { get; set; } [IgnoreDataMember, Ignore] public List&lt;MyUsers&gt; UserModules { get { return AppDelegate.Self.DBManager.GetListOfObjects&lt;MyUsers&gt;("user_id", id); } } public override string ToString() { return string.Format("[MyClasss: id={0}, home_id={1}, username={2}, password={3}, firstname={4}, lastname={5}, email={6}, syncenabled={7}, tradingname={8}, address={9}, town={10}, state={11}, country={12}, securitystamp={13}, password_question={14}, password_answer={15}, mobileServiceAuthenticationToken={16}, providerUserKey={17}, mobiledeviceid={18}, last_login={19}, __createdAt={20}, __updatedAt={21}, user_type={22}, is_deleted={23}, account_enabled={24}, subscription_id={25}, UserModules={26}]", id, home_id, username, password, firstname, lastname, email, syncenabled, tradingname, address, town, state, country, securitystamp, password_question, password_answer, mobileServiceAuthenticationToken, providerUserKey, mobiledeviceid, last_login, __createdAt, __updatedAt, user_type, is_deleted, account_enabled, subscription_id, UserModules); } } </code></pre> <p>Nothing in there that I can see should cause an issue when offline. The query always returns null offline, data online.</p>
3
1,781
$resource on DELETE does not serialize data in json
<p>When using $resource with POST method (the item i want to delete on the server is of type "Todo") My java SpringREST back controller looks like :</p> <pre><code>/** * POST : delete an todo : /todos/DEL */ @RequestMapping(value = "/DEL", method = RequestMethod.POST) public void deletePOST(@RequestBody Todo todo) { todoRepository.delete(todo); } </code></pre> <p>Angular code :</p> <pre><code> vm.deleteTodoRes2 = function deleteTodoRes2(todo) { console.log(todo); var url = REST_SERVER_URL + "/todos/DEL"; var urlParamDefaults = {}; var action = { removeResource: { method: 'POST', headers: { 'Content-Type': 'application/json' }, isArray: false, transformRequest : function(data, headers) { console.log("data"); console.log(data); var out = angular.toJson(data); console.log("out "); console.log(out); return out; } } }; var rest = $resource(url, urlParamDefaults, action); // API : rest.&lt;method&gt; ( [param], // if NON GET [entityData], // [success(value, responseHeaders)], [error(httpResponse)] ) var param = {}; rest.removeResource(param, todo, successCallback, errorCallback); }; </code></pre> <p>It works perfectlt with POST, Now if i try changing the http method from POST to DELETE, it does not work anymore.</p> <p>Spring :</p> <pre><code> @RequestMapping(value = "/DEL", method = RequestMethod.DELETE) &lt;&lt;&lt; only change in JAVA In JS var action = { removeResource: { method: 'DELETE ', &lt;&lt;&lt; only change in JS </code></pre> <p>It does NOT WORK , the console.log(data); => undefined It seems the Angular does NOT want to take my "toto" data and serialize it in json, why ?</p>
3
1,167
Disabled button not being styled correctly
<p>I am trying to style a button that is disabled, but the styling doesn't take effect, and go back to the old styling. I have cleared my cache, to no avail. I have a button that gets disabled using JavaScript with <code>document.getElementById(&quot;updateAccountButton&quot;).disabled = true;</code>. This aforementioned button also has the class of <code>btn-signature-green</code>. Inside my stylesheet, I am trying to set the styling of this button when disabled using:</p> <pre><code>.btn-signature-blue:disabled, .btn-signature-green:disabled, .btn-signature-red:disabled { /* styles go here */ } </code></pre> <p>This is because I have other buttons that may have disabled attributes that I want to account for.</p> <p>Code snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(window).on("load", function() { document.getElementById("updateAccountButton").disabled = true; });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* disabled button */ .btn-signature-blue:disabled, .btn-signature-green:disabled, .btn-signature-red:disabled { background-color: #afafaf; color: white; } .btn-signature-green { -moz-box-shadow: 0px 6px 11px -7px #5fd623; -webkit-box-shadow: 0px 6px 11px -7px #5fd623; box-shadow: 0px 6px 11px -7px #5fd623; background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #67e827), color-stop(1, #81de52)); background: -moz-linear-gradient(top, #67e827 5%, #81de52 100%); background: -webkit-linear-gradient(top, #67e827 5%, #81de52 100%); background: -o-linear-gradient(top, #67e827 5%, #81de52 100%); background: -ms-linear-gradient(top, #67e827 5%, #81de52 100%); background: linear-gradient(to bottom, #67e827 5%, #81de52 100%); filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#67e827', endColorstr='#81de52', GradientType=0); -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; display: inline-block; border: 0px; cursor: pointer; color: #ffffff !important; font-family: Arial; font-size: 15px; font-weight: bold; padding: 5px 11px; text-decoration: none; } /* the green button when hovered over */ .btn-signature-green:hover { background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #81de52), color-stop(1, #67e827)); background: -moz-linear-gradient(top, #81de52 5%, #67e827 100%); background: -webkit-linear-gradient(top, #81de52 5%, #67e827 100%); background: -o-linear-gradient(top, #81de52 5%, #67e827 100%); background: -ms-linear-gradient(top, #81de52 5%, #67e827 100%); background: linear-gradient(to bottom, #81de52 5%, #67e827 100%); filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#81de52', endColorstr='#67e827', GradientType=0); background-color: #81de52; color: black !important; } /* the green button when clicked */ .btn-signature-green:active { position: relative; top: 1px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"&gt;&lt;/script&gt; &lt;button class="btn-signature-green" id="updateAccountButton"&gt;disabled button&lt;/button&gt;</code></pre> </div> </div> </p>
3
1,279
How can a attempt a call to rename and return the results even if there is an error?
<p>I would like to iterate over a list of data frames a rename function. Sometimes the DFs will be NULL.</p> <pre><code>lookup &lt;- list( 'miles_per_gallon' = 'mpg', 'cylinder' = 'cyl' ) df1 &lt;- mtcars df2 &lt;- NULL index_name &lt;- function(df, lookup) { i1 &lt;- unlist(lookup) %in% names(df) names_lookup_sub &lt;- lookup[i1] df %&gt;% rename(!!! lookup[i1]) } </code></pre> <p>Now putting the function to use:</p> <pre><code>df1 %&gt;% {try(index_name(.,lookup))} %&gt;% glimpse # works! Note the newly named features Rows: 32 Columns: 11 $ miles_per_gallon &lt;dbl&gt; 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17.8, 16.4, 17.3, 15.2, 10.4, 10.4, 14… $ cylinder &lt;dbl&gt; 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 8, 8, 8, 8, 4, 4, 4, 8, 6, 8, 4 $ disp &lt;dbl&gt; 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 140.8, 167.6, 167.6, 275.8, 275.8, 275.8, … $ hp &lt;dbl&gt; 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, 180, 180, 205, 215, 230, 66, 52, 65, 97, … $ drat &lt;dbl&gt; 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.92, 3.92, 3.07, 3.07, 3.07, 2.93, 3.00, 3.… $ wt &lt;dbl&gt; 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3.150, 3.440, 3.440, 4.070, 3.730, 3.780, … $ qsec &lt;dbl&gt; 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 22.90, 18.30, 18.90, 17.40, 17.60, 18.00, … $ vs &lt;dbl&gt; 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1 $ am &lt;dbl&gt; 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 $ gear &lt;dbl&gt; 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 4 $ carb &lt;dbl&gt; 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, 1, 1, 2, 2, 4, 2, 1, 2, 2, 4, 6, 8, 2 </code></pre> <p>But when trying with the NULL DF:</p> <pre><code>df2 %&gt;% {try(index_name(.,lookup))} %&gt;% glimpse # error in UseMethod(&quot;rename_&quot;) : no applicable method for 'rename_' applied to an object of class &quot;NULL&quot; </code></pre> <p>How can I apply my function across several dataframes and apply the function where the df exists and otherwise pass over it without throwing an error?</p>
3
1,304
Resolving A Django Error on Form: Object has no attribute
<p>Hi I'm trying to create a form that will when used update one model (Command_Node), and at the same time create an instance of another model (EC_NODE) that has a many to one relationship with the Command_Nodes.</p> <p>However when I go onto the update view and submit the form I'm getting the following error any ideas on how I can resolve this error?</p> <p>Thanks for any help you can offer.</p> <pre><code>AttributeError at /website/update/1 'Beacon' object has no attribute 'EC_Node_set' Request Method: POST Request URL: http://127.0.0.1:8000/website/update/1 Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'Beacon' object has no attribute 'EC_Node_set' </code></pre> <p>This on traceback points to</p> <pre><code> command_form.EC_Node_set.all() # &lt;- not sure with all _ and Maj here </code></pre> <p>Which I can understand. I think my intention here should be clear enough. I want to set an instance of EC_Node to hold the command just put in via the form, and I understand the error. I just don't know how to get around it so that the view/form does what I want.</p> <p><strong>Relevant views.py</strong></p> <pre><code>def update(request, host_id): host_id = Command_Node.objects.get(pk=host_id) form = Command_Form(request.POST or None, instance=host_id) if form.is_valid(): # Original suggestion was command_form = Command_Form.objects.first() command_form = form.cleaned_data['host_id'] command_form.EC_Node_set.all() # &lt;- not sure with all _ and Maj here form.save() return redirect('home') return render (request, 'update.html', {'host_id':host_id,'form':form}) </code></pre> <p><strong>Relevant models.py</strong></p> <pre><code>class Command_Node(models.Model): host_id = models.ForeignKey(Beacon, on_delete=models.CASCADE) current_commands = models.CharField(choices=CHOICES, max_length=50, null=True) def __str__(self): return str(self.host_id) class EC_Node(models.Model): Command_node = models.ForeignKey(Command_Node, on_delete=models.DO_NOTHING) command = models.CharField(choices=CHOICES, max_length=50, null=True) def __str__(self): return str(self.Command_node) </code></pre> <p><strong>Relevant forms.py</strong></p> <pre><code>class Command_Form(ModelForm): class Meta: model = Command_Node fields = ('host_id','current_commands') host_id = forms.ModelChoiceField( required=True, queryset=Beacon.objects.all(), widget=forms.SelectMultiple( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=CHOICES ) def save(self, **kwargs): EC_Node.objects.create( command=self.cleaned_data[&quot;current_commands&quot;], Command_node=self.instance ) return super().save(**kwargs) </code></pre>
3
1,219
Keep scroll visible but disable when nav menu open
<p>I have a nav menu working but the page is still scrollable when that becomes visible over the top of the rest of the content. Because the button is positioned so it's in the same place the page would jump about too much if the scroll bar was hidden. I want to disable the scrollbar on the body when the active class is active. I had tried using CSS <code>position: fixed; overflow-y:scroll</code> on body but this adds double scrolling and doesn't always revert.</p> <p>I'm hoping the JS can be modified to keep the scrollbar present but not scrollable while the nav is open I'm just not sure how to approach this in a workable way.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const navButtons = document.querySelectorAll('button.nav-action'); const siteNav = document.querySelector('.site-nav'); function onClick(event) { siteNav.classList.toggle('active'); } navButtons.forEach(button =&gt; button.addEventListener('click', onClick));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.site-header { height: 80px; background-color: #FFFFFF; display: inline-flex; position: fixed; top: 0; left: 0; right: 0; z-index: 1; box-shadow: 0px 0.5px 10px #000000; } .site-header-fill { height: 80px; } .site-logo-container { height: 60px; margin-left: 20px; margin-right: auto; margin-top: 10px; margin-bottom: 10px; display: block; float: left; } .site-logo { height: 60px; width: auto; float: left; } .site-nav-action-container { height: 50px; width: 50px; max-width: 50px; margin-left: 10px; margin-right: 10px; margin-top: 15px; margin-bottom: 15px; display: block; float: right; text-align: right; } .site-nav { height: 100%; left: 0px; position: fixed; top: 0px; width: 100%; background: #3399ff; z-index: 2; display: none; } .site-nav.active { display: block; } .site-nav-content { width: 20%; position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } @media only screen and (max-width: 500px) { .site-nav-content { width: auto; position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } } .site-nav-pages { text-align:center; } .nav-action { height: 50px; width: 50px; } .pagefill { display: block; with: 50%; height: 2000px; background-color: #000000; margin: auto; margin-top: 100px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="site-header "&gt; &lt;div class="site-logo-container"&gt; &lt;img class="site-logo" src="https://via.placeholder.com/1000x300" alt="Logo"&gt; &lt;/div&gt; &lt;div class="site-nav-action-container"&gt; &lt;button class="nav-action"&gt; &lt;p&gt;☰&lt;/p&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="site-nav"&gt; &lt;div class="site-nav-action-container"&gt; &lt;button class="nav-action"&gt; &lt;p&gt;×&lt;/p&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="site-nav-content"&gt; &lt;div class="site-nav-pages"&gt; &lt;p&gt;Page 1&lt;/p&gt; &lt;p&gt;Page 2&lt;/p&gt; &lt;p&gt;Page 3&lt;/p&gt; &lt;p&gt;Page 4&lt;/p&gt; &lt;p&gt;Page 5&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="pagefill"&gt;&lt;/div&gt; </code></pre> </div> </div> </p> <p><code>EDIT</code></p> <p>Adding this seems to do the trick but the issue is removing the active class when the nav is closed. The position and overflow-y elements also need to be in the main body class too but this is close.</p> <pre><code>body.active, html{ width: 100vw; position: fixed !important; overflow-y: scroll !important; } </code></pre>
3
1,716
Unable to use a `Symbol` for a `Group` with paper.js
<p>I want to do an animation of a reaction-diffusion system with <code>paper.js</code>. </p> <p>Here is a code which generates just one image:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.2/paper-full.min.js"&gt;&lt;/script&gt; &lt;style&gt; canvas { width: 400px; height: 400px; border: black 3px solid; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; function subm_index(M, x){ if (x&lt;0) return x+M; if(x &gt;= M) return x-M; return x; } function update_concentrations(X, L, DA, DB, f, k){ var sum_a, sum_b, x1, y1, t; var m = X.A.length; var n = X.A[0].length; var A = new Array(m); var B = new Array(m); for(var i = 0; i &lt; m; i++){ A[i] = new Array(n); B[i] = new Array(n); } for(var x = 0; x &lt; m; x++) { for(var y = 0; y &lt; n; y++){ sum_a = 0.0; sum_b = 0.0; for(var i = -1; i &lt;= 1; i++){ for(var j = -1; j &lt;= 1; j++){ x1 = subm_index(m, x - i); y1 = subm_index(n, y - j); sum_a = sum_a + L[i+1][j+1] * X.A[x1][y1]; sum_b = sum_b + L[i+1][j+1] * X.B[x1][y1]; } } t = X.A[x][y]*X.B[x][y]*X.B[x][y]; A[x][y] = X.A[x][y] + DA*sum_a - t + f*(1-X.A[x][y]); B[x][y] = X.B[x][y] + DB*sum_b + t - (k+f)*X.B[x][y]; } } return {A: A, B: B}; } function iterate_Gray_Scott(X, L, DA, DB, f, k, n){ for(var i = 0; i &lt; n; i++){ X = update_concentrations(X, L, DA, DB, f, k); } return X; } var L = [[0.05, 0.2, 0.05], [0.2, -1, 0.2], [0.05, 0.2, 0.05]]; var DA = 1; var DB = 0.5; var f = 0.0545; var k = 0.062; &lt;/script&gt; &lt;script type="text/paperscript" canvas="quad"&gt; var pixels = 200; var gridSize = 2; var rectSize = 2; var A = new Array(pixels); var B = new Array(pixels); for(var i = 0; i &lt; pixels; i++){ A[i] = new Array(pixels); B[i] = new Array(pixels); for(var j = 0; j &lt; pixels; j++){ A[i][j] = 1; B[i][j] = Math.random() &lt; 0.98 ? 0 : 1; } } var X = {A: A, B: B}; X = iterate_Gray_Scott(X, L, DA, DB, f, k, 1000); for(var y = 0; y &lt; pixels; y++){ for(var x = 0; x &lt; pixels; x++){ var color = { hue: X.B[x][y] * 360, saturation: 1, brightness: 1 }; var path = new Path.Rectangle(new Point(x, y) * gridSize, new Size(rectSize, rectSize)); path.fillColor = color; } } project.activeLayer.position = view.center; &lt;/script&gt; &lt;canvas id="quad" resize&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Now, here is a code which generates the animation:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.2/paper-full.min.js"&gt;&lt;/script&gt; &lt;style&gt; canvas { width: 400px; height: 400px; border: black 3px solid; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; function subm_index(M, x){ if (x&lt;0) return x+M; if(x &gt;= M) return x-M; return x; } function update_concentrations(X, L, DA, DB, f, k){ var sum_a, sum_b, x1, y1, t; var m = X.A.length; var n = X.A[0].length; var A = new Array(m); var B = new Array(m); for(var i = 0; i &lt; m; i++){ A[i] = new Array(n); B[i] = new Array(n); } for(var x = 0; x &lt; m; x++) { for(var y = 0; y &lt; n; y++){ sum_a = 0.0; sum_b = 0.0; for(var i = -1; i &lt;= 1; i++){ for(var j = -1; j &lt;= 1; j++){ x1 = subm_index(m, x - i); y1 = subm_index(n, y - j); sum_a = sum_a + L[i+1][j+1] * X.A[x1][y1]; sum_b = sum_b + L[i+1][j+1] * X.B[x1][y1]; } } t = X.A[x][y]*X.B[x][y]*X.B[x][y]; A[x][y] = X.A[x][y] + DA*sum_a - t + f*(1-X.A[x][y]); B[x][y] = X.B[x][y] + DB*sum_b + t - (k+f)*X.B[x][y]; } } return {A: A, B: B}; } function iterate_Gray_Scott(X, L, DA, DB, f, k, n){ for(var i = 0; i &lt; n; i++){ X = update_concentrations(X, L, DA, DB, f, k); } return X; } var L = [[0.05, 0.2, 0.05], [0.2, -1, 0.2], [0.05, 0.2, 0.05]]; var DA = 1; var DB = 0.5; var f = 0.0545; var k = 0.062; &lt;/script&gt; &lt;script type="text/paperscript" canvas="quad"&gt; var pixels = 200; var gridSize = 2; var rectSize = 2; var A = new Array(pixels); var B = new Array(pixels); var Paths = new Array(pixels); for(var i = 0; i &lt; pixels; i++){ A[i] = new Array(pixels); B[i] = new Array(pixels); Paths[i] = new Array(pixels); for(var j = 0; j &lt; pixels; j++){ A[i][j] = 1; B[i][j] = Math.random() &lt; 0.99 ? 0 : 1; } } var X = {A: A, B: B}; for(var y = 0; y &lt; pixels; y++){ for(var x = 0; x &lt; pixels; x++){ var color = { hue: X.B[x][y] * 360, saturation: 1, brightness: 1 }; Paths[x][y] = new Path.Rectangle(new Point(x, y) * gridSize, new Size(rectSize, rectSize)); Paths[x][y].fillColor = color; } } var nframes = 100; var XX = new Array(nframes); XX[0] = X; for(var frm = 1; frm &lt; nframes; frm++){ XX[frm] = iterate_Gray_Scott(XX[frm-1], L, DA, DB, f, k, frm); } project.activeLayer.position = view.center; function onFrame(event){ console.log(event.count); if(event.count &lt; nframes){ for(var y = 0; y &lt; pixels; y++){ for(var x = 0; x &lt; pixels; x++){ var color = { hue: XX[event.count].B[x][y] * 360, saturation: 1, brightness: 1 }; Paths[x][y].fillColor = color; } } } } &lt;/script&gt; &lt;canvas id="quad" resize&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>It works but the animation is not fluid enough. This is due to the double loop in <code>onFrame</code>, which consumes some time.</p> <p>So I firstly tried to create an array containing <code>nframes</code> <code>Group</code> elements, each group containing <code>pixels*pixels</code> <code>Rectangle</code> elements. But this generated an out-of-memory. </p> <p>So I tried to use a <code>Symbol</code> to save some memory. The code is below but it does not work, there is not a single image appearing.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.2/paper-full.min.js"&gt;&lt;/script&gt; &lt;style&gt; canvas { width: 400px; height: 400px; border: black 3px solid; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; function subm_index(M, x){ if (x&lt;0) return x+M; if(x &gt;= M) return x-M; return x; } function update_concentrations(X, L, DA, DB, f, k){ var sum_a, sum_b, x1, y1, t; var m = X.A.length; var n = X.A[0].length; var A = new Array(m); var B = new Array(m); for(var i = 0; i &lt; m; i++){ A[i] = new Array(n); B[i] = new Array(n); } for(var x = 0; x &lt; m; x++) { for(var y = 0; y &lt; n; y++){ sum_a = 0.0; sum_b = 0.0; for(var i = -1; i &lt;= 1; i++){ for(var j = -1; j &lt;= 1; j++){ x1 = subm_index(m, x - i); y1 = subm_index(n, y - j); sum_a = sum_a + L[i+1][j+1] * X.A[x1][y1]; sum_b = sum_b + L[i+1][j+1] * X.B[x1][y1]; } } t = X.A[x][y]*X.B[x][y]*X.B[x][y]; A[x][y] = X.A[x][y] + DA*sum_a - t + f*(1-X.A[x][y]); B[x][y] = X.B[x][y] + DB*sum_b + t - (k+f)*X.B[x][y]; } } return {A: A, B: B}; } function iterate_Gray_Scott(X, L, DA, DB, f, k, n){ for(var i = 0; i &lt; n; i++){ X = update_concentrations(X, L, DA, DB, f, k); } return X; } var L = [[0.05, 0.2, 0.05], [0.2, -1, 0.2], [0.05, 0.2, 0.05]]; var DA = 1; var DB = 0.5; var f = 0.0545; var k = 0.062; &lt;/script&gt; &lt;script type="text/paperscript" canvas="quad"&gt; var pixels = 50; var gridSize = 2; var rectSize = 2; var A = new Array(pixels); var B = new Array(pixels); var Paths = new Array(pixels); for(var i = 0; i &lt; pixels; i++){ A[i] = new Array(pixels); B[i] = new Array(pixels); Paths[i] = new Array(pixels); for(var j = 0; j &lt; pixels; j++){ A[i][j] = 1; B[i][j] = Math.random() &lt; 0.99 ? 0 : 1; } } var X = {A: A, B: B}; var nframes = 50; var XX = new Array(nframes); XX[0] = X; for(var frm = 1; frm &lt; nframes; frm++){ XX[frm] = iterate_Gray_Scott(XX[frm-1], L, DA, DB, f, k, frm); } var Rects = []; for(var x = 0; x &lt; pixels; x++){ for(var y = 0; y &lt; pixels; y++){ var rect = new Path.Rectangle(new Point(x, y) * gridSize, new Size(rectSize, rectSize)); var color = { hue: 1, saturation: 1, brightness: 1 }; rect.fillColor = color; rect.visible = false; Rects.push(rect); } } group = new Group(Rects); symbolGroup = new Symbol(group); var Groups = new Array(nframes); for(var frm = 0; frm &lt; nframes; frm++){ Groups[frm] = symbolGroup.place(view.center); var k = 0; for(var x = 0; x &lt; pixels; x++){ for(var y = 0; y &lt; pixels; y++){ Groups[frm].definition.definition.children[k].fillColor = { hue: XX[frm].B[x][y] * 360, saturation: 1, brightness: 1 }; k = k+1; } } XX[frm] = null; // to free some memory } project.activeLayer.position = view.center; function onFrame(event){ if(event.count &lt; nframes){ console.log(event.count); Groups[event.count].visible = true; if(event.count &gt; 0){ Groups[event.count-1].visible = false; // to free some memory } } } &lt;/script&gt; &lt;canvas id="quad" resize&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Can you help me to fix this last code?</p>
3
6,864
Insert Month into data
<p>I have a large section of code that I declare an insert date of at the beginning:</p> <pre><code>DECLARE @lcid INT DECLARE @startdate DATETIME=@10 DECLARE @enddate DATETIME=@11 DECLARE @PitchJobTypeId INT DECLARE @ClientInvestmentJobTypeId INT DECLARE @AdministrationJobTypeId INT IF OBJECT_ID('tempdb..#data') IS NOT NULL DROP TABLE #data DECLARE @Billablejob TABLE( id INT IDENTITY(1,1), Jobid INT) DECLARE @Department table( Id INT IDENTITY(1,1), DepartmentId INT) IF @10 &gt; @11 BEGIN SELECT 'Error in date selection' AS 'Error'; GOTO ExitSp; END INSERT INTO @Billablejob(Jobid) SELECT distinct s.Element FROM dbo.Split(@30,',') AS s Insert into @Department(DepartmentId) SELECT distinct s.Element FROM dbo.Split(@5,',') AS s IF EXISTS(SELECT '' FROM @Department AS d WHERE d.DepartmentId=0) OR NOT EXISTS(SELECT '' FROM @Department AS d) BEGIN DELETE FROM @Department INSERT INTO @Department(DepartmentId) SELECT rsa.AfdID FROM RessSelAfd AS rsa --INNER JOIN @comp c ON c.compid=rsa.SelID END IF @20 IS NULL SET @20=0 CREATE TABLE #data( ID INT IDENTITY(1,1), [Name] nvarchar(MAX), [Employee Type] nvarchar(MAX), [Basic Time] money, [Used Time] MONEY, [Holiday] MONEY, [Recovery] MONEY, [Illness] MONEY, [Billable Time] MONEY, [Non Billable Time] MONEY, [Pitch Time] MONEY, [Internal Time] MONEY, [Used Time2] MONEY, [Max Billable Hours] MONEY, [Available Hours] MONEY, [Office Hours %] INT, [Billable %] INT, [Non Billable %] INT, [Pitch %] INT, [Internal %] INT, [Billable Target %] INT, [Variance to Target %] INT, [Department] NVARCHAR(max), [Job Role] NVARCHAR(max), [Market] NVARCHAR(max), EmpId INT, DepartmentId INT, JobRoleId INT, MarketId INT, IsActive BIT, Hiredate DATETIME, Expirydate DATETIME, EmployeeType INT ) IF @10&gt;@11 BEGIN SELECT 'Date selection error' Error GOTO ExitSp END SELECT @PitchJobTypeId = sj.JobTypeID FROM SysJobtype AS sj WHERE sj.JobtypeNavn='Pitch' IF @PitchJobTypeId IS NULL BEGIN SELECT 'Jobtype ''Pitch'' not found' Error GOTO ExitSp END SELECT @ClientInvestmentJobTypeId = sj.JobTypeID FROM SysJobtype AS sj WHERE sj.JobtypeNavn='Client Investment' IF @ClientInvestmentJobTypeId IS NULL BEGIN SELECT 'Jobtype ''Client Investment'' not found' Error GOTO ExitSp END SELECT @AdministrationJobTypeId = sj.JobTypeID FROM SysJobtype AS sj WHERE sj.JobtypeNavn='Administration' IF @AdministrationJobTypeId IS NULL BEGIN SELECT 'Jobtype ''Administration'' not found' Error GOTO ExitSp END SELECT @lcid=InterfaceLcid FROM ress WHERE ressid=@UserId INSERT INTO #data( empid,[Name],[Billable Target %],[JobRoleId],[Job Role],DepartmentId,MarketId,IsActive,Hiredate,Expirydate,EmployeeType,[Employee Type]) SELECT emp.empid,EmpName,(SELECT TOP 1 ehp.ProfitTarget*100 FROM EmpHrsPrice AS ehp WHERE ehp.EmpId = emp.empid AND ehp.ValidFrom &lt;= @enddate ORDER BY ehp.ValidFrom desc),emppost.PostId, (SELECT ISNULL(nullif(ActLang.ActTxt,''), Act.ActTxt) FROM Act LEFT JOIN ActLang ON Act.AID = ActLang.Aid AND ActLang.LCID=@LCID WHERE Act.AID=emp.aid),emp.DepartmentId,emp.CompId,emp.IsActive,emp.Hiredate,emp.Expirydate,emp.EmployTypeId,CASE WHEN et.enumval=1 OR et.enumval=2 THEN 'Permanent' ELSE 'Freelance' END FROM emp INNER JOIN ress ON ress.RessID=emp.EmpId INNER JOIN @Department AS d ON d.DepartmentId = Emp.DepartmentId LEFT JOIN emppost ON emp.PostId=emppost.PostId LEFT JOIN EnumTable(467) AS et ON et.EnumVal=emp.EmployTypeId WHERE (IsActive=1 OR (Expirydate&gt;=@startdate and Expirydate&lt;=@enddate)) AND (CASE WHEN emp.EmployTypeId=2 THEN 1 ELSE emp.EmployTypeId END=@20 OR @20=0) AND Ress.UserAcountType&lt;&gt;5 UPDATE d SET d.Department=rsa.AfdNavn FROM #data d INNER JOIN RessSelAfd AS rsa ON d.DepartmentId=rsa.AfdID UPDATE d SET d.Market=comp.CompName FROM #data d INNER JOIN comp ON d.MarketId=comp.compid UPDATE d SET d.[Basic Time]=data.HrsNorm FROM #data d INNER JOIN (SELECT cap.ResId,Sum(ISNULL(Cap.HrsNorm,0)+ISNULL(Cap.HrsHoli,0)) AS HrsNorm FROM cap INNER JOIN #data d ON d.empid=cap.ResId AND CAST(DayDate AS DATE) BETWEEN @startdate AND @enddate GROUP BY cap.ResId) data ON d.EmpId=data.ResId UPDATE d SET d.[Used Time]=data.UsedHours FROM #data d INNER JOIN (SELECT tr.EmpId,SUM(tr.RegHrs) AS UsedHours FROM TimeReg AS tr WHERE CAST(RegDate AS DATE) BETWEEN @startdate AND @enddate and reghrs IS NOT null GROUP BY tr.EmpId ) data ON d.EmpId=data.EmpId UPDATE d SET [Basic Time]=[Used Time],d.[Billable Target %]=100 FROM #data d WHERE EmployeeType=3 UPDATE d SET [Basic Time]=ISNULL([Basic Time],0),[Used Time]=ISNULL([Used Time],0) FROM #data d UPDATE d SET d.Holiday = data.UsedHours FROM #data d INNER JOIN ( SELECT tr.EmpId,SUM(tr.RegHrs) AS UsedHours FROM TimeReg AS tr INNER JOIN RessFerie AS rf ON rf.RecId=tr.EmpHoliRecId INNER JOIN AbsenceCode AS ac ON ac.Id=rf.AbsenceID INNER JOIN job ON Job.JobID = tr.JobId INNER JOIN RessProjekter AS rp ON rp.ProjektID = Job.ProjektID INNER JOIN CUST ON cust.CustId=rp.RessID WHERE CAST(RegDate AS DATE) BETWEEN @startdate AND @enddate AND RegHrs IS NOT NULL AND cust.CustTypeId=5 AND job.JobTypeID&lt;&gt;@PitchJobTypeId AND ac.Descr&lt;&gt;'Recovery Day' GROUP BY tr.EmpId ) data ON d.EmpId = data.EmpId; UPDATE d SET d.Recovery = data.UsedHours FROM #data d INNER JOIN ( SELECT tr.EmpId,SUM(tr.RegHrs) AS UsedHours FROM TimeReg AS tr INNER JOIN RessFerie AS rf ON rf.RecId=tr.EmpHoliRecId INNER JOIN AbsenceCode AS ac ON ac.Id=rf.AbsenceID INNER JOIN job ON Job.JobID = tr.JobId INNER JOIN RessProjekter AS rp ON rp.ProjektID = Job.ProjektID INNER JOIN CUST ON cust.CustId=rp.RessID WHERE CAST(RegDate AS DATE) BETWEEN @startdate AND @enddate AND RegHrs IS NOT NULL AND cust.CustTypeId=5 AND job.JobTypeID&lt;&gt;@PitchJobTypeId AND ac.Descr='Recovery Day' GROUP BY tr.EmpId ) data ON d.EmpId = data.EmpId; UPDATE d SET d.Illness = data.UsedHours FROM #data d INNER JOIN ( SELECT tr.EmpId,SUM(tr.RegHrs) AS UsedHours FROM TimeReg AS tr INNER JOIN job ON Job.JobID = tr.JobId INNER JOIN RessProjekter AS rp ON rp.ProjektID = Job.ProjektID INNER JOIN CUST ON cust.CustId=rp.RessID WHERE CAST(RegDate AS DATE) BETWEEN @startdate AND @enddate AND RegHrs IS NOT NULL AND cust.CustTypeId=6 AND job.JobTypeID&lt;&gt;@PitchJobTypeId GROUP BY tr.EmpId ) data ON d.EmpId = data.EmpId; UPDATE d SET d.[Billable Time] = data.UsedHours FROM #data d INNER JOIN ( SELECT tr.EmpId,SUM(tr.RegHrs) AS UsedHours FROM TimeReg AS tr INNER JOIN job ON Job.JobID = tr.JobId INNER JOIN RessProjekter AS rp ON rp.ProjektID = Job.ProjektID INNER JOIN CUST ON cust.CustId=rp.RessID LEFT JOIN @Billablejob AS bj ON job.JobID=bj.Jobid WHERE CAST(RegDate AS DATE) BETWEEN @startdate AND @enddate AND RegHrs IS NOT NULL AND (job.DebitFlg=1 OR bj.Jobid IS NOT NULL) AND (cust.CustTypeId=1 OR cust.CustTypeId=2) AND job.JobTypeID&lt;&gt;@PitchJobTypeId AND job.JobTypeID&lt;&gt;@ClientInvestmentJobTypeId AND job.JobTypeID&lt;&gt;@AdministrationJobTypeId GROUP BY tr.EmpId ) data ON d.EmpId = data.EmpId; UPDATE d SET d.[Non Billable Time] = data.UsedHours FROM #data d INNER JOIN ( SELECT tr.EmpId,SUM(tr.RegHrs) AS UsedHours FROM TimeReg AS tr INNER JOIN job ON Job.JobID = tr.JobId INNER JOIN RessProjekter AS rp ON rp.ProjektID = Job.ProjektID INNER JOIN CUST ON cust.CustId=rp.RessID LEFT JOIN @Billablejob AS bj ON job.JobID=bj.Jobid WHERE CAST(RegDate AS DATE) BETWEEN @startdate AND @enddate AND RegHrs IS NOT NULL AND ((bj.Jobid IS NULL and job.DebitFlg=0 AND (cust.CustTypeId=1 OR cust.CustTypeId=2) AND job.JobTypeID&lt;&gt;@PitchJobTypeId AND job.JobTypeID&lt;&gt;@AdministrationJobTypeId) OR job.JobTypeID=@ClientInvestmentJobTypeId) GROUP BY tr.EmpId ) data ON d.EmpId = data.EmpId; UPDATE d SET d.[Pitch Time] = data.UsedHours FROM #data d INNER JOIN ( SELECT tr.EmpId,SUM(tr.RegHrs) AS UsedHours FROM TimeReg AS tr INNER JOIN job ON Job.JobID = tr.JobId INNER JOIN RessProjekter AS rp ON rp.ProjektID = Job.ProjektID INNER JOIN CUST ON cust.CustId=rp.RessID WHERE CAST(RegDate AS DATE) BETWEEN @startdate AND @enddate AND RegHrs IS NOT NULL AND tr.EmpHoliRecId IS NULL AND job.JobTypeID=@PitchJobTypeId GROUP BY tr.EmpId ) data ON d.EmpId = data.EmpId; UPDATE d SET d.[Internal Time] = data.UsedHours FROM #data d INNER JOIN ( SELECT tr.EmpId,SUM(tr.RegHrs) AS UsedHours FROM TimeReg AS tr INNER JOIN job ON Job.JobID = tr.JobId INNER JOIN RessProjekter AS rp ON rp.ProjektID = Job.ProjektID INNER JOIN CUST ON cust.CustId=rp.RessID WHERE CAST(RegDate AS DATE) BETWEEN @startdate AND @enddate AND RegHrs IS NOT NULL AND tr.EmpHoliRecId IS NULL AND (((cust.CustTypeId=3 OR cust.CustTypeId=4) AND job.JobTypeID&lt;&gt;@PitchJobTypeId AND job.JobTypeID&lt;&gt;@ClientInvestmentJobTypeId) OR job.JobTypeID=@AdministrationJobTypeId) GROUP BY tr.EmpId ) data ON d.EmpId = data.EmpId; UPDATE d SET d.[Used Time2]=isnull(d.[Used Time],0)-isnull(d.Recovery,0) FROM #data d UPDATE d SET d.[Max Billable Hours]=ISNULL(d.[Used Time2],0)-ISNULL(d.Holiday,0)-ISNULL(d.Illness,0) FROM #data d UPDATE d SET d.[Available Hours]=ISNULL(d.[Basic Time],0)-ISNULL(d.Holiday,0)-ISNULL(d.Illness,0) FROM #data d UPDATE d SET d.[Office Hours %]=CAST(CASE WHEN ISNULL(d.[Available Hours],0)=0 THEN 0 ELSE d.[Max Billable Hours]/d.[Available Hours]*100 END AS INT) FROM #data d UPDATE d SET d.[Billable %]=CAST(CASE WHEN ISNULL(d.[Available Hours],0)=0 THEN CASE WHEN ISNULL(d.[Billable Time],0)=0 THEN 100 ELSE 0 END ELSE d.[Billable Time]/d.[Available Hours]*100 END AS INT) FROM #data d UPDATE d SET d.[Non Billable %]=CAST(CASE WHEN ISNULL(d.[Available Hours],0)=0 THEN 0 ELSE d.[Non Billable Time]/d.[Available Hours]*100 END AS INT) FROM #data d UPDATE d SET d.[Pitch %]=CAST(CASE WHEN ISNULL(d.[Available Hours],0)=0 THEN 0 ELSE d.[Pitch Time]/d.[Available Hours]*100 END AS INT) FROM #data d UPDATE d SET d.[Internal %]=CAST(CASE WHEN ISNULL(d.[Available Hours],0)=0 THEN 0 ELSE d.[Internal Time]/d.[Available Hours]*100 END AS INT) FROM #data d UPDATE d SET d.[Variance to Target %]=ISNULL(d.[Billable %],0)-ISNULL(d.[Billable Target %],0) FROM #data d SELECT d.Name, d.[Employee Type], d.[Basic Time], d.[Used Time] AS [Total Time posted], isnull(d.Holiday,0)+isnull(d.Illness,0) [Absence], d.Recovery, d.[Billable Time], d.[Non Billable Time], d.[Pitch Time], d.[Internal Time], isnull(d.[Used Time2],0) AS [Used Time], d.[Max Billable Hours], d.[Available Hours], CAST(d.[Office Hours %] AS NVARCHAR(50))+'%' AS [Office Hours %], CAST(d.[Billable %] AS NVARCHAR(50))+'%' AS [Billable %], CAST(d.[Non Billable %] AS NVARCHAR(50))+'%' AS [Non Billable %], CAST(d.[Pitch %] AS NVARCHAR(50))+'%' AS [Pitch %], CAST(d.[Internal %] AS NVARCHAR(50))+'%' AS [Internal %], CAST(d.[Billable Target %] AS NVARCHAR(50))+'%' AS [Billable Target %], CAST(d.[Variance to Target %] AS NVARCHAR(50))+'%' AS [Variance to Target %], d.Department, d.[Job Role], d.Market FROM #data d ExitSp: </code></pre> <p>This forces the user to pick a date range before pulling back the data.</p> <p>An example of the data received back is:</p> <p><a href="https://i.stack.imgur.com/9r1nQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9r1nQ.png" alt="enter image description here"></a></p> <p>What is the best way to then mark this data with the Month of the range the user picks?</p> <p>For example if they choose <strong>startdate 01/01/2019</strong> and <strong>enddate 16/01/2019</strong> all records would be marked with an extra column showing Jan 2019 or something similar.</p> <p>Additionally if there was a selection that spanned multiple months eg. <strong>01/01/2019 to 20/02/2019</strong> this would mark those relating to Jan and those relating to Feb in a new column?</p> <p>Example of desired result:</p> <p><a href="https://i.stack.imgur.com/GsQiZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GsQiZ.png" alt="enter image description here"></a></p> <p>Many thanks for any advice</p>
3
4,986
Create Query for getting value equals to Current User id
<p>I want to get all matching values with current user id from key "group_member". The key "group_member" consist of users id. Database screenshot:</p> <p><a href="https://i.stack.imgur.com/pNqyx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pNqyx.png" alt="enter image description here"></a></p> <p>For this, i create query <code>Query query = mGroupDatabase.child("group_member").equalTo(mCurrent_user_id);</code></p> <p>but not getting any result. afterwards, this result needs to shown into RecyclerView. </p> <pre><code>mGroupList = (RecyclerView) mMainView.findViewById(R.id.group_list); mAuth = FirebaseAuth.getInstance(); mCurrent_user_id = mAuth.getCurrentUser().getUid(); mGroupDatabase = FirebaseDatabase.getInstance().getReference().child("Groups"); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); linearLayoutManager.setReverseLayout(true); linearLayoutManager.setStackFromEnd(true); mGroupList.setHasFixedSize(true); mGroupList.setLayoutManager(linearLayoutManager); Query query = mGroupDatabase.child("group_member").equalTo(mCurrent_user_id); query.keepSynced(true); FirebaseRecyclerOptions&lt;Group&gt; options = new FirebaseRecyclerOptions.Builder&lt;Group&gt;() .setQuery(query, Group.class) .build(); firebaseRecyclerAdapter = new FirebaseRecyclerAdapter&lt;Group, ViewHolder&gt;(options) { @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // Create a new instance of the ViewHolder, in this case we are using a custom // layout called R.layout.message for each item View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.adapter_users_activity_layout, parent, false); return new ViewHolder(view); } @Override protected void onBindViewHolder(final ViewHolder viewHolder, int position, final Group group) { Log.d("sdfdfgghhjhj", group.getGroup_member()); @Override public void onStart() { super.onStart(); firebaseRecyclerAdapter.startListening(); } @Override public void onStop() { super.onStop(); if (firebaseRecyclerAdapter != null) { firebaseRecyclerAdapter.stopListening(); } } </code></pre> <p>in above code, <code>Log.d("sdfdfgghhjhj", group.getGroup_member());</code> doesnt give any value. </p> <p>Group:</p> <pre><code>package com.example.messenger.messenger; public class Group { String name, group_member; public Group() { } public Group(String name, String group_member) { this.name = name; this.group_member = group_member; } public String getGroup_member() { return group_member; } public void setGroup_member(String group_member) { this.group_member = group_member; } public String getName() { return name; } public void setName(String name) { this.name = name; } } </code></pre>
3
1,337
Ajax And Spring MVC
<p>Hey Guys Am trying to update the jsp page by using ajax response here my issue is </p> <p>i have one dropdown ,It contains some values ,each value is associated with the some certain data,if i select one value from dropdown then i'll get the corresponding data on the jsp page ,If i try to select Another value from dropdown ,then jsp page contains the old as well as new data ,But actually i want new data ,once new data comes old data on jsp page shouls vanishes out from the page</p> <p>here my ajax call code is </p> <pre><code>function getSubjects(sectionId) { $.ajax({ type : 'get', url : approoturl+'/admin/section/subjects?sectionId='+sectionId, success : function(response) { var table = $('&lt;table class="table table-bordered"/&gt;').appendTo($('#somediv')) .append($('&lt;th/&gt;').text("Subject Name")) .append($('&lt;th/&gt;').text("Language")) .append($('&lt;th/&gt;').text("Subject ID")) $(response).each(function(i, response) { $('&lt;tr/&gt;').appendTo(table) .append($('&lt;td/&gt;').text(response.name)) .append($('&lt;td/&gt;').text(response.language)) .append($('&lt;td/&gt;').text(response.id)); }); } }); } &lt;/script&gt; </code></pre> <p>and my jsp page is </p> <pre><code>&lt;div id="form-group-section-id" class="form-group col-md-4 col-md-offset-4"&gt; &lt;label class="control-label"&gt;Choose Class&lt;/label&gt; &lt;form:select cssClass="form-control" path="section.id" onchange="getSubjects(value);"&gt; &lt;form:option value="${-1}"&gt;Select Class&lt;/form:option&gt; &lt;c:forEach items="${sections}" var="section"&gt; &lt;form:option value="${section.id}"&gt;${section.name}&lt;/form:option&gt; &lt;/c:forEach&gt; &lt;/form:select&gt; &lt;div class="text-danger"&gt; &lt;form:errors path="section.id" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="somediv"&gt;&lt;/div&gt; </code></pre> <p>Please give me some tips to remove old data and populate new data to particular div "somediv" any help would be greatfull</p>
3
1,611
ViewPager Issue while Scrolling
<p>When I am scrolling the viewpager from tab0 to tab1 then tab1 is shown correctly but it hitting the tab2 webservice. similiary when tab2 is shown then it's hitting tab3 webservice.</p> <pre><code>public class OrderDetailsTab extends Fragment { View view; ViewPager viewPager; TabLayout tabLayout; public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.tab_layout, container, false); tabLayout = (TabLayout) view.findViewById(R.id.tab_layout); viewPager = (ViewPager) view.findViewById(R.id.pager); tabLayout.addTab(tabLayout.newTab().setText("STATUS")); tabLayout.addTab(tabLayout.newTab().setText("TRUCKS")); tabLayout.addTab(tabLayout.newTab().setText("CHARGES")); tabLayout.addTab(tabLayout.newTab().setText("QUOTES")); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); viewPager.setAdapter(new MyPagerAdapter(getActivity().getSupportFragmentManager())); MyPagerAdapter myPagerAdapter=new MyPagerAdapter(getActivity().getSupportFragmentManager()); viewPager.setAdapter(myPagerAdapter); myPagerAdapter.notifyDataSetChanged(); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); myPagerAdapter.getRegisteredFragment(viewPager.getCurrentItem()); return view; } public static class MyPagerAdapter extends DetailPagerAdapter{ private static int NUM_ITEMS = 4; public MyPagerAdapter(FragmentManager fragmentManager) { super(fragmentManager); } @Override public Fragment getItem(int position) { switch (position) { case 0: return StatusTab.init(0); case 1: return TruckInfoTab.init(1); case 2: return ApprovalTab.init(2); case 3: return QuotesFragment.init(3); default: return null; } } @Override public int getCount() { return NUM_ITEMS; } @Override public CharSequence getPageTitle(int position) { return "Page " + position; } } @Override public void onResume() { super.onResume(); ((AppCompatActivity) getActivity()).getSupportActionBar().hide(); } } </code></pre> <p>Abstract Adapter Class:</p> <pre><code>public abstract class DetailPagerAdapter extends FragmentPagerAdapter { // Sparse array to keep track of registered fragments in memory private SparseArray&lt;Fragment&gt; registeredFragments = new SparseArray&lt;Fragment&gt;(); public DetailPagerAdapter(FragmentManager fragmentManager) { super(fragmentManager); } // Register the fragment when the item is instantiated @Override public Object instantiateItem(ViewGroup container, int position) { Fragment fragment = (Fragment) super.instantiateItem(container, position); registeredFragments.put(position, fragment); return fragment; } // Unregister when the item is inactive @Override public void destroyItem(ViewGroup container, int position, Object object) { registeredFragments.remove(position); super.destroyItem(container, position, object); } // Returns the fragment for the position (if instantiated) public Fragment getRegisteredFragment(int position) { Log.e("pos---", "" + position); return registeredFragments.get(position); } } </code></pre>
3
1,677
missing JSON array SWIFT
<p>There is a code generated by Insomnia and it works: </p> <pre><code>import Foundation let headers = [ "x-auth-header": "fb2f56fde81f21926fc0b5b74702f71da9f152efa7b5587a308984b71c9acac7fd44da05583ab06d57d29794f59fc475d9f2d132cbc6e29c421f11330a30a613", "content-type": "application/x-www-form-urlencoded" ] let postData = NSData(data: "".data(using: String.Encoding.utf8)!) let request = NSMutableURLRequest(url: NSURL(string: "http://rekrutacja.backendzs.pl/note/")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "GET" request.allHTTPHeaderFields = headers request.httpBody = postData as Data let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -&gt; Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume() </code></pre> <p>It works and has to return the array of items:</p> <pre><code>[ { "note_id": 14, "title": "last one", "content": "maybe", "version": 16, "created": 1530825998, "modified": 1530825998 }, { "note_id": 13, "title": "again", "content": "again", "version": 15, "created": 1530825532, "modified": 1530825532 }, { "note_id": 12, "title": "zzz", "content": "zzzz", "version": 14, "created": 1530825484, "modified": 1530825484 }, { "note_id": 11, "title": "Nowy tytuł", "content": "4", "version": 13, "created": 1530825331, "modified": 1530825331 }, { "note_id": 10, "title": "test5", "content": "test", "version": 12, "created": 1530825252, "modified": 1530825252 }, { "note_id": 9, "title": "title7", "content": "1111", "version": 11, "created": 1530825225, "modified": 1530825225 }, { "note_id": 7, "title": "test", "content": "content", "version": 9, "created": 1530817192, "modified": 1530817192 }, { "note_id": 6, "title": "Tytuł", "content": "Treść", "version": 8, "created": 1530550847, "modified": 1530550847 }, { "note_id": 5, "title": "Tytuł", "content": "Treść", "version": 7, "created": 1530547099, "modified": 1530547099 }, { "note_id": 3, "title": "title", "content": "content", "version": 3, "created": 1530469102, "modified": 1530469102 }, { "note_id": 2, "title": "title", "content": "content", "version": 2, "created": 1530468369, "modified": 1530468369 } ] </code></pre> <p>However, it doesn't provide this list with the response from the server. Only general data is displayed. I've tested and checked every article related to Alamofire, swiftyJSON, Swift .get requests and none of them works. </p> <p>Considering this information: </p> <ol> <li>The connection with the server is being established (code)</li> <li>If to launch the generated "shell" code and run through the "terminal" (Mac OS) it returns the array.</li> <li>Incorrect parsing? If yes - how to extract this data?</li> </ol> <p>Tried Dictionaries, swiftyJSON, NSSession ... but I did something wrong for sure. I'm dealing with JSON at SWIFT first time, so I can do silly mistakes!</p> <p>Thanks to everyone who will try to help in advance!!!</p> <p><a href="https://i.stack.imgur.com/1Cg0Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Cg0Z.png" alt="enter image description here"></a></p>
3
1,851
using animation_enabled boolean to prevent multiple jquery animations at once will break after being spammed
<p>I have 4 links on my page which fade their respective divs in and out as well as adjusting the containing div's height where necessary. I only want one div on a page at a time and the onload visible div is labels_div.</p> <p>When the user spams these links the divs get out of sync or overlap each other. I have researched this and the best possible option is to use a boolean variable which is checked onclick of each link.</p> <p>The issue arises that when a user spams the links eventually the boolean value gets stuck on false thus preventing any more animations.</p> <p>Could somebody explain what I have done wrong? Thanks</p> <pre><code>var animation_enabled; animation_enabled = true; function open_labels_div(){ if(!animation_enabled )return; animation_enabled = false; if($("#labels_div").is(':hidden')){ if($("#charts_div").is(':visible')){ $("#charts_div").fadeOut(400, function(){animation_enabled = true;}); $("#labels_div").fadeIn(400, function (){ $("#charts_div").css("display","none"); $("#labels_div").css("display","inline-block"); }); } else if($("#blank_charts_div").is(':visible')){ $("#blank_charts_div").fadeOut(400, function(){animation_enabled = true;}); $("#labels_div").fadeIn(400, function (){ $("#blank_charts_div").css("display","none"); $("#labels_div").css("display","inline-block"); }); } else if($("#reorder_div").is(':visible')){ $("#reorder_div").fadeOut(400, function(){animation_enabled = true;}); var minus = $("#reorder_div").height()-100; $('#tab_content').animate({'height': '-='+minus},400,"linear"); $("#labels_div").fadeIn(400, function (){ $("#reorder_div").css("display","none"); $("#labels_div").css("display","inline-block"); }); } } } function open_charts_div(){ if(!animation_enabled )return; animation_enabled = false; if($("#charts_div").is(':hidden')){ if($("#labels_div").is(':visible')){ $("#labels_div").fadeOut(400, function(){animation_enabled = true;}); $("#charts_div").fadeIn(400, function (){ $("#labels_div").css("display","none"); $("#charts_div").css("display","inline-block"); }); } else if($("#blank_charts_div").is(':visible')){ $("#blank_charts_div").fadeOut(400, function(){animation_enabled = true;}); $("#charts_div").fadeIn(400, function (){ $("#blank_charts_div").css("display","none"); $("#charts_div").css("display","inline-block"); }); } else if($("#reorder_div").is(':visible')){ $("#reorder_div").fadeOut(400, function(){animation_enabled = true;}); var minus = $("#reorder_div").height()-100; $('#tab_content').animate({'height': '-='+minus},400,"linear"); $("#charts_div").fadeIn(400, function (){ $("#reorder_div").css("display","none"); $("#charts_div").css("display","inline-block"); }); } } } function open_blank_charts_div(){ if(!animation_enabled )return; animation_enabled = false; if($("#blank_charts_div").is(':hidden')){ if($("#labels_div").is(':visible')){ $("#labels_div").fadeOut(400, function(){animation_enabled = true;}); $("#blank_charts_div").fadeIn(400, function (){ $("#labels_div").css("display","none"); $("#blank_charts_div").css("display","inline-block"); }); } else if($("#charts_div").is(':visible')){ $("#charts_div").fadeOut(400, function(){animation_enabled = true;}); $("#blank_charts_div").fadeIn(400, function (){ $("#charts_div").css("display","none"); $("#blank_charts_div").css("display","inline-block"); }); } else if($("#reorder_div").is(':visible')){ $("#reorder_div").fadeOut(400, function(){animation_enabled = true;}); var minus = $("#reorder_div").height()-100; $('#tab_content').animate({'height': '-='+minus},400,"linear"); $("#blank_charts_div").fadeIn(400, function (){ $("#reorder_div").css("display","none"); $("#blank_charts_div").css("display","inline-block"); }); } } } function open_reorder(){ if(!animation_enabled )return; animation_enabled = false; if($("#reorder_div").is(':hidden')){ var add = $("#reorder_div").height()-100; $('#tab_content').animate({'height': '+='+add},400,"linear", function(){animation_enabled = true;}); if($("#labels_div").is(':visible')){ $("#labels_div").fadeOut(400, function(){animation_enabled = true;}); $("#reorder_div").fadeIn(400, function (){ $("#labels_div").css("display","none"); $("#reorder_div").css("display","inline-block"); }); } else if($("#charts_div").is(':visible')){ $("#charts_div").fadeOut(400, function(){animation_enabled = true;}); $("#reorder_div").fadeIn(400, function (){ $("#charts_div").css("display","none"); $("#reorder_div").css("display","inline-block"); }); } else if($("#blank_charts_div").is(':visible')){ $("#blank_charts_div").fadeOut(400, function(){animation_enabled = true;}); $("#reorder_div").fadeIn(400, function (){ $("#blank_charts_div").css("display","none"); $("#reorder_div").css("display","inline-block"); }); } } } &lt;div id='options_tabs'&gt; &lt;ul&gt; &lt;li onclick='open_labels_div()'&gt;&lt;a&gt;Labels&lt;/a&gt;&lt;/li&gt; &lt;li onclick='open_charts_div()'&gt;&lt;a&gt;Charts&lt;/a&gt;&lt;/li&gt; &lt;li onclick='open_blank_charts_div()'&gt;&lt;a&gt;Blank Charts&lt;/a&gt;&lt;/li&gt; &lt;li onclick='open_reorder()'&gt;&lt;a&gt;Reorder&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id='tab_content'&gt; &lt;div id='labels_div'&gt; &lt;p&gt;labels content&lt;/p&gt; &lt;/div&gt; &lt;div id='charts_div'&gt; &lt;p&gt;charts content&lt;/p&gt; &lt;/div&gt; &lt;div id='blank_charts_div'&gt; &lt;p&gt;blank charts content&lt;/p&gt; &lt;/div&gt; &lt;div id='reorder_div'&gt; &lt;p&gt;reorder content&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
3
3,313
Kafka Connect in Docker container: Connector not added
<p>I'm trying to get a simple Kafka Connect container running. I did try the <a href="https://docs.confluent.io/5.0.0/installation/docker/docs/installation/connect-avro-jdbc.html" rel="nofollow noreferrer">Confluent Connect Tutorial</a>, but have a slightly different setup (no docker machine, no schema registry).</p> <p>For the time being, I'm working with a Docker compose setup containing Zookeeper and Kafka.</p> <pre><code>version: '3.1' services: zookeeper: image: confluentinc/cp-zookeeper ports: - 2181 environment: - ZOOKEEPER_CLIENT_PORT=2181 - ZOOKEEPER_TICK_TIME=2000 - ZOOKEEPER_SYNC_LIMIT=2 kafka: image: confluentinc/cp-kafka depends_on: - zookeeper ports: - 9092 - 9094:9094 environment: - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 # setup :9092 for access inside the docker network, 9094 for outside (ie host) - KAFKA_LISTENERS=INTERNAL://kafka:9092,OUTSIDE://kafka:9094 - KAFKA_ADVERTISED_LISTENERS=INTERNAL://kafka:9092,OUTSIDE://localhost:9094 - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=INTERNAL:PLAINTEXT,OUTSIDE:PLAINTEXT - KAFKA_INTER_BROKER_LISTENER_NAME=INTERNAL - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 - KAFKA_NUM_PARTITIONS=10 </code></pre> <p>That works fine for different uses, so I don't expect this to be a problem.</p> <p>Now I'm starting a Kafka Connect container which connects fine to Kafka. I use the following command which is adapted from the Connect Tutorial:</p> <pre><code>docker run -d \ --name=kafka-connect-test \ --net=kafka-connect_default \ --expose 28083 \ -p 28083:28083 \ -e CONNECT_BOOTSTRAP_SERVERS=kafka:9092 \ -e CONNECT_REST_PORT=28083 \ -e CONNECT_GROUP_ID="quickstart-test" \ -e CONNECT_CONFIG_STORAGE_TOPIC="quickstart-test-config" \ -e CONNECT_OFFSET_STORAGE_TOPIC="quickstart-test-offsets" \ -e CONNECT_STATUS_STORAGE_TOPIC="quickstart-test-status" \ -e CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR=1 \ -e CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR=1 \ -e CONNECT_STATUS_STORAGE_REPLICATION_FACTOR=1 \ -e CONNECT_KEY_CONVERTER="org.apache.kafka.connect.storage.StringConverter" \ -e CONNECT_VALUE_CONVERTER="org.apache.kafka.connect.storage.StringConverter" \ -e CONNECT_INTERNAL_KEY_CONVERTER="org.apache.kafka.connect.storage.StringConverter" \ -e CONNECT_INTERNAL_VALUE_CONVERTER="org.apache.kafka.connect.storage.StringConverter" \ -e CONNECT_REST_ADVERTISED_HOST_NAME="localhost" \ -e CONNECT_LOG4J_ROOT_LOGLEVEL=DEBUG \ -e CONNECT_PLUGIN_PATH=/usr/share/java/kafka,/etc/kafka-connect/jars \ -v /tmp/quickstart/file:/tmp/quickstart \ -v /tmp/quickstart/jars:/etc/kafka-connect/jars \ confluentinc/cp-kafka-connect:latest </code></pre> <p>The most notable difference is that I'm using the <code>StringConverter</code>, because I'd like to use <code>kafkacat</code> to insert test data.</p> <p>The container starts up fine and is running and reachable on all the exposed endpoints I tried. Since I didn't add any connectors, I query the available ones:</p> <p><code>localhost:28083/connector-plugins</code>:</p> <pre><code>[ { "class": "org.apache.kafka.connect.file.FileStreamSinkConnector", "type": "sink", "version": "5.4.0-ccs" }, { "class": "org.apache.kafka.connect.file.FileStreamSourceConnector", "type": "source", "version": "5.4.0-ccs" }, { "class": "org.apache.kafka.connect.mirror.MirrorCheckpointConnector", "type": "source", "version": "1" }, { "class": "org.apache.kafka.connect.mirror.MirrorHeartbeatConnector", "type": "source", "version": "1" }, { "class": "org.apache.kafka.connect.mirror.MirrorSourceConnector", "type": "source", "version": "1" } ] </code></pre> <p>So for now it would be enough for me to create a file sink that writes data from a topic to a file. I POST to <code>localhost:28083/connectors</code></p> <pre><code>{ "name": "file-sink", "config": { "connector.class": "org.apache.kafka.connect.file.FileStreamSinkConnector", "tasks.max": 1, "file": "/test.sink.txt", "topics": "test-topic" } } </code></pre> <p>and receive <code>201 - Created</code>.</p> <p>However, when querying that endpoint with <code>GET</code>, I get an empty array as a response. Trying around, I can also change the <code>connector.class</code> to <code>FileStreamSinkConnector</code> or just <code>FileStreamSink</code> and will still get a <code>201</code> (without a connector being added).</p> <p>What am I doing wrong?</p> <p>And why am I getting "success" responses when something obviously went wrong?</p>
3
1,865
Nodemon crashes in the middle of the process without showing any error message, how do i resolve it?
<p>I am running a script that is getting the files from Google drive and putting it in the s3. Now when i run the script, the process goes smoothly for sometime then app suddenly crashes without any error message, the script takes input also so couldn't find a way to use <code>nohup</code></p> <p>The code is like this</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict"; const fs = require("fs"); const readline = require("readline"); const { google } = require("googleapis"); const { upload_to_s3, emptyFolder, s3_exist } = require("./helper"); const prompt = require("prompt"); const SCOPES = ["https://www.googleapis.com/auth/drive"]; // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. const TOKEN_PATH = "token.json"; // Load client secrets from a local file. fs.readFile("credentials.json", (err, content) =&gt; { if (err) return console.log("Error loading client secret file:", err); // Authorize a client with credentials, then call the Google Drive API. authorize(JSON.parse(content), listFiles); }); /** * Create an OAuth2 client with the given credentials, and then execute the * given callback function. * @param {Object} credentials The authorization client credentials. * @param {function} callback The callback to call with the authorized client. */ function authorize(credentials, callback) { const { client_secret, client_id, redirect_uris } = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0] ); // Check if we have previously stored a token. fs.readFile(TOKEN_PATH, (err, token) =&gt; { if (err) return getAccessToken(oAuth2Client, callback); oAuth2Client.setCredentials(JSON.parse(token)); callback(oAuth2Client); }); } /** * Get and store new token after prompting for user authorization, and then * execute the given callback with the authorized OAuth2 client. * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for. * @param {getEventsCallback} callback The callback for the authorized client. */ function getAccessToken(oAuth2Client, callback) { const authUrl = oAuth2Client.generateAuthUrl({ access_type: "offline", scope: SCOPES, }); console.log("Authorize this app by visiting this url:", authUrl); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question("Enter the code from that page here: ", (code) =&gt; { rl.close(); oAuth2Client.getToken(code, (err, token) =&gt; { if (err) return console.error("Error retrieving access token", err); oAuth2Client.setCredentials(token); // Store the token to disk for later program executions fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) =&gt; { if (err) return console.error(err); console.log("Token stored to", TOKEN_PATH); }); callback(oAuth2Client); }); }); } /** * Lists the names and IDs of up to 10 files. * @param {google.auth.OAuth2} auth An authorized OAuth2 client. */ async function listFiles(auth) { let page_size; let page_token; prompt.start(); try { prompt.get( ["stage [d (dev),s (staging),p (prod)]", "pageSize", "pageToken"], function (err, result) { if (err) { return onErr(err); } let stage; let count = 0; let total; if ( result["stage [d (dev),s (staging),p (prod)]"] === "d" || result["stage [d (dev),s (staging),p (prod)]"] === "dev" ) { stage = "dev"; } else if ( result["stage [d (dev),s (staging),p (prod)]"] === "s" || result["stage [d (dev),s (staging),p (prod)]"] === "staging" ) { stage = "staging"; } else if ( result["stage [d (dev),s (staging),p (prod)]"] === "p" || result["stage [d (dev),s (staging),p (prod)]"] === "prod" ) { stage = "prod"; } else { console.log( "invalid input, default is chosen", result["stage [d (dev),s (staging),p (prod)]"] ); stage = "dev"; } // await emptyFolder("/tmp"); console.log("Getting the files"); console.log(" stage: " + stage); page_size = result.pageSize || 1000; console.log(" pageSize: " + page_size); page_token = String(result.pageToken) || null; console.log(" pageToken: " + page_token); const drive = google.drive({ version: "v3", auth }); drive.files.list( { includeItemsFromAllDrives: true, supportsAllDrives: true, pageSize: page_size, pageToken: page_token, fields: "nextPageToken,files(id,mimeType, name,fileExtension)", includeRemoved: false, }, async (err, res) =&gt; { if (err) return console.log("The API returned an error: " + err); const files = res.data.files; // console.log(res.data); // console.log(files); if (res.data.nextPageToken) { console.log("nextPageToken :", res.data.nextPageToken, "\n"); } let promises = []; if (files.length) { const filesWithExt = files.filter((file) =&gt; { if (file.fileExtension) { return file; } }); total = filesWithExt.length; console.log("Total files", files.length); console.log("Total files to be moved", filesWithExt.length); console.log("Files:"); // let t = 1; // files.map((file) =&gt; { // console.log(`${file.name} - (${file.id}) [${file.mimeType}]`); // // console.log(t); // // t = t + 1; // }); for (let i = 0; i &lt; files.length; i++) { const file = files[i]; const tmpName = file.name; const filePath = `/tmp/${tmpName}`; let path = tmpName; if (file.fileExtension) { const exist = await s3_exist(`migration-temp-${stage}`, path); if (exist) { console.log(path, " already exists in s3, skipped", exist); } else { promises.push( await downloadFile(stage, file.id, path, auth) ); } count = count + 1; console.log("..... ", total - count, " remaining"); } } await Promise.all(promises).then(async (result) =&gt; { console.log(result); if (res.data.nextPageToken) { console.log("nextPageToken :", res.data.nextPageToken, "\n"); } // await emptyFolder("/tmp"); process.exit(0); }); } else { console.log("No files found."); } } ); } ); } catch (err) { console.log("Error :", err); } // prompt.stop(); function onErr(err) { console.log(err); return 1; } } const downloadFile = async (stage, fileId, finalName, auth) =&gt; { const drive = google.drive({ version: "v3", auth }); console.log(`Downloading ${finalName}`); return drive.files .get({ fileId, alt: "media" }, { responseType: "arraybuffer" }) .then(async (res) =&gt; { try { console.log("Done downloading file."); // console.log(res.data); // var buffer = new Buffer(res.data, "binary"); var arrBuffer = res.data; var buffer = Buffer.from(new Uint8Array(arrBuffer)); // console.log("Buffer----", buffer); const promise_s3 = await upload_to_s3( buffer, finalName, `migration-temp-${stage}` ); return await promise_s3; } catch (err) { console.log("Error while uploading", err); } }); };</code></pre> </div> </div> </p> <p>need help resolving the crash,<br /> the error - [nodemon] app crashed - waiting for file changes before starting... the crash looks like this <a href="https://i.stack.imgur.com/CGQvb.png" rel="nofollow noreferrer">Error image</a></p> <p>Edit 1 : forgot to mention that i am running it on a t2.large ec2 instance, which has 50GB storage and 8GB RAM</p>
3
3,856
Why html player doesnt play audio blob on IOS safari?
<p>So I have two buttons(start/stop), canvas with sound visualizer and html5 audio player. Everything works cool, but not on IOS Safari (tested on 15.3). On IOS it shows that recording was started, that everything is going ok, but when the recording has stopped and blob inserted into audio tag, it shows &quot;error&quot; message inside audio-tag instead of playing this blob. Here is the code:</p> <pre><code> var stop = document.querySelector('#rec-stop'); var player = document.querySelector('#rec-player'); var totest = document.querySelector('.test-choice-btn'); navigator.mediaDevices.getUserMedia({audio:true}) .then(stream =&gt; {handlerFunction2(stream)}) function handlerFunction2(stream) { rec = new MediaRecorder(stream); audioContext = new AudioContext(); analyser = audioContext.createAnalyser(); microphone = audioContext.createMediaStreamSource(stream); javascriptNode = audioContext.createScriptProcessor(2048, 1, 1); analyser.smoothingTimeConstant = 0.8; analyser.fftSize = 1024; microphone.connect(analyser); analyser.connect(javascriptNode); javascriptNode.connect(audioContext.destination); canvasContext = $(&quot;#rec-canvas&quot;)[0].getContext(&quot;2d&quot;); javascriptNode.onaudioprocess = function() { var array = new Uint8Array(analyser.frequencyBinCount); analyser.getByteFrequencyData(array); var values = 0; var length = array.length; for (var i = 0; i &lt; length; i++) { values += (array[i]); } var average = values / length; canvasContext.clearRect(0, 0, 150, 270); canvasContext.fillStyle = '#BadA55'; canvasContext.fillRect(0, 270 - average, 150, 270); canvasContext.fillStyle = '#262626'; } audioChunks = []; rec.start(); stop.onclick = e =&gt; { rec.stop(); totest.classList.add('shown'); } rec.ondataavailable = e =&gt; { audioChunks.push(e.data); if (rec.state == &quot;inactive&quot;){ let blob = new Blob(audioChunks,{type:'audio/mpeg-3'}); player.src = URL.createObjectURL(blob); player.controls=true; player.autoplay=true; } } } </code></pre>
3
1,379
Liferay 7.1 custom portlet using CXF JAX-RS
<p>I'm getting the following error when my bundle is trying to start:</p> <pre><code>The activate method has thrown an exception java.lang.NoClassDefFoundError: Could not initialize class javax.ws.rs.core.EntityTag </code></pre> <p>That happens when I tried to deploy an OSGi module.</p> <p>I'm using:</p> <ul> <li>Liferay 7.1.2-ga3</li> <li>"org.apache.cxf:cxf-rt-rs-client:3.2.5"</li> <li>"javax.ws.rs:javax.ws.rs-api:2.1"</li> </ul> <p><strong>EDIT 1</strong> Full stacktrace</p> <pre><code>java.lang.ExceptionInInitializerError at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at org.apache.cxf.common.util.ProxyHelper.canSeeAllInterfaces(ProxyHelper.java:112) at org.apache.cxf.common.util.ProxyHelper.getClassLoaderForInterfaces(ProxyHelper.java:61) at org.apache.cxf.common.util.ProxyHelper.getProxyInternal(ProxyHelper.java:48) at org.apache.cxf.common.util.ProxyHelper.getProxy(ProxyHelper.java:126) at org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean.createWithValues(JAXRSClientFactoryBean.java:323) at org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean.create(JAXRSClientFactoryBean.java:264) at org.apache.cxf.jaxrs.client.JAXRSClientFactory.create(JAXRSClientFactory.java:172) at org.apache.cxf.jaxrs.client.JAXRSClientFactory.create(JAXRSClientFactory.java:126) at com.mycompany.myservice.service.impl.MyServiceImpl.activate(MyServiceImpl.java:161) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.felix.scr.impl.inject.methods.BaseMethod.invokeMethod(BaseMethod.java:228) at org.apache.felix.scr.impl.inject.methods.BaseMethod.access$500(BaseMethod.java:41) at org.apache.felix.scr.impl.inject.methods.BaseMethod$Resolved.invoke(BaseMethod.java:664) at org.apache.felix.scr.impl.inject.methods.BaseMethod.invoke(BaseMethod.java:510) at org.apache.felix.scr.impl.inject.methods.ActivateMethod.invoke(ActivateMethod.java:317) at org.apache.felix.scr.impl.inject.methods.ActivateMethod.invoke(ActivateMethod.java:307) at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:341) at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:114) at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:983) at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:956) at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:901) at org.eclipse.osgi.internal.serviceregistry.ServiceFactoryUse$1.run(ServiceFactoryUse.java:212) at java.security.AccessController.doPrivileged(Native Method) at org.eclipse.osgi.internal.serviceregistry.ServiceFactoryUse.factoryGetService(ServiceFactoryUse.java:210) at org.eclipse.osgi.internal.serviceregistry.ServiceFactoryUse.getService(ServiceFactoryUse.java:111) at org.eclipse.osgi.internal.serviceregistry.ServiceConsumer$2.getService(ServiceConsumer.java:45) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.getService(ServiceRegistrationImpl.java:524) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.getService(ServiceRegistry.java:464) at org.eclipse.osgi.internal.framework.BundleContextImpl.getService(BundleContextImpl.java:624) at org.apache.felix.scr.impl.manager.SingleRefPair.getServiceObject(SingleRefPair.java:73) at org.apache.felix.scr.impl.inject.BindParameters.getServiceObject(BindParameters.java:47) at org.apache.felix.scr.impl.inject.field.FieldHandler$ReferenceMethodImpl.getServiceObject(FieldHandler.java:519) at org.apache.felix.scr.impl.manager.DependencyManager.getServiceObject(DependencyManager.java:2308) at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.prebind(DependencyManager.java:1162) at org.apache.felix.scr.impl.manager.DependencyManager.prebind(DependencyManager.java:1576) at org.apache.felix.scr.impl.manager.AbstractComponentManager.collectDependencies(AbstractComponentManager.java:1029) at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:936) at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:756) at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(DependencyManager.java:1053) at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(DependencyManager.java:1007) at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.java:1216) at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.java:1137) at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.trackAdding(ServiceTracker.java:944) at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.track(ServiceTracker.java:880) at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:1168) at org.apache.felix.scr.impl.BundleComponentActivator$ListenerInfo.serviceChanged(BundleComponentActivator.java:125) at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:109) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:891) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:804) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:127) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:228) at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:469) at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentManager.java:906) at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentManager.java:892) at org.apache.felix.scr.impl.manager.RegistrationManager.changeRegistration(RegistrationManager.java:128) at org.apache.felix.scr.impl.manager.AbstractComponentManager.registerService(AbstractComponentManager.java:959) at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:732) at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(DependencyManager.java:1053) at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(DependencyManager.java:1007) at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.java:1216) at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.java:1137) at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.trackAdding(ServiceTracker.java:944) at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.track(ServiceTracker.java:880) at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:1168) at org.apache.felix.scr.impl.BundleComponentActivator$ListenerInfo.serviceChanged(BundleComponentActivator.java:125) at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:109) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:891) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:804) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:127) at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:228) at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:469) at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentManager.java:906) at org.apache.felix.scr.impl.manager.AbstractComponentManager$3.register(AbstractComponentManager.java:892) at org.apache.felix.scr.impl.manager.RegistrationManager.changeRegistration(RegistrationManager.java:128) at org.apache.felix.scr.impl.manager.AbstractComponentManager.registerService(AbstractComponentManager.java:959) at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:732) at org.apache.felix.scr.impl.manager.AbstractComponentManager.enableInternal(AbstractComponentManager.java:666) at org.apache.felix.scr.impl.manager.AbstractComponentManager.enable(AbstractComponentManager.java:432) at org.apache.felix.scr.impl.manager.ConfigurableComponentHolder.enableComponents(ConfigurableComponentHolder.java:665) at org.apache.felix.scr.impl.BundleComponentActivator.initialEnable(BundleComponentActivator.java:339) at org.apache.felix.scr.impl.Activator.loadComponents(Activator.java:381) at org.apache.felix.scr.impl.Activator.access$200(Activator.java:49) at org.apache.felix.scr.impl.Activator$ScrExtension.start(Activator.java:263) at org.apache.felix.scr.impl.AbstractExtender.createExtension(AbstractExtender.java:196) at org.apache.felix.scr.impl.AbstractExtender.modifiedBundle(AbstractExtender.java:169) at org.apache.felix.scr.impl.AbstractExtender.modifiedBundle(AbstractExtender.java:49) at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:488) at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:1) at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232) at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:450) at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:908) at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:230) at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:137) at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:129) at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:191) at org.eclipse.osgi.container.Module.publishEvent(Module.java:476) at org.eclipse.osgi.container.Module.start(Module.java:467) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1682) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1662) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1624) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1555) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1) at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:64) at javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:48) at javax.ws.rs.core.EntityTag.&lt;clinit&gt;(EntityTag.java:28) ... 111 more Caused by: java.lang.ClassNotFoundException at javax.ws.rs.ext.RuntimeDelegateFinder.newInstance(RuntimeDelegateFinder.java:118) at javax.ws.rs.ext.RuntimeDelegateFinder.find(RuntimeDelegateFinder.java:94) at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:58) ... 113 more Caused by: java.lang.InstantiationException at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at java.lang.Class.newInstance(Class.java:442) at javax.ws.rs.ext.RuntimeDelegateFinder.newInstance(RuntimeDelegateFinder.java:114) </code></pre> <p>Note that JAX RS RuntimeDelegate's default implementation is <strong>org.apache.cxf.jaxrs.impl.RuntimeDelegateImpl</strong> </p> <p><strong>EDIT 2</strong></p> <pre><code>WARN [main][AriesJaxrsServiceRuntime:246] Extension CachingServiceReference {_cachedProperties={osgi.jaxrs.application.select=(osgi.jaxrs.name=Liferay.OAuth2.Application), service.id=3972, objectClass=[javax.ws.rs.ext.MessageBodyWriter], osgi.jaxrs.name=OAuthAuthorizationDataMessageBodyWriter, osgi.jaxrs.extension.select=null (cached), service.ranking=null (cached), osgi.jaxrs.whiteboard.target=null (cached)}_serviceReference={javax.ws.rs.ext.MessageBodyWriter}={service.id=3972, osgi.jaxrs.extension=true, service.bundleid=660, service.scope=bundle, osgi.jaxrs.application.select=(osgi.jaxrs.name=Liferay.OAuth2.Application), osgi.jaxrs.name=OAuthAuthorizationDataMessageBodyWriter, component.name=com.liferay.oauth2.provider.rest.internal.endpoint.authorize.OAuthAuthorizationDataMessageBodyWriter, component.id=2290}_} is registered with error [Sanitized] ERROR [main][Whiteboard:80] ServiceReference CachingServiceReference {_cachedProperties={osgi.jaxrs.application.select=(osgi.jaxrs.name=Liferay.OAuth2.Application), service.id=3972, objectClass=[javax.ws.rs.ext.MessageBodyWriter], osgi.jaxrs.name=OAuthAuthorizationDataMessageBodyWriter, osgi.jaxrs.extension.select=null (cached), service.ranking=null (cached), osgi.jaxrs.whiteboard.target=null (cached)}_serviceReference={javax.ws.rs.ext.MessageBodyWriter}={service.id=3972, osgi.jaxrs.extension=true, service.bundleid=660, service.scope=bundle, osgi.jaxrs.application.select=(osgi.jaxrs.name=Liferay.OAuth2.Application), osgi.jaxrs.name=OAuthAuthorizationDataMessageBodyWriter, component.name=com.liferay.oauth2.provider.rest.internal.endpoint.authorize.OAuthAuthorizationDataMessageBodyWriter, component.id=2290}_} for extension produced error: java.lang.IllegalArgumentException: interface org.apache.cxf.jaxrs.ext.MessageContext is not visible from class loader [Sanitized] WARN [main][AriesJaxrsServiceRuntime:246] Extension CachingServiceReference {_cachedProperties={osgi.jaxrs.application.select=(osgi.jaxrs.name=Liferay.OAuth2.Application), service.id=3973, objectClass=[javax.ws.rs.ext.MessageBodyWriter], osgi.jaxrs.name=OAuthErrorMessageBodyWriter, osgi.jaxrs.extension.select=null (cached), service.ranking=null (cached), osgi.jaxrs.whiteboard.target=null (cached)}_serviceReference={javax.ws.rs.ext.MessageBodyWriter}={service.id=3973, osgi.jaxrs.extension=true, service.bundleid=660, service.scope=bundle, osgi.jaxrs.application.select=(osgi.jaxrs.name=Liferay.OAuth2.Application), osgi.jaxrs.name=OAuthErrorMessageBodyWriter, component.name=com.liferay.oauth2.provider.rest.internal.endpoint.authorize.OAuthErrorMessageBodyWriter, component.id=2291}_} is registered with error [Sanitized] ERROR [main][Whiteboard:80] ServiceReference CachingServiceReference {_cachedProperties={osgi.jaxrs.application.select=(osgi.jaxrs.name=Liferay.OAuth2.Application), service.id=3973, objectClass=[javax.ws.rs.ext.MessageBodyWriter], osgi.jaxrs.name=OAuthErrorMessageBodyWriter, osgi.jaxrs.extension.select=null (cached), service.ranking=null (cached), osgi.jaxrs.whiteboard.target=null (cached)}_serviceReference={javax.ws.rs.ext.MessageBodyWriter}={service.id=3973, osgi.jaxrs.extension=true, service.bundleid=660, service.scope=bundle, osgi.jaxrs.application.select=(osgi.jaxrs.name=Liferay.OAuth2.Application), osgi.jaxrs.name=OAuthErrorMessageBodyWriter, component.name=com.liferay.oauth2.provider.rest.internal.endpoint.authorize.OAuthErrorMessageBodyWriter, component.id=2291}_} for extension produced error: java.lang.IllegalArgumentException: interface org.apache.cxf.jaxrs.ext.MessageContext is not visible from class loader [Sanitized] WARN [main][AriesJaxrsServiceRuntime:246] Extension CachingServiceReference {_cachedProperties={osgi.jaxrs.application.select=null (cached), service.id=1287, objectClass=[javax.ws.rs.ext.MessageBodyReader, javax.ws.rs.ext.MessageBodyWriter], osgi.jaxrs.name=jaxb-json, osgi.jaxrs.extension.select=null (cached), service.ranking=-2147483648, osgi.jaxrs.whiteboard.target=null (cached)}_serviceReference={javax.ws.rs.ext.MessageBodyReader, javax.ws.rs.ext.MessageBodyWriter}={service.id=1287, osgi.jaxrs.extension=true, service.bundleid=551, service.scope=prototype, service.ranking=-2147483648, osgi.jaxrs.name=jaxb-json}_} is registered with error [Sanitized] ERROR [main][Whiteboard:80] ServiceReference CachingServiceReference {_cachedProperties={osgi.jaxrs.application.select=null (cached), service.id=1287, objectClass=[javax.ws.rs.ext.MessageBodyReader, javax.ws.rs.ext.MessageBodyWriter], osgi.jaxrs.name=jaxb-json, osgi.jaxrs.extension.select=null (cached), service.ranking=-2147483648, osgi.jaxrs.whiteboard.target=null (cached)}_serviceReference={javax.ws.rs.ext.MessageBodyReader, javax.ws.rs.ext.MessageBodyWriter}={service.id=1287, osgi.jaxrs.extension=true, service.bundleid=551, service.scope=prototype, service.ranking=-2147483648, osgi.jaxrs.name=jaxb-json}_} for extension produced error: java.lang.IllegalArgumentException: interface org.apache.cxf.jaxrs.ext.MessageContext is not visible from class loader [Sanitized] WARN [main][AriesJaxrsServiceRuntime:246] Extension CachingServiceReference {_cachedProperties={osgi.jaxrs.application.select=null (cached), service.id=1287, objectClass=[javax.ws.rs.ext.MessageBodyReader, javax.ws.rs.ext.MessageBodyWriter], osgi.jaxrs.name=jaxb-json, osgi.jaxrs.extension.select=null (cached), service.ranking=-2147483648, osgi.jaxrs.whiteboard.target=null (cached)}_serviceReference={javax.ws.rs.ext.MessageBodyReader, javax.ws.rs.ext.MessageBodyWriter}={service.id=1287, osgi.jaxrs.extension=true, service.bundleid=551, service.scope=prototype, service.ranking=-2147483648, osgi.jaxrs.name=jaxb-json}_} is registered with error [Sanitized] ERROR [main][Whiteboard:80] ServiceReference CachingServiceReference {_cachedProperties={osgi.jaxrs.application.select=null (cached), service.id=1287, objectClass=[javax.ws.rs.ext.MessageBodyReader, javax.ws.rs.ext.MessageBodyWriter], osgi.jaxrs.name=jaxb-json, osgi.jaxrs.extension.select=null (cached), service.ranking=-2147483648, osgi.jaxrs.whiteboard.target=null (cached)}_serviceReference={javax.ws.rs.ext.MessageBodyReader, javax.ws.rs.ext.MessageBodyWriter}={service.id=1287, osgi.jaxrs.extension=true, service.bundleid=551, service.scope=prototype, service.ranking=-2147483648, osgi.jaxrs.name=jaxb-json}_} for extension produced error: java.lang.IllegalArgumentException: interface org.apache.cxf.jaxrs.ext.MessageContext is not visible from class loader [Sanitized] </code></pre>
3
6,459
Unity game crash on some Android 6 (API 23)
<p>We have recently launched our android game ^_^ It it working fine for all users <strong>except for a few</strong>.</p> <p>The has complained that it <strong>suddenly crashes in-game</strong>. We couldn't track or reproduce the issue but we know that they all have the same android version which is <strong>Android 6, API 23</strong>.</p> <p>We tried running it on android 6 devices in our company but it just works fine.</p> <p>I suspect it has something to do with something's version.</p> <p>Any sort of idea?</p> <blockquote> <p>Unity version: 5.4.1f1</p> <p>Minimum API level in Player Settings: API 9</p> <p>Target SDK version: API 24</p> </blockquote> <h2>Android Manifest:</h2> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;ir.funera.crazycrowz&quot; android:versionCode=&quot;1&quot; android:versionName=&quot;1.0&quot;&gt; &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt; &lt;uses-permission android:name=&quot;com.farsitel.bazaar.permission.PAY_THROUGH_BAZAAR&quot; /&gt; &lt;!-- TODO: Replace the 'package' value above to reflect your app's package id. --&gt; &lt;!-- NOTE: Adjust minSDKVersion and targetSdkVersion as desired. --&gt; &lt;uses-sdk android:minSdkVersion=&quot;9&quot; android:targetSdkVersion=&quot;24&quot; /&gt; &lt;!-- NOTE: You must have at least these four permissions for AdColony. --&gt; &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt; &lt;application android:label=&quot;@string/app_name&quot; android:icon=&quot;@drawable/app_icon&quot; android:hardwareAccelerated=&quot;true&quot; android:name=&quot;com.soomla.SoomlaApp&quot;&gt; &lt;activity android:name=&quot;com.unity3d.player.UnityPlayerActivity&quot; android:configChanges=&quot;keyboardHidden|orientation|screenSize&quot; android:label=&quot;@string/app_name&quot;&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt; &lt;/intent-filter&gt; &lt;!-- &lt;meta-data android:name=&quot;unityplayer.UnityActivity&quot; android:value=&quot;true&quot; /&gt; --&gt; &lt;meta-data android:name=&quot;unityplayer.ForwardNativeEventsToDalvik&quot; android:value=&quot;true&quot; /&gt; &lt;/activity&gt; &lt;!-- NOTE: You must include these three activity specifications for AdColony. --&gt; &lt;activity android:name=&quot;com.jirbo.adcolony.AdColonyOverlay&quot; android:configChanges=&quot;keyboardHidden|orientation|screenSize&quot; android:theme=&quot;@android:style/Theme.Translucent.NoTitleBar.Fullscreen&quot; /&gt; &lt;activity android:name=&quot;com.jirbo.adcolony.AdColonyFullscreen&quot; android:configChanges=&quot;keyboardHidden|orientation|screenSize&quot; android:theme=&quot;@android:style/Theme.Black.NoTitleBar.Fullscreen&quot; /&gt; &lt;activity android:name=&quot;com.jirbo.adcolony.AdColonyBrowser&quot; android:configChanges=&quot;keyboardHidden|orientation|screenSize&quot; android:theme=&quot;@android:style/Theme.Black.NoTitleBar.Fullscreen&quot; /&gt; &lt;activity android:name=&quot;com.soomla.store.billing.bazaar.BazaarIabService$IabActivity&quot; android:theme=&quot;@android:style/Theme.Translucent.NoTitleBar.Fullscreen&quot; /&gt; &lt;meta-data android:name=&quot;billing.service&quot; android:value=&quot;bazaar.BazaarIabService&quot; /&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <h2>Here is the list of plugins used in this game with their versions:</h2> <p><a href="https://i.stack.imgur.com/cP7J9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cP7J9.png" alt="enter image description here" /></a></p> <h2>Here is all the installed packages in android SDK:</h2> <p><a href="https://i.stack.imgur.com/OU3ZP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OU3ZP.png" alt="enter image description here" /></a></p>
3
1,666
Upload a photo to a DB using servlets
<p>I am trying to make a Servlet that upload and insert an image to the Data base . this image is of blob type in the database . The code gives me this error : org.netbeans.modules.web.monitor.server.MonitorRequestWrapper cannot be cast to org.apache.tomcat.util.http.fileupload.RequestContext [Ljava.lang.StackTraceElement;@30ec706b</p> <p>here is a part of my code : ## web.xml ##</p> <pre><code> &lt;servlet&gt; &lt;servlet-name&gt;UploadServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;Servlet.UploadServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;uploadDir&lt;/param-name&gt; &lt;param-value&gt;/tmp&lt;/param-value&gt; &lt;/init-param&gt; &lt;/servlet&gt; </code></pre> <h2>DataUtente</h2> <pre><code> protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session=request.getSession(false); PrintWriter out = response.getWriter(); try { out.println("&lt;!DOCTYPE html&gt;"); out.println("&lt;html&gt;"); out.println("&lt;head&gt;"); out.println("&lt;title&gt;Servlet DataUtente&lt;/title&gt;"); out.println("&lt;/head&gt;"); out.println("&lt;body&gt;"); Utente utente =(Utente)session.getAttribute("utente"); out.println("&lt;h1&gt; Welcome " + utente.getUsername() + "&lt;/h1&gt;"); out.println(" &lt;form name=\"myWebForm\" action=\"UploadServlet\" method=\"POST\" ENCTYPE=\"multipart/form-data\"&gt;\n" + " &lt;input type=\"file\" name=\"uploadField\" /&gt;\n" + " &lt;INPUT TYPE='submit' VALUE='upload'&gt;"+ "&lt;/form&gt;"); out.println("&lt;/body&gt;"); out.println("&lt;/html&gt;"); } finally { out.close(); } } </code></pre> <h2>UploadServlet</h2> <pre><code>public class UploadServlet extends HttpServlet { DBManager dbman; private int maxFileSize = 50 * 1024; private int maxMemorySize = 4 * 1024; private File file ; private String dirName; public void init(ServletConfig config) throws ServletException{ super.init(config); //read the uploadDir from the servlet parameters dirName=config.getInitParameter("uploadDir"); if(dirName== null){ throw new ServletException("Please supply uploadDir parameters"); } } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session=request.getSession(false); PrintWriter out = response.getWriter(); try { // Apache Commons-Fileupload library classes DiskFileItemFactory factory = new DiskFileItemFactory(); //maximum size that will be stored in memory factory.setSizeThreshold(maxMemorySize); //create a file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); if (! ServletFileUpload.isMultipartContent(request)) { System.out.println("sorry. No file uploaded"); return; } // parse request List items = upload.parseRequest((RequestContext) request); // get uploaded file FileItem file = (FileItem) items.get(0); // Connect to the DB dbman = new DBManager(); Utente utente=(Utente)session.getAttribute("utente"); //String query = "insert into photos values(?)"; PreparedStatement ps = dbman.connectToDB().prepareStatement("insert into Utente(avatar) values(?) where Id='" + utente.getId() + "'"); ps.setBinaryStream(1, file.getInputStream(), (int) file.getSize()); ps.executeUpdate(); // dbman.connectToDB().commit(); dbman.connectToDB().close(); out.println("Proto Added Successfully. &lt;p&gt; &lt;a href='listphotos'&gt;List Photos &lt;/a&gt;"); } catch(Exception ex) { out.println( "Error ==&gt; " + ex.getMessage()); out.print(ex.getStackTrace()); } } </code></pre> <p>and here is the DDmanager:</p> <pre><code>public void closeConnection(){ try { dbConnection.close(); } catch (SQLException ex) { ex.printStackTrace(); Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex); } } public Connection connectToDB() throws SQLException, ClassNotFoundException{ String dbString = null; Class.forName(driver); dbString = "jdbc:derby://localhost:1527/DB"; dbConnection = (Connection) DriverManager.getConnection(dbString, userName, password); return dbConnection; } public boolean connectToDb() { //conneto a db try { String dbString = null; Class.forName(driver); dbString = "jdbc:derby://localhost:1527/DB"; dbConnection = (Connection) DriverManager.getConnection(dbString, userName, password); } catch (Exception e) { e.printStackTrace(); // System.out.print("erore"); return false; } return true; } public ResultSet executeQuery(String command) { try { stmt = dbConnection.createStatement(); ResultSet ress = stmt.executeQuery(command); return ress; } catch (Exception e) { e.printStackTrace(); return null; } } public void executeUpdateQuery(String command) { try { stmt = dbConnection.createStatement(); int ress = stmt.executeUpdate(command); stmt.close(); } catch (Exception e) { e.printStackTrace(); } </code></pre>
3
3,151
How to save a nested many-to-many relationship in API-only Rails?
<p>In my Rails (api only) learning project, I have 2 models, Group and Artist, that have a many-to-many relationship with a joining model, Role, that has additional information about the relationship. I have been able to save m2m relationships before by saving the joining model by itself, but here I am trying to save the relationship as a nested relationship. I'm using the <a href="https://github.com/jsonapi-serializer/jsonapi-serializer" rel="nofollow noreferrer">jsonapi-serializer</a> gem, but not married to it nor am I tied to the JSON api spec. Getting this to work is more important than following best practice.</p> <p>With this setup, I'm getting a 500 error when trying to save with the following errors: <code>Unpermitted parameters: :artists, :albums</code> and <code>ActiveModel::UnknownAttributeError (unknown attribute 'relationships' for Group.)</code></p> <p>I'm suspecting that my problem lies in the strong param and/or the json payload.</p> <p><strong>Models</strong></p> <pre><code>class Group &lt; ApplicationRecord has_many :roles has_many :artists, through: :roles accepts_nested_attributes_for :artists, :roles end class Artist &lt; ApplicationRecord has_many :groups, through: :roles end class Role &lt; ApplicationRecord belongs_to :artist belongs_to :group end </code></pre> <p><strong>Controller#create</strong></p> <pre><code>def create group = Group.new(group_params) if group.save render json: GroupSerializer.new(group).serializable_hash else render json: { error: group.errors.messages }, status: 422 end end </code></pre> <p><strong>Controller#group_params</strong></p> <pre><code>def group_params params.require(:data) .permit(attributes: [:name, :notes], relationships: [:artists]) end </code></pre> <p><strong>Serializers</strong></p> <pre><code>class GroupSerializer include JSONAPI::Serializer attributes :name, :notes has_many :artists has_many :roles end class ArtistSerializer include JSONAPI::Serializer attributes :first_name, :last_name, :notes end class RoleSerializer include JSONAPI::Serializer attributes :artist_id, :group_id, :instruments end </code></pre> <p><strong>Example JSON payload</strong></p> <pre><code>{ &quot;data&quot;: { &quot;attributes&quot;: { &quot;name&quot;: &quot;Pink Floyd&quot;, &quot;notes&quot;: &quot;&quot;, }, &quot;relationships&quot;: { &quot;artists&quot;: [{ type: &quot;artist&quot;, &quot;id&quot;: 3445 }, { type: &quot;artist&quot;, &quot;id&quot;: 3447 }] } } </code></pre> <p><strong>Additional Info</strong></p> <p>It might help to know that I was able to save another model with the following combination of json and strong params.</p> <pre><code># Example JSON &quot;data&quot;: { &quot;attributes&quot;: { &quot;title&quot;: &quot;Wish You Were Here&quot;, &quot;release_date&quot;: &quot;1975-09-15&quot;, &quot;release_date_accuracy&quot;: 1 &quot;notes&quot;: &quot;&quot;, &quot;group_id&quot;: 3455 } } # in albums_controller.rb def album_params params.require(:data).require(:attributes) .permit(:title, :group_id, :release_date, :release_date_accuracy, :notes) end </code></pre>
3
1,161
How to create JS Canvas Top Down Rain Effect or Reverse Warp Speed
<p>I am trying to figure out how to create a canvas rain effect, but from the top down perspective. Basically it's like you are looking down at the ground and you are watching the rain fall around you and fall slightly to the center at an angle, but it falls a short distance before ending. I am not seeing anything in searches except some game development that isn't canvas.</p> <p>I am also looking for a solution that doesn't require an external library.</p> <p>I have been able to modify some warp speed effect code to reverse the direction on the particles to fall to the background instead of off screen, but it is continuing to infinity toward the center and not redrawing or looping the particles that are coming from off screen.</p> <p>I think it has something to do with the particles not dropping off screen in this part of the code. Am I on the right track here or can I not accomplish this effect with the current code?</p> <pre><code>clear(); const cx = w / 2; const cy = h / 2; const count = stars.length; for (var i = 0; i &lt; count; i++) { const star = stars[i]; const x = cx + star.x / (star.z * 0.001); const y = cy + star.y / (star.z * 0.001); if (x &lt; 0 || x &gt;= w || y &lt; 0 || y &gt;= h) { continue; } const d = star.z / 1000.0; const b = 1000 - d * d; putPixel(x, y, b); } </code></pre> <p>Here is the full code that I am looking at. Any help would be appreciated trying to figure this out.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const canvas = document.getElementById("canvas"); const c = canvas.getContext("2d"); let w; let h; const setCanvasExtents = () =&gt; { w = document.body.clientWidth; h = document.body.clientHeight; canvas.width = w; canvas.height = h; }; setCanvasExtents(); window.onresize = () =&gt; { setCanvasExtents(); }; const makeStars = count =&gt; { const out = []; for (let i = 0; i &lt; count; i++) { const s = { x: Math.random() * 1600 - 800, y: Math.random() * 900 - 450, z: Math.random() * 1000 }; out.push(s); } return out; }; let stars = makeStars(1000); const clear = () =&gt; { c.fillStyle = "black"; c.fillRect(0, 0, canvas.width, canvas.height); }; const putPixel = (x, y, brightness) =&gt; { const intensity = brightness * 255; const rgb = "rgb(" + intensity + "," + intensity + "," + intensity + ")"; c.fillStyle = rgb; c.fillRect(x, y, 5, 5); }; const moveStars = distance =&gt; { const count = stars.length; for (var i = 0; i &lt; count; i++) { const s = stars[i]; s.z += distance; while (s.z &lt;= 1) { s.z -= 10; } } }; let prevTime; const init = time =&gt; { prevTime = time; requestAnimationFrame(tick); }; const tick = time =&gt; { let elapsed = time - prevTime; prevTime = time; moveStars(elapsed * 1.5); clear(); const cx = w / 2; const cy = h / 2; const count = stars.length; for (var i = 0; i &lt; count; i++) { const star = stars[i]; const x = cx + star.x / (star.z * 0.001); const y = cy + star.y / (star.z * 0.001); if (x &lt; 0 || x &gt;= w || y &lt; 0 || y &gt;= h) { continue; } const d = star.z / 1000.0; const b = 1000 - d * d; putPixel(x, y, b); } requestAnimationFrame(tick); }; requestAnimationFrame(init);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { position: fixed; left: 0px; right: 0px; top: 0px; bottom: 0px; overflow: hidden; margin: 0; padding: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="canvas" style="width: 100%; height: 100%; padding: 0;margin: 0;"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p>
3
1,444
different way to write a method
<p>I have a class to define a right hand side terms of differential equation: this class provide the method to compute the rhs function and its derivate the function is store in a vector container in this way the class is suitable for the system of Differential Equation as well.</p> <p>here the interface in which the method that I would to change is defined </p> <pre><code> template &lt;typename Type = double&gt; class rhsODEProblem { using analysisFunction = std::function&lt;const Type(const Type, const std::valarray&lt;Type&gt;)&gt;; public: rhsODEProblem(const std::vector&lt;std::function&lt;const Type(const Type,const std::valarray&lt;Type&gt;)&gt;&gt; numfun , const std::vector&lt;std::function&lt;const Type(const Type,const Type)&gt;&gt; exactfun , const Type,const Type,const Type,const std::valarray&lt;Type&gt;,const std::string ) noexcept ; rhsODEProblem(const std::vector&lt;std::function&lt;const Type(const Type,const std::valarray&lt;Type&gt;)&gt;&gt; numfun, const Type, const Type, const Type, const std::valarray&lt;Type&gt; ) noexcept ; virtual ~rhsODEProblem() = default ; rhsODEProblem(const rhsODEProblem &amp;) = default ; rhsODEProblem(rhsODEProblem&amp;&amp; ) = default ; rhsODEProblem&amp; operator=(const rhsODEProblem&amp;) = default ; rhsODEProblem&amp; operator=(rhsODEProblem&amp;&amp; ) = default ; const std::vector&lt;std::function&lt;const Type(const Type,const std::valarray&lt;Type&gt;)&gt;&gt; numericalFunction ; const std::vector&lt;std::function&lt;const Type(const Type,const Type)&gt;&gt; analiticalFunction ; const std::vector&lt;analysisFunction&gt;&amp; f = numericalFunction ; const auto dfdt(std::size_t indx , const Type t , const std::valarray&lt;Type&gt; u) { return (f[indx](t, u+eps )-f[indx](t,u))/eps ; } auto setRhs (const std::vector&lt; std::function&lt;const Type(const Type,const std::valarray&lt;Type&gt;)&gt;&gt; numfun) noexcept { for(auto i=0 ; i &lt; numfun.size() ; i++) { numericalFunction.push_back(numfun.at(i)) ; } } auto setExact(const std::vector&lt;std::function&lt;const Type(const Type,const Type)&gt;&gt; exactfun) noexcept { for(auto i=0 ; i &lt; exactfun.size(); i++) { analiticalFunction.push_back(exactfun.at(i)); } } auto solveExact() noexcept ; const Type t0() const noexcept { return _t0 ;} const Type tf() const noexcept { return _tf ;} const Type dt() const noexcept { return _dt ;} const std::valarray&lt;Type&gt; u0() const noexcept { return _u0 ;} const std::string fname () const noexcept { return filename ;} //--- private: Type _t0 ; // start time Type _tf ; // final time Type _dt ; // time-step std::valarray&lt;Type&gt; _u0 ; // iv std::string filename ; Type eps = 1e-12 ; }; </code></pre> <p>I would like to change the method dfdt in a way in which I can call it using the following syntax <code>dfdt[index]( t , u_valarray )</code> instead of <code>dfdt(index, t, u_valarray )</code> In which way I can change this method ? </p> <p><strong>EDIT</strong> thank for your answer so in my case it gonna be :</p> <pre><code>foo_helper(foo &amp;, int index); operator()(int n, Type t, std::valarray&lt;Type&gt; u ); </code></pre> <p>right ?</p> <p><strong>EDIT</strong> no I didn't get the point. I wrote :</p> <pre><code>class dfdx { public: dfdx( rhsODEProblem&lt;Type&gt; &amp;r , int index_ ) : index{index_ } {} void operator()(Type t, std::valarray&lt;Type&gt; u){ return (f[index](t, u + eps )-f[index](t,u))/eps ; } int index ; }; dfdx operator[](std::size_t index) { return dfdx(*this, index); } </code></pre> <p>then I call it in this way : </p> <pre><code>rhs.dfdx[j](t , uOld) ) </code></pre> <p>but I got an error :</p> <pre><code>BackwardEulerSolver.H:114:50: error: invalid use of ‘class mg::numeric::odesystem::rhsODEProblem&lt;double&gt;::dfdx’ ( 1- dt() * rhs.dfdx[j](t , uOld) ) ; ~~~~^~~~ </code></pre>
3
1,956
C# global clipboard contents
<p>I am not sure if I am going about this c# form the right way. I want to get the clipboard contents of any ctrl + C events that happen on any window. What is the right way to capture global clipboard information?</p> <pre><code> namespace WindowsFormsApplication1 { public class copydata { public int entry; public string data; } public partial class Form1 : Form { // DLL libraries used to manage hotkeys [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk); [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); const int COPY_ACTION = 1; const int TOGGLE_FORM = 2; const int WM_HOTKEY = 0x0312; List&lt;copydata&gt; copies; int count; public Form1() { InitializeComponent(); RegisterHotKey(this.Handle, COPY_ACTION, 2, Keys.C.GetHashCode()); RegisterHotKey(this.Handle, TOGGLE_FORM, 6, Keys.L.GetHashCode()); copies = new List&lt;copydata&gt;(); count = 0; } private void button1_Click(object sender, EventArgs e) { Clipboard.SetText(listBox1.Items[listBox1.SelectedIndex].ToString()); } protected override void WndProc(ref Message m) { base.WndProc(ref m); if(m.Msg == WM_HOTKEY) { if(m.WParam.ToInt32() == COPY_ACTION) { string val = Clipboard.GetText(); ++count; copies.Add(new copydata { entry = count, data = val }); this.listBox1.DisplayMember = "data"; this.listBox1.ValueMember = "entry"; this.listBox1.DataSource = copies; } if (m.WParam.ToInt32() == TOGGLE_FORM) { if(!this.Visible) { this.Show(); } else { this.Hide(); } } } } } } </code></pre>
3
1,223
How to judge bmp pictures from clipboard whether they are same using wxpython?
<p>Function that I want to realize: when the bmp picture get from clipboard is changed, refresh window. If not, nothing will be done.</p> <p>Question that I meet: every time my program goes into function UpdateMsgShownArea(), self.oldBmp will be diff with self.bmp, but I have already let self.oldBmp = self.bmp if they are different, and it prints "111111". While next time the program goes into UpdateMsgShownArea(), self.oldBmp will be diff with self.bmp again. It confuses me.</p> <p><a href="https://i.stack.imgur.com/b4j9B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b4j9B.png" alt="my print message image"></a></p> <p>code as follows:</p> <pre><code>#!/usr/bin/env python import wx import os, sys #---------------------------------------------------------------------------- # main window class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(600,480)) self.panel = MyPanel(self) self.CreateStatusBar() # A StatusBar in the bottom of the window # Setting up the menu. filemenu= wx.Menu() # wx.ID_ABOUT and wx.ID_EXIT are standard ids provided by wxWidgets. menuAbout = filemenu.Append(wx.ID_ABOUT, "&amp;About"," Information about this program") menuExit = filemenu.Append(wx.ID_EXIT,"E&amp;xit"," Terminate the program") # Creating the menubar. menuBar = wx.MenuBar() menuBar.Append(filemenu,"&amp;File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. # Set events. self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout) self.Bind(wx.EVT_MENU, self.OnExit, menuExit) self.Show(True) def OnAbout(self,e): # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets. dlg = wx.MessageDialog( self, "A small text editor", "About Sample Editor", wx.OK) dlg.ShowModal() # Show it dlg.Destroy() # finally destroy it when finished. def OnExit(self,e): self.Close(True) # Close the frame. #---------------------------------------------------------------------------- # main panel class MyPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) # shared path boxsizer, DirPickerCtrl is alternative and better realization for textCtrl + btn sharedPathStaticText = wx.StaticText(self, -1, 'Shared Dir:') self.sharedPathTextCtrl = wx.TextCtrl(self, -1, 'Please choose a dir', style = wx.TE_READONLY|wx.TE_RICH) sharedPathBtn = wx.Button(self, -1, 'Browse', name = 'Shared dir button') box1 = wx.BoxSizer(wx.HORIZONTAL) box1.Add(sharedPathStaticText, 0, wx.ALIGN_CENTER) box1.Add(self.sharedPathTextCtrl, 1, wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, 5) # proportion = 1, border = 5 box1.Add(sharedPathBtn, 0) self.Bind(wx.EVT_BUTTON, self.OnOpen, sharedPathBtn) # local path boxsizer localPathStaticText = wx.StaticText(self, -1, 'Local Dir: ') self.localPathTextCtrl = wx.TextCtrl(self, -1, 'Please choose a dir', style = wx.TE_READONLY|wx.TE_RICH) localPathBtn = wx.Button(self, -1, 'Browse', name = 'local dir button') box2 = wx.BoxSizer(wx.HORIZONTAL) box2.Add(localPathStaticText, 0, wx.ALIGN_CENTER) box2.Add(self.localPathTextCtrl, 1, wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, 5) # proportion = 1, border = 5 box2.Add(localPathBtn, 0) self.Bind(wx.EVT_BUTTON, self.OnOpen, localPathBtn) # message show area messageShowStaticText = wx.StaticText(self, -1, 'Sync info shown area: ') box5 = wx.BoxSizer(wx.HORIZONTAL) box5.Add(messageShowStaticText, 0, wx.ALIGN_LEFT) # size (200,200) don't take effect #msgShowAreaID = wx.NewId() #print msgShowAreaID self.msgShowArea = wx.ScrolledWindow(self, -1, size = (200,200), style = wx.SIMPLE_BORDER) box3 = wx.BoxSizer(wx.HORIZONTAL) box3.Add(self.msgShowArea, 1, wx.ALIGN_CENTER, 10) # sync ctrl buttons stopSyncBtn = wx.Button(self, -1, 'Stop Sync', name = 'Stop Sync button') resumeSyncBtn = wx.Button(self, -1, 'Resume Sync', name = 'Resume Sync button') box4 = wx.BoxSizer(wx.HORIZONTAL) box4.Add(stopSyncBtn, 0, wx.ALIGN_CENTER|wx.RIGHT, 20) box4.Add(resumeSyncBtn, 0, wx.ALIGN_CENTER|wx.LEFT, 20) # sizer sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(box1, 0, wx.EXPAND|wx.ALL, 10) sizer.Add(box2, 0, wx.EXPAND|wx.ALL, 10) sizer.Add(box5, 0, wx.EXPAND|wx.ALL, 10) sizer.Add(box3, 0, wx.EXPAND|wx.ALL, 10) sizer.Add(box4, 0, wx.ALIGN_CENTER, 10) self.SetSizer(sizer) self.SetAutoLayout(True) # clipboard self.clip = wx.Clipboard() self.x = wx.BitmapDataObject() self.bmp = None self.oldBmp = None self.msgShowArea.Bind(wx.EVT_IDLE, self.UpdateMsgShownArea) self.msgShowArea.Bind(wx.EVT_PAINT, self.OnPaint) def OnOpen(self, e): """ Open a file""" button = e.GetEventObject() dlg = wx.DirDialog(self, "Choose a dir", "", wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() if button.GetName() == 'Shared dir button': self.sharedPathTextCtrl.SetValue(path) if button.GetName() == 'local dir button': self.localPathTextCtrl.SetValue(path) dlg.Destroy() def UpdateMsgShownArea(self, e): print "UpdateMsgShownArea" self.clip.Open() self.clip.GetData(self.x) self.clip.Close() self.bmp = self.x.GetBitmap() if self.oldBmp == self.bmp: print "same pic" return else: print "diff pic" self.oldBmp = self.bmp if self.oldBmp == self.bmp: print "111111" else: print "222222" print "abcd" #self.Refresh() #self.msgShowArea.Refresh() def OnPaint(self, evt): if self.bmp: dc = wx.PaintDC(self.msgShowArea) dc.DrawBitmap(self.bmp, 20, 20, True) #---------------------------------------------------------------------------- if __name__ == '__main__': app = wx.App(False) frame = MyFrame(None, "EasySync") app.MainLoop() </code></pre>
3
2,996
dynamic form funky behavior in vuejs
<p>I am using VueJS 2.6.11 and bootstrap 4 to create two dynamic sections(Category and Product) that contain divs and input fields. The product section is nested within the category section. When someone clicks the New Category button another category should get generated. The same behavior should also happen when someone clicks the New Product button, another Product section should get generated, but only inside the current category section.</p> <p>Issue:</p> <p>When someone clicks the New Product button, the Add Product section will get generated inside all current Category sections. Also, v-model appears to bind to every product name input. When someone clicks the X button for a specific Product section one product section would get deleted from all current Category sections.</p> <p>I'm not exactly sure why this is happening.</p> <p>codepen: <a href="https://codepen.io/d0773d/pen/ExjbEpy" rel="nofollow noreferrer">https://codepen.io/d0773d/pen/ExjbEpy</a></p> <p>code: </p> <pre><code>&lt;!-- Bootstrap CSS --&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"&gt; &lt;title&gt;Create Categories and Products&lt;/title&gt; </code></pre> <p> </p> <pre><code> &lt;!-- New Category --&gt; &lt;button class="btn btn-success mt-5 mb-5" @click="addNewCategoryForm"&gt; New Category &lt;/button&gt; &lt;div class="card mb-3" v-for="(category, index) in categories"&gt; &lt;div class="card-body"&gt; &lt;span class="float-right" style="cursor:pointer" @click="deleteCategoryForm"&gt; X &lt;/span&gt; &lt;h4 class="card-title"&gt;Add Category&lt;/h4&gt; &lt;div class="category-form"&gt; &lt;input type="text" class="form-control mb-2" placeholder="Category Name" v-model="category.name"&gt; &lt;/div&gt; &lt;!-- New Product --&gt; &lt;button class="btn btn-success mt-5 mb-5" @click="addNewProductForm"&gt; New Product &lt;/button&gt; &lt;div class="card mb-3" v-for="(product, index) in products"&gt; &lt;div class="card-body"&gt; &lt;span class="float-right" style="cursor:pointer" @click="deleteProductForm"&gt; X &lt;/span&gt; &lt;h4 class="card-title"&gt;Add Product&lt;/h4&gt; &lt;div class="product-form"&gt; &lt;input type="text" class="form-control mb-2" placeholder="Product Name" v-model="product.name"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Optional JavaScript --&gt; &lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt; &lt;script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"&gt;&lt;/script&gt; &lt;script&gt; var app = new Vue({ el: '.container', data: { categories: [ { name: '', } ], products: [ { name: '', } ] }, methods: { addNewCategoryForm () { this.categories.push({ name: '', }); }, deleteCategoryForm (index) { this.categories.splice(index, 1); }, addNewProductForm () { this.products.push({ name: '', }); }, deleteProductForm (index) { this.products.splice(index, 1); }, } }); &lt;/script&gt; </code></pre> <p> </p>
3
2,087
React Native Component Renders under other components inside a modal
<p>I have a modal that contains various children components. One of them being a calendar component that is opened after pressing the text &quot;Select Date&quot;</p> <p>Upon opening the Calendar component renders underneath the other components on the page.</p> <p>I have tried using position: 'absolute' with a higher zIndex but I still cannot get the Calendar Component to render on top of everything else...how can I accomplish this?</p> <p><a href="https://i.stack.imgur.com/aNn5R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aNn5R.png" alt="Here is an image of what is occuring" /></a></p> <p><a href="https://i.stack.imgur.com/6eZFr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6eZFr.png" alt="This is wrapped in a View component with position: absolute and a high zindex" /></a></p> <p><a href="https://i.stack.imgur.com/Dz8Ku.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dz8Ku.png" alt="This is wrapped in a View component with position: absolute and a high zindex" /></a></p> <p>JSX For the components</p> <pre><code>&lt;View style={styles.container}&gt; &lt;View style={styles.routineitems}&gt; &lt;TouchableOpacity &gt; &lt;Text style={{ }}&gt;Due Date&lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;TouchableOpacity onPress={()=&gt;calendarShouldShow(calendarVisible)}&gt; &lt;Text style={{ }}&gt;Select Date&lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; &lt;Calendar style={{position: 'absolute',zIndex: 4}}/&gt; &lt;View style={styles.routineitems}&gt; &lt;Text&gt;Tags&lt;/Text&gt; &lt;DropDownPicker placeholder=&quot;Tags&quot; /&gt; &lt;/View&gt; &lt;View style={styles.routineitems}&gt; &lt;Text&gt;Notes&lt;/Text&gt; &lt;TextInput style={styles.input} onChangeText ={ value =&gt; setNotes(value)} value={notes} laceholder=&quot;Notes&quot; textAlign={'right'} /&gt; &lt;/View&gt; &lt;/View&gt; </code></pre> <p>STYLESHEET</p> <pre><code>const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', width: '100%' }, routineitems: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', width: '90%', marginBottom: '1%', marginTop: '1%', alignItems: 'center', zIndex: 0 }, input: { height: 40, width: '30%', borderRadius: 20, backgroundColor: 'white', fontSize: 50, textAlignVertical:'bottom', paddingTop: 0, paddingBottom:0, textAlign: 'right' } }); </code></pre>
3
1,360
OpenCV corrupting HQ Rapsicam data above 4000x3040 resoution?
<h1>The Problem</h1> <p>When I take an image using OpenCV that is larger than 4000 pixels wide, using a high quality picam, the image data appears corrupted (it's offset).</p> <h2>More Detail</h2> <p>As stated, I cannot get a good image when using OpenCV at over 4000 pixels wide of resolution. I know that the hardware is not the issue as I can get a clean full resolution (4056x3040) image when I use the raspistill command:</p> <p><code>sudo raspistill -o testing.tiff -w 4056 -h 3040</code></p> <p>Here is the clean output from raspistill:</p> <p><a href="https://i.stack.imgur.com/EuE8o.jpg" rel="nofollow noreferrer">4056x3040 image - Clean Image produced by raspistill command</a></p> <p>I am able to capture images using OpenCV in either Python:</p> <pre><code>import cv2 as cv def main(): cap = cv.VideoCapture(&quot;/dev/video2&quot;, cv.CAP_V4L2) cap.set(cv.CAP_PROP_FRAME_WIDTH, 4056)#works fine up to 4000 cap.set(cv.CAP_PROP_FRAME_HEIGHT, 3040) if not(cap.isOpened()): print(&quot;could not open video device&quot;) else: print(&quot;cap opened&quot;) ret, frame = cap.read() if(ret): cv.imwrite(&quot;./test_im.jpg&quot;, frame) print(&quot;image saved&quot;) else: print(&quot;no capture data returned&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Or I can capture in OpenCV with C++:</p> <pre><code>#include &lt;opencv2/opencv.hpp&gt; #include &lt;iostream&gt; int main(int argc, char *argv[]){ cv::Mat frame; cv::VideoCapture cap(&quot;/dev/video2&quot;, cv::CAP_V4L2); cap.set(cv::CAP_PROP_FRAME_WIDTH, 4056); cap.set(cv::CAP_PROP_FRAME_HEIGHT, 3040); if(cap.isOpened() == false){ std::cout &lt;&lt; &quot;cap not opened&quot; &lt;&lt; std::endl; } else{ std::cout &lt;&lt; &quot;cap opened&quot; &lt;&lt; std::endl; } cap &gt;&gt; frame; if(frame.empty()){ std::cout &lt;&lt; &quot;empy frame&quot;; } else{ std::cout &lt;&lt; &quot;successfully captured image&quot; &lt;&lt; std::endl; cv::imwrite(&quot;test.tiff&quot;, frame); } } </code></pre> <p>The Result is the same either way.</p> <p>Here is the corrupted output from OpenCV:</p> <p><a href="https://i.stack.imgur.com/NFoB5.jpg" rel="nofollow noreferrer">4056x3040 image - Corrupted and captured by OpenCV</a></p> <p>To me it seems as if it something was going wrong with the timing of the capture. The format of which I save it to does not make a difference either. I have tried .png, .jpg, and .tiff. The result is always the same. After reboot the results remain the same.</p> <p>If I reduce the desired capture resolution to only 4000x3040 then I am able to successfully make a capture. Here are the results:</p> <p><a href="https://i.stack.imgur.com/1BMdC.jpg" rel="nofollow noreferrer">4000x3040 image - successfully captured by OpenCV</a></p> <p>I am not sure why this is happening. And would really appreciate any help! Let me know if there is any other information that could be useful!</p> <h1>System</h1> <ul> <li>Raspberry Pi 4B with 4GB RAM.</li> <li>High Quality Picam</li> <li>Running Ubuntu 20.04</li> <li>OpenCV 4.5.5</li> </ul>
3
1,335
How do I use SELECT LAST_INSERT_ID() without closing the connection
<p>I have table whose only column is an auto-incrementing primary key. I want to insert a new row into this table, and then get the ID generated by this insert. </p> <p>Reading through StackOverflow, LAST_INSERT_ID() appears to be the standard solution. The caveat given is that it will return the last generated ID per connection. I wrote a new method to INSERT and then SELECT, all without closing the connection. Then I started getting "Operation not allowed after ResultSet closed" errors. Reading up on that in StackOverflow leads me to think I should not be preparing multiple statements on the same connection. </p> <p>How should I be implementing this insert and select model? Am I misunderstanding what counts as the database connection concerning LAST_INSERT_ID()?</p> <p>relevant excerpts:</p> <pre><code>public class ConceptPortal { public static ConceptID createNewConceptID() throws Exception { ConceptID returnConceptID = null; StringBuilder stmt = new StringBuilder("INSERT INTO " + MysqlDefs.CONCEPT_TABLE + " VALUES ()"); ArrayList&lt;Object&gt; parameters = new ArrayList&lt;Object&gt;(); StringBuilder stmt2 = new StringBuilder("SELECT LAST_INSERT_ID()"); ResultSet resultSet = MysqlPortal.specialExecuteStatement(stmt.toString(), parameters, stmt2.toString()); if (resultSet.next()) { returnConceptID = new ConceptID(resultSet.getLong(1)); resultSet.getStatement().close(); } else { throw new Exception("Wait a minute...I can't create new concepts?!!"); } return returnConceptID; } } public class MysqlPortal { private static ConnPool connPool = null; public static void init(String database, boolean startFromScratch) throws Exception { databaseName = database; connPool = new ConnPool(database); } /* * This one doesn't close right away, * so that we can run LAST_INSERT_ID() on it */ static ResultSet specialExecuteStatement(String sqlCommand, ArrayList&lt;Object&gt; parameters, String followUpSelect) throws Exception { ResultSet resultSet = null; if (parameters == null) { System.out.println(sqlCommand + " :: [null]"); } else { System.out.println(sqlCommand + " :: " + Arrays.deepToString(parameters.toArray()) ); } ConnectionImpl connInstance = connPool.aquire(); try { Connection myConn = connInstance.getConnection(); try (PreparedStatement pstmt = myConn.prepareStatement(sqlCommand)) { if (parameters != null) { int i = 1; for (Object parameter : parameters) { pstmt.setObject(i, parameter); i++; } } pstmt.execute(); } try (PreparedStatement pstmt2 = myConn.prepareStatement(followUpSelect)) { resultSet = pstmt2.executeQuery(); } connPool.release(connInstance); return resultSet; } catch (SQLException e) { System.out.println(sqlCommand); throw e; } } } </code></pre>
3
1,317
ResourceNotFoundException ListViewAdapter
<p>I made a constructor <code>DataPembeli</code>for list view item then make the custom List View Adapter <code>DataPembeliListAdapter</code> and used the constructor like this:</p> <pre><code>txtid.setText(dataPembeliItems.get(position).getId()); // THIS IS THE ERROR LINE txtket1.setText(dataPembeliItems.get(position).getNama()); txtket2.setText(dataPembeliItems.get(position).getAlamat()); txtket3.setText(dataPembeliItems.get(position).getNohp()); </code></pre> <p>In the <code>DataPembeliFragment</code> class I've used it like this:</p> <pre><code>public class DataPembeliFragment extends Fragment { private ListView listPembeli; private ImageButton btnTambah; // slide data items private int[] idDataPembeli; private String[] namaDataPembeli, alamatDataPembeli, noHpDataPembeli; private ArrayList&lt;DataPembeli&gt; dataPembeliItems; private DataPembeliListAdapter adapter; public DataPembeliFragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_data_pembeli, container, false); listPembeli = (ListView) rootView.findViewById(R.id.list_sliderdata); btnTambah = (ImageButton) rootView.findViewById(R.id.btnTambah); btnTambah.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { showEditDialog(); } }); dataPembeliItems = new ArrayList&lt;DataPembeli&gt;(); idDataPembeli = new int[10]; namaDataPembeli = new String[10]; alamatDataPembeli = new String[10]; noHpDataPembeli = new String[10]; idDataPembeli[0] = 1; namaDataPembeli[0] = "ryno"; alamatDataPembeli[0]= "padang"; noHpDataPembeli[0] = "0812874512"; dataPembeliItems.add(new DataPembeli(idDataPembeli[0], namaDataPembeli[0], alamatDataPembeli[0], noHpDataPembeli[0])); idDataPembeli[1] = 2; namaDataPembeli[1] = "yezu"; alamatDataPembeli[1]= "padang"; noHpDataPembeli[1] = "0819232211"; dataPembeliItems.add(new DataPembeli(idDataPembeli[1], namaDataPembeli[1], alamatDataPembeli[1], noHpDataPembeli[1])); idDataPembeli[2] = 3; namaDataPembeli[2] = "test"; alamatDataPembeli[2]= "padangs"; noHpDataPembeli[2] = "0819232xx"; dataPembeliItems.add(new DataPembeli(idDataPembeli[2], namaDataPembeli[2], alamatDataPembeli[2], noHpDataPembeli[2])); listPembeli.setOnItemClickListener(new SlideMenuClickListener()); adapter = new DataPembeliListAdapter(getActivity().getApplicationContext(),dataPembeliItems); listPembeli.setAdapter(adapter); return rootView; } </code></pre> <p>}</p> <p>When I call the Fragment I got <code>ResourceNotFoundException</code> in the logcat at DataPembeliAdapter on the line that I marked above.(at comment "//THIS IS THE ERROR LINE")</p>
3
1,219
Adding a Trailing Twelve Months array feature to VBA code
<p>I have an existing code which is a function that yields an array: Example input: <code>=cellrange(B5,"ytd")</code> [where from <code>B5</code> and below (or above) there are dates] Example output: <code>$B$129:$B$280</code> which is the full date range for this year in column <code>B</code></p> <p>I am trying to add a new <code>case</code> called <code>ttm</code> (trailing twelve months), however I am struggling to find a way to incorporate it.</p> <p>The <code>ttm</code> case should show yield a trailing 12 months range from the latest available date</p> <pre><code>Option Explicit Public Function cellrange(rDates As Range, vFilter As Variant, Optional colOffsetA As Variant, Optional colOffsetB As Variant) As String 'DESCRIPTION: 'This function takes any cell value in a row and a input: YTD, ALL, or any year (i.e. 2014, 2015) and it finds the range in which the date is situated Dim i As Long, ndx1 As Long, ndx2 As Long, r As Range, vA As Variant, bErr As Boolean, bAll As Boolean bErr = True If IsDate(rDates) Then With rDates.EntireColumn i = rDates.Parent.Evaluate("count(" &amp; .Address &amp; ")") Set r = .Cells(1 - i + rDates.Parent.Evaluate("index(" &amp; .Address &amp; ",match(9.9E+307," &amp; .Address &amp; "))").row).Resize(i, 1) End With vA = r.Value If IsMissing(colOffsetA) And IsMissing(colOffsetB) Then colOffsetA = 0: colOffsetB = 0 End If If IsMissing(colOffsetB) = True Then colOffsetB = colOffsetA Select Case LCase(vFilter) Case "all" bErr = 0: bAll = 1 Set r = r.Range(r.Parent.Cells(1, 1 + colOffsetA), r.Parent.Cells(r.Count, 1 + colOffsetB)) Case "ytd" For i = 1 To UBound(vA) If ndx1 = 0 And Year(vA(i, 1)) = Year(Date) Then ndx1 = i If vA(i, 1) &lt;= Date Then ndx2 = i Next Case Else 'year vFilter = Val(vFilter) If vFilter Then For i = 1 To UBound(vA) If ndx1 = 0 And Year(vA(i, 1)) = vFilter Then ndx1 = i If ndx1 And Year(vA(i, 1)) = vFilter Then ndx2 = i Next End If End Select If Not bAll Then If ndx1 &gt; 0 And ndx2 &gt; 0 Then Set r = r.Range(r.Parent.Cells(ndx1, 1 + colOffsetA), r.Parent.Cells(ndx2, 1 + colOffsetB)): bErr = False If Not bErr Then cellrange = r.Address Else cellrange = CVErr(xlErrValue) Else cellrange = CVErr(xlErrValue) 'check if this is the correct error handling End If End Function </code></pre>
3
1,233
In CSS Grid how to remove column 1's matching height of column 2?
<p>Not familiar with CSS Grid I'm trying to create a two column layout. Per reading tutorials it was suggested to use <code>minmax()</code> but for some reason I cannot figure out how to break column 1's full height that matches column 2, example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: grid; grid-template-columns: minmax(0, 1fr) 300px; column-gap:32px; } .col1 { background:red; padding:32px; } .col2 { background:orange; padding:32px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="col1"&gt;Bacon ipsum dolor amet boudin andouille pig beef, prosciutto tongue ball tip cow ham. Ground round salami tenderloin, biltong tail pastrami pork shoulder pork loin. Picanha cow ribeye meatloaf tri-tip pork chop burgdoggen salami beef chuck alcatra swine ground round. Tail doner tri-tip flank brisket prosciutto chislic capicola meatloaf picanha swine. Shankle capicola venison beef boudin, strip steak alcatra bacon sirloin cupim spare ribs short ribs kielbasa pork loin ground round. Leberkas short loin boudin meatloaf.&lt;/div&gt; &lt;div class="col2"&gt;Kielbasa pastrami tenderloin, turkey short loin pork loin swine fatback flank leberkas prosciutto hamburger t-bone drumstick. Jowl picanha ham, t-bone filet mignon short ribs turducken leberkas. Turducken ham hock alcatra, shoulder tail sirloin strip steak hamburger picanha jerky tenderloin spare ribs tri-tip. Tenderloin prosciutto picanha, capicola kevin pig biltong t-bone pork chop boudin porchetta bacon salami chicken fatback. Ham hock pancetta tail tenderloin jerky ground round chislic frankfurter shank picanha pork belly strip steak pork chop. Short loin andouille biltong corned beef pig pork chop pork bacon tri-tip jerky. Filet mignon meatloaf drumstick hamburger ham hock landjaeger tri-tip ribeye swine. Ham shankle tongue, kielbasa swine burgdoggen tenderloin beef ribs buffalo meatball hamburger leberkas picanha t-bone. Beef ribs ball tip ham pork loin capicola filet mignon. Hamburger sausage shoulder meatball pork chop tail spare ribs, fatback burgdoggen drumstick short loin swine pork loin. Kielbasa boudin cow beef beef ribs tongue pork chop frankfurter sausage burgdoggen. Flank landjaeger leberkas spare ribs alcatra, swine corned beef boudin shoulder pig prosciutto pancetta pork chop. Pork chop turducken andouille filet mignon alcatra porchetta cupim tri-tip cow tongue beef meatball doner. Beef ribs ham hock chuck shank doner. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>after research and reading &quot;<a href="https://alligator.io/css/css-grid-layout-minmax-function/" rel="nofollow noreferrer">CSS Grid Layout: The Minmax Function</a>&quot; I tried:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: grid; grid-template-columns: minmax(min-content, max-content) 300px; column-gap:32px; } .col1 { background:red; padding:32px; } .col2 { background:orange; padding:32px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="col1"&gt;Bacon ipsum dolor amet boudin andouille pig beef, prosciutto tongue ball tip cow ham. Ground round salami tenderloin, biltong tail pastrami pork shoulder pork loin. Picanha cow ribeye meatloaf tri-tip pork chop burgdoggen salami beef chuck alcatra swine ground round. Tail doner tri-tip flank brisket prosciutto chislic capicola meatloaf picanha swine. Shankle capicola venison beef boudin, strip steak alcatra bacon sirloin cupim spare ribs short ribs kielbasa pork loin ground round. Leberkas short loin boudin meatloaf.&lt;/div&gt; &lt;div class="col2"&gt;Kielbasa pastrami tenderloin, turkey short loin pork loin swine fatback flank leberkas prosciutto hamburger t-bone drumstick. Jowl picanha ham, t-bone filet mignon short ribs turducken leberkas. Turducken ham hock alcatra, shoulder tail sirloin strip steak hamburger picanha jerky tenderloin spare ribs tri-tip. Tenderloin prosciutto picanha, capicola kevin pig biltong t-bone pork chop boudin porchetta bacon salami chicken fatback. Ham hock pancetta tail tenderloin jerky ground round chislic frankfurter shank picanha pork belly strip steak pork chop. Short loin andouille biltong corned beef pig pork chop pork bacon tri-tip jerky. Filet mignon meatloaf drumstick hamburger ham hock landjaeger tri-tip ribeye swine. Ham shankle tongue, kielbasa swine burgdoggen tenderloin beef ribs buffalo meatball hamburger leberkas picanha t-bone. Beef ribs ball tip ham pork loin capicola filet mignon. Hamburger sausage shoulder meatball pork chop tail spare ribs, fatback burgdoggen drumstick short loin swine pork loin. Kielbasa boudin cow beef beef ribs tongue pork chop frankfurter sausage burgdoggen. Flank landjaeger leberkas spare ribs alcatra, swine corned beef boudin shoulder pig prosciutto pancetta pork chop. Pork chop turducken andouille filet mignon alcatra porchetta cupim tri-tip cow tongue beef meatball doner. Beef ribs ham hock chuck shank doner. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>So far I'm not finding a resolution in my search query or after reading:</p> <ul> <li><a href="https://stackoverflow.com/questions/49636862/remove-wide-gaps-in-css-grid">Remove wide gaps in CSS Grid</a></li> <li><a href="https://stackoverflow.com/questions/55434774/is-it-possible-to-remove-the-height-from-empty-rows-in-grid-with-grid-template">Is it possible to remove the height from empty rows in grid with <code>grid-template-areas</code>?</a></li> <li><a href="https://stackoverflow.com/questions/61471820/why-cant-i-remove-all-the-deadspace-from-css-grid-layout">Why can't I remove all the deadspace from CSS Grid Layout?</a></li> <li><a href="https://stackoverflow.com/questions/54754492/how-to-hide-overflow-part-of-column-in-css-grid-layout-with-specified-row-height">How to hide overflow part of column in css grid layout with specified row height?</a></li> <li><a href="https://stackoverflow.com/questions/51616903/css-grid-white-space-on-the-bottom-and-how-to-remove-it">CSS Grid - White space on the bottom and how to remove it</a></li> <li><a href="https://stackoverflow.com/questions/51962136/why-is-my-grid-elements-height-not-being-calculated-correctly">Why is my Grid element's height not being calculated correctly?</a></li> </ul> <p>With CSS Grid how can I remove column 1's matching height of column 2?</p>
3
2,229
Fail to load ApplicationContext SpringBoot with SpringSecurity and JUnit Jupiter
<p>I'm working on a REST API using Spring Boot. Currently, the V1 of the API is complete. So, I'm implementing Spring Security to manage authentication and authorization.<br /> Since I've implemented Spring Security, my JUnit Jupiter tests does not work (no one works).</p> <p>I searched a lot a solution on internet, but all answers I found are for JUnit4 and not JUnit5 (so I don't have all required classes).<br /> I got the classical &quot;Fail to load ApplicationContext&quot; error, but I don't know how to solve it.</p> <p>Can you help me?</p> <p>Here is my code for one class (UserController):</p> <p>gradle.build:</p> <pre><code>plugins { id 'jacoco' id 'org.springframework.boot' version '2.6.0' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '11' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web:2.5.6' implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.6' implementation 'org.projectlombok:lombok:1.18.22' annotationProcessor 'org.projectlombok:lombok:1.18.22' developmentOnly 'org.springframework.boot:spring-boot-devtools:2.5.6' testImplementation 'org.springframework.boot:spring-boot-starter-test:2.5.6' implementation 'com.h2database:h2' runtimeOnly 'com.h2database:h2' } test { systemProperty 'spring.profiles.active', 'test' useJUnitPlatform() finalizedBy jacocoTestReport } </code></pre> <p>Application:</p> <pre class="lang-java prettyprint-override"><code>@SpringBootApplication public class BackendApplication { public static void main(String[] args) { SpringApplication.run(BackendApplication.class, args); } } </code></pre> <p>UserController sample:</p> <pre class="lang-java prettyprint-override"><code>@RestController @RequestMapping(&quot;/api/v1/users&quot;) public class UserController extends AbstractCrudController&lt;User, Long&gt; { @Autowired public UserController(CrudService&lt;User, Long&gt; service) { super(service); } @GetMapping(&quot;&quot;) @Override @Secured({ &quot;ROLE_XXXXX&quot; }) public ResponseEntity&lt;ResponseListDto&lt;User, Long&gt;&gt; findAll() { return super.findAll(); } // ... } </code></pre> <p>MockedUserControllerTest sample:</p> <pre class="lang-java prettyprint-override"><code>@SpringBootTest public class MockedUserControllerTest { @Mock private UserService service; @InjectMocks private UserController controller; private static User user; private static List&lt;User&gt; users; @BeforeAll public static void beforeAll() { user = new User(); user.setId(1L); user.setUsername(&quot;A user name&quot;); user.setFirstname(&quot;First-Name&quot;); user.setLastname(&quot;Last-Name&quot;); user.setPassword(&quot;A Gre4t P4ssw0rd!&quot;); user.setMail(&quot;first-name.last-name@mail.com&quot;); user.setBirthDate(Date.valueOf(&quot;1980-01-15&quot;)); user.setKey(&quot;A-key&quot;); user.setNewsletter(Boolean.TRUE); users = List.of(user); } @Test public void testFindAll() { when(service.findAll()).thenReturn(users); assertEquals(new ResponseEntity&lt;&gt;(new ResponseListDto&lt;&gt;(users, null, null), HttpStatus.OK), controller.findAll()); } //... } </code></pre> <p>Thank you in advance for looking my problem.</p>
3
1,418
Add a second field category Prestashop 1.7
<p>I am trying to add a editable field for Category in Prestashop 1.7</p> <p>I'm already do this :</p> <p>Insert text_SEO in Database</p> <p><strong>override/classes/Category.php</strong></p> <pre><code>&lt;?php class Category extends CategoryCore { public $text_SEO; // My Custom field public static $definition = array( 'table' =&gt; 'category', 'primary' =&gt; 'id_category', 'multilang' =&gt; true, 'multilang_shop' =&gt; true, 'fields' =&gt; array( 'nleft' =&gt; array('type' =&gt; self::TYPE_INT, 'validate' =&gt; 'isUnsignedInt'), 'nright' =&gt; array('type' =&gt; self::TYPE_INT, 'validate' =&gt; 'isUnsignedInt'), 'level_depth' =&gt; array('type' =&gt; self::TYPE_INT, 'validate' =&gt; 'isUnsignedInt'), 'active' =&gt; array('type' =&gt; self::TYPE_BOOL, 'validate' =&gt; 'isBool', 'required' =&gt; true), 'id_parent' =&gt; array('type' =&gt; self::TYPE_INT, 'validate' =&gt; 'isUnsignedInt'), 'id_shop_default' =&gt; array('type' =&gt; self::TYPE_INT, 'validate' =&gt; 'isUnsignedId'), 'is_root_category' =&gt; array('type' =&gt; self::TYPE_BOOL, 'validate' =&gt; 'isBool'), 'position' =&gt; array('type' =&gt; self::TYPE_INT), 'date_add' =&gt; array('type' =&gt; self::TYPE_DATE, 'validate' =&gt; 'isDate'), 'date_upd' =&gt; array('type' =&gt; self::TYPE_DATE, 'validate' =&gt; 'isDate'), // Lang fields 'name' =&gt; array('type' =&gt; self::TYPE_STRING, 'lang' =&gt; true, 'validate' =&gt; 'isCatalogName', 'required' =&gt; true, 'size' =&gt; 64), 'link_rewrite' =&gt; array('type' =&gt; self::TYPE_STRING, 'lang' =&gt; true, 'validate' =&gt; 'isLinkRewrite', 'required' =&gt; true, 'size' =&gt; 64), 'description' =&gt; array('type' =&gt; self::TYPE_HTML, 'lang' =&gt; true, 'validate' =&gt; 'isString'), 'text_SEO' =&gt; array('type' =&gt; self::TYPE_HTML, 'lang' =&gt; true, 'validate' =&gt; 'isString'), 'meta_title' =&gt; array('type' =&gt; self::TYPE_STRING, 'lang' =&gt; true, 'validate' =&gt; 'isGenericName', 'size' =&gt; 128), 'meta_description' =&gt; array('type' =&gt; self::TYPE_STRING, 'lang' =&gt; true, 'validate' =&gt; 'isGenericName', 'size' =&gt; 255), 'meta_keywords' =&gt; array('type' =&gt; self::TYPE_STRING, 'lang' =&gt; true, 'validate' =&gt; 'isGenericName', 'size' =&gt; 255), ), ); } </code></pre> <p><strong>override/controllers/admin/AdminCategoriesController.php</strong></p> <pre><code> class AdminCategoriesController extends AdminCategoriesControllerCore { public function renderForm() { $this-&gt;fields_form_override =array( array( 'type' =&gt; 'textarea', 'label' =&gt; $this-&gt;l('Text SEO'), 'name' =&gt; 'text_SEO', 'lang' =&gt; true, 'autoload_rte' =&gt; true, 'hint' =&gt; $this-&gt;l('Invalid characters:').' &lt;&gt;;=#{}', ), ); return parent::renderForm(); } } </code></pre> <p>How can I display the areatext ?</p> <p>Thank you ! :D</p>
3
1,477
Stuck Scraping Multiple Domains sequentially - Python Scrapy
<p>I am fairly new to python as well as web scraping. My first project is web scraping random Craiglist cities (5 cities total) under the transportation sub-domain (i.e. <a href="https://dallas.craigslist.org" rel="nofollow noreferrer">https://dallas.craigslist.org</a>), though I am stuck on having to manually run the script per city after manually updating each cities respective domain under the constants >>>> (start_urls = and absolute_next_url = ) in the script . Is there anyway that I can adjust the script to sequentially run through the cities I have defined (i.e. miami, new york, houston, chicago, etc), and auto-populate the constants for its respective city (start_urls = and absolute_next_url = ) ?</p> <p>Also, is there a way to adjust the script to output each city into its own .csv >> (i.e. miami.csv, houston.csv, chicago.csv, etc) ? </p> <p>Thank you in advance</p> <pre><code># -*- coding: utf-8 -*- import scrapy from scrapy import Request class JobsSpider(scrapy.Spider): name = "jobs" allowed_domains = ["craigslist.org"] start_urls = ['https://dallas.craigslist.org/d/transportation/search/trp'] def parse(self, response): jobs = response.xpath('//p[@class="result-info"]') for job in jobs: listing_title = job.xpath('a/text()').extract_first() city = job.xpath('span[@class="result-meta"]/span[@class="result-hood"]/text()').extract_first("")[2:-1] job_posting_date = job.xpath('time/@datetime').extract_first() job_posting_url = job.xpath('a/@href').extract_first() data_id = job.xpath('a/@data-id').extract_first() yield Request(job_posting_url, callback=self.parse_page, meta={'job_posting_url': job_posting_url, 'listing_title': listing_title, 'city':city, 'job_posting_date':job_posting_date, 'data_id':data_id}) relative_next_url = response.xpath('//a[@class="button next"]/@href').extract_first() absolute_next_url = "https://dallas.craigslist.org" + relative_next_url yield Request(absolute_next_url, callback=self.parse) def parse_page(self, response): job_posting_url = response.meta.get('job_posting_url') listing_title = response.meta.get('listing_title') city = response.meta.get('city') job_posting_date = response.meta.get('job_posting_date') data_id = response.meta.get('data_id') description = "".join(line for line in response.xpath('//*[@id="postingbody"]/text()').extract()).strip() compensation = response.xpath('//p[@class="attrgroup"]/span[1]/b/text()').extract_first() employment_type = response.xpath('//p[@class="attrgroup"]/span[2]/b/text()').extract_first() latitude = response.xpath('//div/@data-latitude').extract_first() longitude = response.xpath('//div/@data-longitude').extract_first() posting_id = response.xpath('//p[@class="postinginfo"]/text()').extract() #yield{'job_posting_url': job_posting_url, 'listing_title': listing_title, 'city':city, 'job_posting_date':job_posting_date, 'description':description, #'compensation':compensation, 'employment_type':employment_type, 'posting_id':posting_id, 'longitude':longitude, 'latitude':latitude } yield{'job_posting_url':job_posting_url, 'data_id':data_id, 'listing_title':listing_title, 'city':city, 'description':description, 'compensation':compensation, 'employment_type':employment_type, 'latitude':latitude, 'longitude':longitude, 'job_posting_date':job_posting_date, 'posting_id':posting_id, 'data_id':data_id } </code></pre>
3
1,590
How to serialize json to sql?
<p>I have a list of words and I should send requests to an API and get the information about the words. I want to convert the API data which is in JSON format to SQL(my DB is PostgreSQL) format in Django. How can I do that? Do you know any good source to learn to serialize json to sql? I have just started learning Django.</p> <p>It is the API's JSON data:</p> <pre><code> [ { &quot;word&quot;: &quot;hello&quot;, &quot;phonetics&quot;: [ { &quot;text&quot;: &quot;/həˈloʊ/&quot;, &quot;audio&quot;: &quot;https://lex-audio.useremarkable.com/mp3/hello_us_1_rr.mp3&quot; }, { &quot;text&quot;: &quot;/hɛˈloʊ/&quot;, &quot;audio&quot;: &quot;https://lex-audio.useremarkable.com/mp3/hello_us_2_rr.mp3&quot; } ], &quot;meanings&quot;: [ { &quot;partOfSpeech&quot;: &quot;exclamation&quot;, &quot;definitions&quot;: [ { &quot;definition&quot;: &quot;Used as a greeting or to begin a phone conversation.&quot;, &quot;example&quot;: &quot;hello there, Katie!&quot; } ] }, { &quot;partOfSpeech&quot;: &quot;noun&quot;, &quot;definitions&quot;: [ { &quot;definition&quot;: &quot;An utterance of “hello”; a greeting.&quot;, &quot;example&quot;: &quot;she was getting polite nods and hellos from people&quot;, &quot;synonyms&quot;: [ &quot;greeting&quot;, &quot;welcome&quot;, &quot;salutation&quot;, &quot;saluting&quot;, &quot;hailing&quot;, &quot;address&quot;, &quot;hello&quot;, &quot;hallo&quot; ] } ] }, { &quot;partOfSpeech&quot;: &quot;intransitive verb&quot;, &quot;definitions&quot;: [ { &quot;definition&quot;: &quot;Say or shout “hello”; greet someone.&quot;, &quot;example&quot;: &quot;I pressed the phone button and helloed&quot; } ] } ] } ] </code></pre> <p>this is my models.py:</p> <pre><code>class Words(models.Model): word = models.CharField(max_length=50) american_phonetic= models.CharField(max_length=50) american_audio= models.URLField(max_length = 200) british_phonetic= models.CharField(max_length=50) british_audio= models.URLField(max_length = 200) ########################################################################### class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField('birth date') field= models.CharField(max_length=50) location = models.CharField(max_length=30, blank=True) interest= models.IntegerField() # for example : 1 for science , 2 for art , 3 for sport etc. education= models.IntegerField() # for example : 1 for highschool , 2 for bachelor , 3 for master and 4 for phd @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class UserLearned(models.Model): Profile_id = models.ForeignKey(Profile, on_delete=models.CASCADE) word_id = models.ForeignKey(Words, models.SET_NULL, blank=True, null=True,) def __str__(self): return self.word_id ############################################################################ class Meanings(models.Model): word_id = models.ForeignKey(Words, on_delete=models.CASCADE) partOfSpeech = models.CharField(max_length=30) class Definitions(models.Model): word_id = models.ForeignKey(Words, on_delete=models.CASCADE) Meaning_id = models.OneToOneField(Meanings, on_delete=models.CASCADE, primary_key=True) definition = models.TextField() def __str__(self): return self.definition class Examples(models.Model): word_id = models.ForeignKey(Words, on_delete=models.CASCADE) Meaning_id = models.OneToOneField(Meanings, on_delete=models.CASCADE, primary_key=True) example = models.TextField() def __str__(self): return self.example class Synonyms(models.Model): word_id = models.ForeignKey(Words, on_delete=models.CASCADE) Meaning_id = models.ForeignKey(Meanings, on_delete=models.CASCADE) synonym = models.CharField(max_length=50) def __str__(self): return self.synonym </code></pre>
3
2,124
Espresso Test : app:compileDebugAndroidTestKotlin FAILED with Unresolved reference: PopupBackgroundView
<p>I recorded an EspressoTest in which I test values in spinner :</p> <pre><code>&lt;LinearLayout android:id=&quot;@+id/linearLayoutSeedlingsTypes&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;40dp&quot;&gt; &lt;androidx.cardview.widget.CardView android:layout_width=&quot;180dp&quot; android:layout_height=&quot;wrap_content&quot; app:cardCornerRadius=&quot;20dp&quot; android:innerRadius=&quot;0dp&quot; android:shape=&quot;ring&quot; android:thicknessRatio=&quot;1.9&quot; android:backgroundTint=&quot;@color/green&quot; android:background=&quot;@color/green&quot;&gt; &lt;Spinner android:id=&quot;@+id/fas_spinner_types&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;30dp&quot; android:layout_marginLeft=&quot;@dimen/default_margin&quot; android:layout_marginStart=&quot;@dimen/default_margin&quot; android:entries=&quot;@array/seedlings_types&quot; android:spinnerMode=&quot;dropdown&quot; /&gt; </code></pre> <p>It generated the following Kotlin class :</p> <pre><code>@LargeTest @RunWith(AndroidJUnit4::class) class AddNominalTest { @Rule @JvmField var mActivityTestRule = ActivityTestRule(MainActivity::class.java) @Test fun addNominal() { //... val materialTextView = onData(anything()) .inAdapterView( childAtPosition( withClassName(`is`(&quot;android.widget.PopupWindow$PopupBackgroundView&quot;)),//compile error ! 0 ) ) .atPosition(1) materialTextView.perform(click()) //... </code></pre> <p>I have the following error at compile in <strong>app:compileDebugAndroidTestKotlin : Unresolved reference: PopupBackgroundView</strong></p> <p>Any idea about this error ?</p>
3
1,029
Back/Up Arrow not working when using navigation drawer
<p>The back or up button is not working when using a navigation drawer. The icon changes from a hamburger (having set the top level destinations) but both open the navigation drawer. I want the back/up arrow to go back in the stack.</p> <p>public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, DrawerLocker {</p> <pre><code>public static final String TAG = MainActivity.class.getSimpleName(); private DrawerLayout drawerLayout; private NavigationView navView; private Toolbar toolbar; private NavController navController; private ActionBarDrawerToggle drawerToggle; private AppBarConfiguration appBarConfiguration; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); //configure drawer layout drawerLayout = findViewById(R.id.drawer_layout); navView = findViewById(R.id.drawer_navigation_view); navController = Navigation.findNavController(this,R.id.nav_host_fragment); appBarConfiguration = new AppBarConfiguration.Builder(R.id.scenarioListFragment, R.id.tokenListFragment, R.id.settingsFragment,R.id.historyFragment) .setDrawerLayout(drawerLayout) .build(); NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration); NavigationUI.setupWithNavController(navView, navController); navView.setNavigationItemSelectedListener(this); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawerLayout.addDrawerListener(drawerToggle); drawerToggle.syncState(); if (savedInstanceState == null ) { navView.setCheckedItem(R.id.drawer_menu_scenario); toolbar.setTitle(&quot;Scenarios&quot;); } } </code></pre> <p>I watched <a href="https://www.youtube.com/watch?v=wv5VFEcnb-8" rel="nofollow noreferrer">this video</a>, which made it seem sort of simple, but it is referring to Kotlin and my code is not far off.</p> <p><a href="https://stackoverflow.com/questions/56219768/toolbars-back-button-not-working-when-using-with-navigation-drawer">This post</a> covers a similar challenge as well, though in Kotlin I tried adding a setNavigationOnClickListener and put a logd statement in it. It never got fired, but the solution itself seemed like it shouldn't be necessary.</p> <p><a href="https://stackoverflow.com/questions/60030589/how-to-make-up-button-go-back-instead-of-opening-navigation-drawer">This post</a> seems to have cover the same issue but there are no answers. One of the responses says to setupActionBarWithNavController, which I have:</p> <pre><code>NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration); </code></pre> <p>This function has a lot of overloads and I've tried a number of them, but they seem to cause me to lose the set of top level destinations (hamburger icon for multiple fragments) and undue my the navigation which is working.</p> <p>I tried to follow <a href="https://developer.android.com/guide/navigation/navigation-ui#add_a_navigation_drawer" rel="nofollow noreferrer">this documentation</a>, but it only seemed to step me back from where I was. This call:</p> <pre><code> AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()) .setDrawerLayout(drawerLayout) .build(); </code></pre> <p>Seems to replace the topLevelDestinations and use the navController.getGraph(), but since I have multiple ones, I have been referencing the <a href="https://developer.android.com/guide/navigation/navigation-ui#appbarconfiguration" rel="nofollow noreferrer">fragments themselves</a>.</p> <p>I did <a href="https://stackoverflow.com/questions/63525227/navigation-drawer-hamburger-menu-working-but-back-arrow-opens-the-drawer">ask</a> about this problem previously but it was clear to me I did not explain it well (answers addressed how to pop back and not why the back arrow was not working). I would have deleted it but people did answer and the guidance SO provided was that I should not delete it in that case. I am sorry if I caused confusion.</p>
3
1,364
Distribute values across subsequent rows in Postgresql
<p>I have two tables. One contains user state transitions.</p> <pre><code>create table state ( id serial primary key, ctime timestamp with time zone not null, state text not null ); insert into state (ctime, state) values ('2019-05-01 03:58:40+00', 'Busy') , ('2019-05-01 03:58:42+00', 'Ready') , ('2019-05-01 04:00:14+00', 'Busy') , ('2019-05-01 04:16:26+00', 'Ready') , ('2019-05-01 04:16:36+00', 'Busy') ; </code></pre> <p>And the other one contains user's actions.</p> <pre><code>create table action ( id serial primary key, ctime timestamp with time zone not null, action text not null ); insert into action (ctime, action) values ('2019-05-01 03:58:42+00', 'vasah') , ('2019-05-01 03:58:42+00', 'mituh') , ('2019-05-01 04:00:14+00', 'jumuf') , ('2019-05-01 04:00:16+00', 'vibaj') , ('2019-05-01 04:00:16+00', 'sasij') , ('2019-05-01 04:16:21+00', 'husih') , ('2019-05-01 04:16:26+00', 'radod') , ('2019-05-01 04:16:30+00', 'zadub') , ('2019-05-01 04:16:35+00', 'mimoh') , ('2019-05-01 04:16:36+00', 'rimoh') , ('2019-05-01 04:16:37+00', 'zahuf') , ('2019-05-01 04:16:37+00', 'fisak') ; </code></pre> <p>It is easy to union these tables and <strong>visually</strong> see in which state an action was performed.</p> <pre><code>select * from ( select ctime, state, null from state union all select ctime, null, action from action) x order by ctime; </code></pre> <p>Output:</p> <pre><code> 2019-05-01 06:58:40+03 | Busy | 2019-05-01 06:58:42+03 | | mituh 2019-05-01 06:58:42+03 | | vasah 2019-05-01 06:58:42+03 | Ready | 2019-05-01 07:00:14+03 | | jumuf 2019-05-01 07:00:14+03 | Busy | 2019-05-01 07:00:16+03 | | vibaj 2019-05-01 07:00:16+03 | | sasij 2019-05-01 07:16:21+03 | | husih 2019-05-01 07:16:26+03 | Ready | 2019-05-01 07:16:26+03 | | radod 2019-05-01 07:16:30+03 | | zadub 2019-05-01 07:16:35+03 | | mimoh 2019-05-01 07:16:36+03 | Busy | 2019-05-01 07:16:36+03 | | rimoh 2019-05-01 07:16:37+03 | | zahuf 2019-05-01 07:16:37+03 | | fisak </code></pre> <p>How can I &quot;fill the blanks&quot; so the output will be like this?</p> <pre><code> 2019-05-01 06:58:40+03 | Busy | 2019-05-01 06:58:42+03 | Busy | mituh 2019-05-01 06:58:42+03 | Busy | vasah 2019-05-01 06:58:42+03 | Ready | 2019-05-01 07:00:14+03 | Ready | jumuf 2019-05-01 07:00:14+03 | Busy | 2019-05-01 07:00:16+03 | Busy | vibaj 2019-05-01 07:00:16+03 | Busy | sasij 2019-05-01 07:16:21+03 | Busy | husih 2019-05-01 07:16:26+03 | Ready | 2019-05-01 07:16:26+03 | Ready | radod 2019-05-01 07:16:30+03 | Ready | zadub 2019-05-01 07:16:35+03 | Ready | mimoh 2019-05-01 07:16:36+03 | Busy | 2019-05-01 07:16:36+03 | Busy | rimoh 2019-05-01 07:16:37+03 | Busy | zahuf 2019-05-01 07:16:37+03 | Busy | fisak </code></pre>
3
1,335
Android sprite animation with BitmapRegionDecoder
<p>I'd like to animate a sprite. I select the current frame by BitmapRegionDecoder, but it causes native crash on some Anroid 6.0 devices (mainly on Samsung). I get this stack trace: </p> <blockquote> <hr> <p>Build fingerprint: 'samsung/zeroltexx/zerolte:6.0.1/MMB29K/G925FXXU4DPGW:user/release-keys' Revision: '10' ABI: 'arm64' pid: 10872, tid: 10872, name: .aff.index.main >>> com.aff.index.main &lt;&lt;&lt; signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x30 x0 0000000000000000 x1 0000000000000000 x2 0000000000000002 x3 0000000000000000 x4 0000000000000000 x5 00000000ffffffff x6 0000000000000000 x7 0000000000000000 x8 0000000000000000 x9 0000000000000000 x10 0000000000000000 x11 0000000000000000 x12 0000007f1d0fd5c8 x13 0000000000000002 x14 0000000000000000 x15 000000c8000000c5 x16 0000007f7931c5f8 x17 0000007f7925e3dc x18 0000000000000000 x19 0000000000000000 x20 0000007f7563d180 x21 0000000000000001 x22 0000000000000000 x23 0000000000000000 x24 0000000000000000 x25 0000000000000000 x26 00000000ffffffff x27 0000000000000000 x28 0000000000000000 x29 0000007fead6d070 x30 0000007f79264348 sp 0000007fead6d050 pc 0000007f7925e3dc pstate backtrace: #00 pc 00000000000f23dc /system/lib64/libandroid_runtime.so (_ZNK7android6Bitmap4infoEv) #01 pc 00000000000f8344 /system/lib64/libandroid_runtime.so (_ZN11GraphicsJNI12createBitmapEP7_JNIEnvPN7android6BitmapEiP11_jbyteArrayP8_jobjecti+60) #02 pc 0000000000104224 /system/lib64/libandroid_runtime.so #03 pc 0000000003f6b77c /system/framework/arm64/boot.oat (offset 0x2f37000)</p> </blockquote> <p>I call this runnable inside a View</p> <pre><code> @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); try { if (isInited &amp;&amp; region != null) canvas.drawBitmap(region, 0, 0, paint); } catch (Throwable t) { Timber.w(t, null); } } class AnimatePlaceholderRunnable implements Runnable { @Override public void run() { try { if (Build.VERSION.SDK_INT &lt; 10) return; if (!isAnimating) return; if ((top + height + empty) &lt;= maxTop) top = top + height + empty; else top = 0; bottom = top + height; src = new Rect(left, top, right, bottom); region = decoder.decodeRegion(src, null); invalidate(); postDelayed(placeholderRunnable, 41); } catch (Throwable t) { Timber.w(t, null); } } } </code></pre> <p>On many devices it runs well, e.g. on Nexus 6.0 with Android 7.0 or on a Sony XPeria Z1 with Android 5.x, but on my Samsung Galaxy S6 with Android 6.x my app crashes.</p>
3
1,206
Python Tkinter: Create a variable for each string inside a listbox?
<p>I'm (almost) a poor programmer-virgin so please go easy on me.</p> <p>This is my second attempt at making a program and this is turning out to be a bit more than I can navigate, I am afraid. I ask for your help after a long time of trying to solve this.</p> <p>I am basically making a ToDo-list but wanted it to have some more functionality than just being a boring list.</p> <p>How I imagine it in my head is that the user adds a task into an entry widget, which would then be displayed in a Listbox. Each string in the Listbox would then have a value associated with it (which I need to some calculations for the functionality I want the program to have). So what I think I kind of want is every string in the Listbox to be made a variable and then associated with that variable I want a value.</p> <p>I will try to show you:</p> <p>Here I am adding the string that I want to become a new variable</p> <p><a href="https://i.stack.imgur.com/0aKiZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0aKiZ.jpg" alt="Adding the string" /></a></p> <p>Then I specify a number from a drop down menu. I want this number to be the value of the variable/string from previous step.</p> <p><a href="https://i.stack.imgur.com/SuHsh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SuHsh.jpg" alt="Value that must be designated to the variable/string" /></a></p> <p>I really hope one of you can lead me in the right direction in a way that (preferably) doesn't require me to change things up too much. Things are still very slippery to me and it is already fairly hard for me to navigate the code. The purpose is simply that I want to do some calculations with the (hopefully) soon-to-be values associated with each task. Thanks in advance if any of you dare!</p> <p>The associated code is here:</p> <pre><code>import tkinter.messagebox # Import the messagebox module import pickle # Module to save to .dat import tkinter as tk root = tk.Tk() # root.title('SmaToDo') # Name of the program/window def new_task(): global entry_task global task_window task_window = Toplevel(root) task_window.title('Add a new task') task_label = tk.Label(task_window, text = 'Title your task concisely:', justify='center') task_label.pack() # Entry for tasks in new window entry_task = tkinter.Entry(task_window, width=50, justify='center') entry_task.pack() # Add task button in new window button_add_task = tkinter.Button(task_window, text='Add task', width=42, command=lambda: [add_task(), impact()]) button_add_task.pack() def add_task(): global task global impact_window task = entry_task.get() # we get the task from entry_task and we get the input from the entry_task type-field with .get() if task != '': # If textbox inputfield is NOT empty do this: listbox_tasks.insert(tkinter.END, task) entry_task.delete(0, tkinter.END) # Slet hvad der står i inputfeltet fra første bogstav til sidste (0, tkinter.END) task_window.destroy() else: tkinter.messagebox.showwarning(title='Whoops', message='You must enter a task') task_window.destroy() def delete_task(): try: task_index = listbox_tasks.curselection()[0] listbox_tasks.delete(task_index) except: tkinter.messagebox.showwarning(title='Oops', message='You must select a task to delete') def save_tasks(): tasks = listbox_tasks.get(0, listbox_tasks.size()) pickle.dump(tasks, open('tasks.dat', 'wb')) def prioritize_tasks(): pass # Create UI frame_tasks = tkinter.Frame(root) frame_tasks.pack() scrollbar_tasks = tkinter.Scrollbar(frame_tasks) scrollbar_tasks.pack(side=tkinter.RIGHT, fill=tkinter.Y) listbox_tasks = tkinter.Listbox(frame_tasks, height=10, width=50, justify='center') # tkinter.Listbox(where it should go, height=x, width=xx) listbox_tasks.pack() listbox_tasks.config(yscrollcommand=scrollbar_tasks.set) scrollbar_tasks.config(command=listbox_tasks.yview) try: tasks = pickle.load(open('tasks.dat', 'rb')) listbox_tasks.delete(0, tkinter.END) for task in tasks: listbox_tasks.insert(tkinter.END, task) except: tkinter.messagebox.showwarning(title='Phew', message='You have no tasks') # Add task button button_new_task = tkinter.Button(root, text='New task', width=42, command=new_task) button_new_task.pack() button_delete_task = tkinter.Button(root, text='Delete task', width=42, command=delete_task) button_delete_task.pack() button_save_tasks = tkinter.Button(root, text='Save tasks', width=42, command=save_tasks) button_save_tasks.pack() button_prioritize_tasks = tkinter.Button(root, text='Prioritize', width=42, command=prioritize_tasks) button_prioritize_tasks.pack() root.mainloop() </code></pre>
3
1,674
WPF Custom DependencyProperty Binding - SetValue set correct value but binded property set receive null
<p>I have issue with custom DependencyProperty in my control. Let me explain:</p> <p>I have control with list of the checkable items. I need property binding to the IEnumerable SelectedItems. The logic of SelectedItemsProperty filling is inside of control, so it is not just simple binding. Here is code behind of my control:</p> <pre><code> public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems", typeof(IEnumerable&lt;object&gt;), typeof(ButtonColumnFilter)); public IEnumerable&lt;object&gt; SelectedItems { get { return (IEnumerable&lt;object&gt;)GetValue(SelectedItemsProperty); } set { Debug.WriteLine("SelectedItems has been set in ButtonColumnFilter - Count:{0}", value?.Count()); SetValue(SelectedItemsProperty, value); } } </code></pre> <p>Here I get Debug message with correct number of selected items, so my logic inside of control is working well. The property in XAML is binded here:</p> <pre><code> &lt;MESControls:ButtonColumnFilter CanSearch="True" CanSort="False" DisplayMemberPath="DisplayName" ItemsSource="{Binding Path=FilterAdapter.Drivers, Mode=OneWay, IsAsync=True}" OnApplyFilter="Drivers_ApplyFilter" SelectedItems="{Binding Path=SelectedFilterDrivers, Mode=TwoWay}"/&gt; </code></pre> <p>And property is defined in my code here:</p> <pre><code>public IEnumerable&lt;Driver&gt; SelectedFilterDrivers { get =&gt; _SelectedFilterDrivers; set { Debug.WriteLine("SelectedFilterDrivers has been set in PlannerFilterAdapter - Count: {0}", value?.Count()); if (_SelectedFilterDrivers != value) { _SelectedFilterDrivers = value; NotifyPropertyChanged("SelectedFilterDrivers"); } } } </code></pre> <p>!!! But here I get Debug message 'value == null' !!!</p> <p>The binding is working well, and property set is called correctly in time i suppose. The weird is, that SetValue inside control has correct value, but outside in code the propert set value is null.</p> <p>What can be wrong? Thanks.</p> <p>UPDATE:</p> <p>Here is code that changes SelectedItems inside control:</p> <pre><code>private void CheckableItem_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsChecked" &amp;&amp; !_IsChecking) { _IsChecking = true; CheckableItem item = sender as CheckableItem; if(item.IsChecked == true &amp;&amp; InnerItemsSource.Where(ci=&gt;ci.Item.ToString() != SELECTALL).All(ci=&gt;ci.IsChecked == true)) { InnerItemsSource.Single(ci =&gt; ci.Item.ToString() == SELECTALL).IsChecked = true; SelectAllIsSelected = true; } else if (InnerItemsSource.Where(ci =&gt; ci.Item.ToString() != SELECTALL).All(ci=&gt;ci.IsChecked == true) || InnerItemsSource.Where(ci =&gt; ci.Item.ToString() != SELECTALL).All(ci =&gt; ci.IsChecked == false)) { InnerItemsSource.Single(ci =&gt; ci.Item.ToString() == SELECTALL).IsChecked = false; SelectAllIsSelected = false; } else { InnerItemsSource.Single(ci =&gt; ci.Item.ToString() == SELECTALL).IsChecked = null; SelectAllIsSelected = false; } SelectedItems = CheckedItems; NotifyPropertyChanged("IsFilterUsed"); NotifyPropertyChanged("FilterIcon"); } _IsChecking = false; } public IEnumerable&lt;object&gt; CheckedItems { get { return InnerItemsSource?.Where(ci =&gt; ci.IsChecked == true &amp;&amp; ci.Item.ToString() != SELECTALL).Select(ci =&gt; ci.Item); } } </code></pre> <p>But as I written, the property set inside control receive correct value and I guess correct type. The return value of CheckedItems is IEnumerable'&lt;<em>object</em>>'.</p> <p>Thanks for help.</p> <p><a href="https://i.stack.imgur.com/HGbUK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HGbUK.png" alt="value is IEnumerable&lt;Driver&gt;"></a></p> <p>Call stack situation</p> <p>Here is visible count of the collection just one step back in the call stack <a href="https://i.stack.imgur.com/hkQcV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hkQcV.png" alt="Here is visible count of the collection just one step back in the call stack"></a></p> <p>Next step of call stack - breakpoint - value is null <a href="https://i.stack.imgur.com/aLMkR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aLMkR.png" alt="Next step of call stack - breakpoint - value is null"></a> The true is, that between theses steps is some external code - but I didn't get any error neither warning <a href="https://i.stack.imgur.com/F1fLt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F1fLt.png" alt="The true is, that between theses steps is some external code - but I didn&#39;t get any error neither warning"></a></p> <p>UPDATE - some progress</p> <p>I tried change public IEnumerable&lt;<em>Driver</em>> SelectedFilterDrivers to </p> <pre><code>public IEnumerable&lt;object&gt; SelectedFilterDrivers { get =&gt; _SelectedFilterDrivers; set { Debug.WriteLine("SelectedFilterDrivers has been set in PlannerFilterAdapter - Count: {0}", value?.Count()); if (_SelectedFilterDrivers != value) { _SelectedFilterDrivers = (IEnumerable&lt;Driver&gt;)value; NotifyPropertyChanged("SelectedFilterDrivers"); } } } </code></pre> <p>And I receive correct number of items. So there is an issue during retyping of items in collection. So I need to kick forward with the better way, how to keep ability for SelectedItems to use generic IEnumerable&lt;<em>object</em>> </p> <p>Important is, that IEnumerable&lt;<em>object</em>> is working well with simple binding (in this case ItemsSource - true is, that it si just OneWay binding)</p>
3
2,624
CSS animation-delay timing
<p>I took this example code from JSFiddle and played with it, but there is code confusing me</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.backgroundimg { -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; position: absolute; top: 0; left: 0; height: 100%; width: 100%; } #back5 { background: url("http://duananhalotus.com/upload/album/0904234.jpg") no-repeat center fixed; z-index: -1; } #back4 { background: url("http://www.chinadaily.com.cn/world/images/attachement/jpg/site1/20120806/d4bed9d534551189e67329.jpg") no-repeat center fixed; z-index: -1; } #back3 { background: url("https://amazingslider.com/wp-content/uploads/2012/12/dandelion.jpg") no-repeat center fixed; z-index: -1; } #back2 { background: url("https://cdn.pixabay.com/photo/2013/04/06/11/50/image-editing-101040_960_720.jpg") no-repeat center fixed; z-index: -1; } #back1 { background: url("http://www.gettyimages.com/gi-resources/images/Embed/new/embed2.jpg") no-repeat center fixed; z-index: -1; } @keyframes backgroundchangeFadeInOut { 0% { opacity:1; } 17% { opacity:1; } 25% { opacity:0; } 92% { opacity:0; } 100% { opacity:1; } } @-webkit-keyframes backgroundchangeFadeInOut { 0% { opacity:1; } 17% { opacity:1; } 25% { opacity:0; } 92% { opacity:0; } 100% { opacity:1; } } #backgroundchange div:nth-of-type(1) { animation-delay: 8s; -webkit-animation-delay: 8s; } #backgroundchange div:nth-of-type(2) { animation-delay: 6s; -webkit-animation-delay: 6s; } #backgroundchange div:nth-of-type(3) { animation-delay: 4s; -webkit-animation-delay: 4s; } #backgroundchange div:nth-of-type(4) { animation-delay: 2s; -webkit-animation-delay: 2s; } #backgroundchange div:nth-of-type(5) { animation-delay: 0; -webkit-animation-delay: 0; } #backgroundchange div { animation-name: backgroundchangeFadeInOut; animation-timing-function: ease-in-out; animation-iteration-count: infinite; animation-duration: 8s; -webkit-animation-name: backgroundchangeFadeInOut; -webkit-animation-timing-function: ease-in-out; -webkit-animation-iteration-count: infinite; -webkit-animation-duration: 8s; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="inner"&gt; &lt;div id="backgroundchange"&gt; &lt;div class="backgroundimg" id="back1"&gt;&lt;/div&gt; &lt;div class="backgroundimg" id="back2"&gt;&lt;/div&gt; &lt;div class="backgroundimg" id="back3"&gt;&lt;/div&gt; &lt;div class="backgroundimg" id="back4"&gt;&lt;/div&gt; &lt;div class="backgroundimg" id="back5"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>It takes 2 seconds for each image to crossfade to the next, I tried changing it to 3 seconds by adding one second on each nth-of-type but didn't work. I need your help with this please!</p>
3
1,430
Dynamic dropdown list
<ol> <li>subjects</li> <li>course</li> <li>chapters</li> </ol> <p>I want to add 2 dynamic dropdown lists, one is for subjects, and one is for course. When I select subject, courses which is added to that subject should be loaded in the course dropdown list, and then add chapters to that courses.</p> <p>How do I do that? </p> <p>Any help would be appreciated.</p> <p>Here is my code:</p> <pre><code>&lt;div class="content-form-inner"&gt; &lt;div id="page-heading"&gt;Enter the details&lt;/div&gt; &lt;div class="form_loader" id="thisFormLoader"&gt;&lt;/div&gt; &lt;div id="error_message"&gt;&lt;/div&gt; &lt;form name="thisForm" id="thisForm" action="editchapters.php?mode=&lt;?php echo $_REQUEST['mode']; ?&gt;&amp;id=&lt;?php echo $id; ?&gt;" method="post" enctype="multipart/form-data"&gt; &lt;table border="0" cellpadding="0" cellspacing="0" id="id-form" &gt; &lt;tr&gt; &lt;th valign="top" style="width:0%"&gt;&lt;span class="required"&gt;*&lt;/span&gt;Subject&lt;/th&gt; &lt;td style="width: 0%"&gt; &lt;select name="subject_name" class="select-form required " style="color:#000 !important;width:200px !important"&gt; &lt;option value=""&gt;Select&lt;/option&gt; &lt;?php $sql = "select * from mock_subject "; $res = mysqli_query($dbhandle,$sql); $numrows =mysqli_num_rows($res); echo mysql_error(); if($numrows){ while($obj = mysqli_fetch_object($res)){ if($obj-&gt;status == 1){ if($subject == $obj-&gt;id){ echo '&lt;option value="'.$obj-&gt;id.'" selected&gt;'.($obj-&gt;subject_name).'&lt;/option&gt;'; } else{ echo '&lt;option value="'.$obj-&gt;id.'"&gt;'.($obj-&gt;subject_name).'&lt;/option&gt;'; } } } } ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td style="width: 0%;"&gt; &lt;div id="subject_id-error" class="error-inner"&gt;&lt;/div&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th valign="top" style="width:0%"&gt;&lt;span class="required"&gt;*&lt;/span&gt;Course&lt;/th&gt; &lt;td style="width: 0%"&gt; &lt;select name="course_name" class="select-form required " style="color:#000 !important;width:200px !important"&gt; &lt;option value=""&gt;Select&lt;/option&gt; &lt;?php $sql = "select * from mock_course "; $res = mysqli_query($dbhandle,$sql); $numrows =mysqli_num_rows($res); echo mysql_error(); if($numrows){ while($obj = mysqli_fetch_object($res)){ if($obj-&gt;status == 1){ if($course == $obj-&gt;id){ echo '&lt;option value="'.$obj-&gt;id.'" selected&gt;'.($obj-&gt;course_name).'&lt;/option&gt;'; } else{ echo '&lt;option value="'.$obj-&gt;id.'"&gt;'.($obj-&gt;course_name).'&lt;/option&gt;'; } } } } ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td style="width: 0%;"&gt; &lt;div id="course_id-error" class="error-inner"&gt;&lt;/div&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&lt;span class="required"&gt;*&lt;/span&gt;Chapter&lt;/th&gt; &lt;td&gt;&lt;input type="text" name="chapter_name" class="inp-form required" value="&lt;?php echo $chapter;?&gt;" style="color:#000 !important;"&gt;&lt;/td&gt; &lt;td&gt; &lt;div&gt;&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;&amp;nbsp;&lt;/th&gt; &lt;td valign="top"&gt;&lt;input type="submit" name="submit_button" value="&lt;?php echo $mode=="edit"? "Update" : "Add" ?&gt;" class="form-submit" /&gt; &lt;input type="reset" value="Reset" class="form-reset" /&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
3
3,554
How to pass 'quotaUser' parameter for queries to MySQL server in GCP from cloud function?
<p>I'm working on a project right now that shows a list of items. To retrieve this data, the page calls a callable cloud function which queries the data from a MySQL server. This MySQL server, like our cloud functions, is part of our project on the Google Cloud Platform.</p> <p>The page that shows the items is used quite a lot by our customer and last Tuesday they reported some problems that the data wasn't showing or took a long time to show up. Having looked at the cloud function logs at that time, we see a lot of timeouts followed by a few of these errors:</p> <blockquote> <p>CloudSQL warning: your action is needed to update your function and avoid potential disruptions. Please see <a href="https://cloud.google.com/functions/docs/sql#troubleshooting" rel="nofollow noreferrer">https://cloud.google.com/functions/docs/sql#troubleshooting</a> for additional details: googleapi: Error 429: Quota exceeded for quota group 'default' and limit 'Queries per user per 100 seconds' of service 'sqladmin.googleapis.com' for consumer 'project_number:[some number]'., rateLimitExceeded</p> </blockquote> <p>I'm not entirely sure if this is the cause of the issue, but it does seem like something we should do something about anyway. As I understand it, we can send 300 queries per user per 100 seconds to the MySQL server. So about 3 per second. The cloud function itself only sends 2 queries to the server. One to retrieve the data for the current page with the applied filters and another one to get a total record count. However, we don't send any user info when performing the query. So I think that if 150 users each trigger the callable, 300 queries will be performed and counted towards the quota as if they were done by a single user. Because it's a server, the cloud function, that actually performs the query. The error also mentions the quota group 'default'.</p> <p>The following page tells me that I should be able to pass a 'quotaUser' parameter to specify a specific user that requests should count towards for the quota.</p> <p><a href="https://cloud.google.com/apis/docs/capping-api-usage#limiting_requests_per_second_per_user" rel="nofollow noreferrer">https://cloud.google.com/apis/docs/capping-api-usage#limiting_requests_per_second_per_user</a></p> <p>However... I have no idea how to pass that parameter with our queries. I've read something that this parameter can be used in the url parameters or in the headers, but we are using the Node.js mysql package to perform these queries, and I don't know how to tell it to send this parameter. This is the guide we followed to set up the mysql connection. We are using the same mysql package.</p> <p><a href="https://cloud.google.com/sql/docs/mysql/connect-functions#node.js" rel="nofollow noreferrer">https://cloud.google.com/sql/docs/mysql/connect-functions#node.js</a></p> <p>I would think that if a GCP guide tells us to use that mysql package, it should also somehow be possible to specify this quotaUser.</p> <p>If anyone can help me out with this, it would be greatly appreciated. I'm a bit stuck and can't find any documentation or examples on how to pass this parameter for MySQL queries.</p> <p>This is how we connect to the MySQL server:</p> <pre><code>import { config } from '../config'; import { createConnection, Connection, ConnectionConfig } from 'mysql'; export function connectToMySQLDatabase(): Connection { const connectionName: string | undefined = process.env.INSTANCE_CONNECTION_NAME || `${config.firebaseProjectId}:${config.mysqlConfig.regionId}:${config.mysqlConfig.instanceId}`; const dbUser: string | undefined = process.env.SQL_USER || config.mysqlConfig.user; const dbPassword: string | undefined = process.env.SQL_PASSWORD || config.mysqlConfig.password; const dbName: string | undefined = process.env.SQL_NAME || config.mysqlConfig.databaseName; const mysqlConfig: ConnectionConfig = { user: dbUser, password: dbPassword, database: dbName, dateStrings: true, socketPath = `/cloudsql/${connectionName}`; }; return createConnection(mysqlConfig); } </code></pre> <p>And how we perform a query:</p> <pre><code>exports.itemQuerySQL = functions .region(config.region) .runWith({ timeoutSeconds: 60, memory: '1GB' }) .https .onCall(async (request: GetItemsRequest, context) =&gt; { const mysqlConnection: Connection = connectToMySQLDatabase(); try { return await queryItems(request, mysqlConnection); } catch (error) { throw error; } finally { mysqlConnection.end(); } }); async function queryItems(request: GetItemsRequest, mysqlConnection: Connection): Promise&lt;CallableQueryResponse&lt;string&gt;&gt; { let query = ''; let values = []; // Removed a bunch of code irrelevant to the issue that builds up the query and values array. const results: any[] = await performQuery(mysqlConnection, sqlQuery, sqlQueryValues); return { results: results, // Some other properties }; } async function performQuery(mysqlConnection: Connection, query: string, values?: (string | string[] | number | null)[]): Promise&lt;any&gt; { return new Promise((resolve: (value?: unknown) =&gt; void, reject: (reason?: any) =&gt; void): void =&gt; { mysqlConnection.query(query, values, (error: MysqlError, results: any) =&gt; { if (error) { return reject(error); } else { return resolve(results); } }); }); } </code></pre> <p>Besides the code that constructs the query itself, I also left out most of the error handling to keep these examples small.</p>
3
1,792
FCM messages is not always delivered
<p>I push Firebase messages from PHP and they usually get the target Android app.</p> <p>Nonetheless, and occasionally, a push message is not correctly delivered if the target Android mobile was inactive for some period of time. Then, if I open the app, the message is delivered immediately.</p> <p>I read about the Doze status; the battery optimizations; etc. I don't want to bother the user to explicitly whitelist the app.</p> <p>Thanks in advance !</p> <p>PHP:</p> <pre><code> private function sendFirebaseMessage($msg, $to_uid) { // getting firebase token ID $user_token_id = DB::getInstance()-&gt;getUserFirebaseTokenId($to_uid); #API access key from Google API's Console define( 'API_ACCESS_KEY', 'A...7' ); $fields = array ( 'to' =&gt; $user_token_id, 'data' =&gt; $msg, &quot;priority&quot; =&gt; &quot;high&quot; ); $headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' ); #Send Reponse To FireBase Server $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) ); $result = curl_exec($ch ); curl_close( $ch ); #Echo Result Of FireBase Server return $user_token_id . &quot;]XXX[&quot; . $result; } </code></pre> <p>Android/Java:</p> <pre><code> @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); // Check if message contains a data payload. Map&lt;String, String&gt; data = remoteMessage.getData(); if (data.size() &gt; 0) { Log.d(TAG, &quot;StorableMessage data payload: &quot; + data); if (data.containsKey(&quot;sender_id&quot;) &amp;&amp; data.containsKey(&quot;sender_name&quot;) &amp;&amp; data.containsKey(&quot;chat_topic&quot;)) { if (!ChatActivity.IsVisible) { NotifsManager.showFirebaseNotif(this, data.get(&quot;sender_name&quot;), data.get(&quot;sender_id&quot;), data.get(&quot;chat_topic&quot;)); } } } } </code></pre>
3
1,292
Using CUDA atomicInc to get unique indices
<p>I have CUDA kernel where basically each thread holds a value, and it needs to add that value to one or more lists in shared memory. So for each of those lists, it needs to get an index value (unique for that list) to put the value.</p> <p>The real code is different, but there are lists like:</p> <pre><code>typedef struct { unsigned int numItems; float items[MAX_NUM_ITEMS]; } List; __shared__ List lists[NUM_LISTS]; </code></pre> <p>The values <code>numItems</code> are initially all set to 0, and then a <code>__syncthreads()</code> is done.</p> <p>To add its value to the lists, each thread does:</p> <pre><code>for(int list = 0; list &lt; NUM_LISTS; ++list) { if(should_add_to_list(threadIdx, list)) { unsigned int index = atomicInc(&amp;lists[list].numItems, 0xffffffff); assert(index &lt; MAX_NUM_ITEMS); // always true lists[list].items[index] = my_value; } } </code></pre> <p>This works most of the time, but it seems that when making some unrelated changes in other parts of the kernel (such as not checking asserts that always succeed), sometimes two threads get the same index for one list, or indices are skipped. The final value of <code>numSamples</code> always becomes correct, however.</p> <p>However, when using the following custom implementation for <code>atomicInc_</code> instead, it seems to work correctly:</p> <pre><code>__device__ static inline uint32_t atomicInc_(uint32_t* ptr) { uint32_t value; do { value = *ptr; } while(atomicCAS(ptr, value, value + 1) != value); return value; } </code></pre> <p>Are the two <code>atomicInc</code> functions equivalent, and is it valid to use <code>atomicInc</code> that way to get unique indices?</p> <p>According the the <a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/#atomic-functions" rel="nofollow noreferrer">CUDA programming guide</a>, the atomic functions do not imply memory ordering constraints, and different threads can access the <code>numSamples</code> of different lists at the same time: could this cause it to fail?</p> <p><strong>Edit:</strong></p> <p>The real kernel looks like this:</p> <p>Basically there is a list of <em>spot blocks</em>, containing <em>spots</em>. Each <em>spot</em> has XY coordinates (<em>col</em>, <em>row</em>). The kernel needs to find, for each spot, the spots that are in a certain window (col/row difference) around it, and put them into a list in shared memory.</p> <p>The kernel is called with a fixed number of warps. A CUDA block corresponds to a group of <em>spot blocks</em>. (here 3) These are called the <em>local</em> spot blocks.</p> <p>First it takes the spots from the block's 3 spot blocks, and copies them into shared memory (<code>localSpots[]</code>). For this it uses one warp for each spot block, so that the spots can be read coalesced. Each thread in the warp is a spot in the local spot block. The spot block indices are here hardcoded (<code>blocks[]</code>).</p> <p>Then it goes through the <em>surrounding</em> spot blocks: These are all the spot blocks that may contain spots that are close enough to a spot in the <em>local spot blocks</em>. The surrounding spot block's indices are also hardcoded here (<code>sblock[]</code>).</p> <p>In this example it only uses the first warp for this, and traverses <code>sblocks[]</code> iteratively. Each thread in the warp is a spot in the surrounding spot block. It also iterates through the list of all the local spots. If the thread's spot is close enough to the local spot: It inserts it into the local spot's list, using <code>atomicInc</code> to get an index.</p> <p>When executed, the printf shows that for a given local spot (here the one with row=37, col=977), indices are sometimes repeated or skipped.</p> <p>The real code is more complex/optimized, but this code already has the problem. Here it also only runs one CUDA block.</p> <pre><code>#include &lt;assert.h&gt; #include &lt;stdio.h&gt; #define MAX_NUM_SPOTS_IN_WINDOW 80 __global__ void Kernel( const uint16_t* blockNumSpotsBuffer, XGPU_SpotProcessingBlockSpotDataBuffers blockSpotsBuffers, size_t blockSpotsBuffersElementPitch, int2 unused1, int2 unused2, int unused3 ) { typedef unsigned int uint; if(blockIdx.x!=30 || blockIdx.y!=1) return; int window = 5; ASSERT(blockDim.x % WARP_SIZE == 0); ASSERT(blockDim.y == 1); uint numWarps = blockDim.x / WARP_SIZE; uint idxWarp = threadIdx.x / WARP_SIZE; int idxThreadInWarp = threadIdx.x % WARP_SIZE; struct Spot { int16_t row; int16_t col; volatile unsigned int numSamples; float signalSamples[MAX_NUM_SPOTS_IN_WINDOW]; }; __shared__ uint numLocalSpots; __shared__ Spot localSpots[3 * 32]; numLocalSpots = 0; __syncthreads(); ASSERT(numWarps &gt;= 3); int blocks[3] = {174, 222, 270}; if(idxWarp &lt; 3) { uint spotBlockIdx = blocks[idxWarp]; ASSERT(spotBlockIdx &lt; numSpotBlocks.x * numSpotBlocks.y); uint numSpots = blockNumSpotsBuffer[spotBlockIdx]; ASSERT(numSpots &lt; WARP_SIZE); size_t inOffset = (spotBlockIdx * blockSpotsBuffersElementPitch) + idxThreadInWarp; uint outOffset; if(idxThreadInWarp == 0) outOffset = atomicAdd(&amp;numLocalSpots, numSpots); outOffset = __shfl_sync(0xffffffff, outOffset, 0, 32); if(idxThreadInWarp &lt; numSpots) { Spot* outSpot = &amp;localSpots[outOffset + idxThreadInWarp]; outSpot-&gt;numSamples = 0; uint32_t coord = blockSpotsBuffers.coord[inOffset]; UnpackCoordinates(coord, &amp;outSpot-&gt;row, &amp;outSpot-&gt;col); } } __syncthreads(); int sblocks[] = { 29,30,31,77,78,79,125,126,127,173,174,175,221,222,223,269,270,271,317,318,319,365,366,367,413,414,415 }; if(idxWarp == 0) for(int block = 0; block &lt; sizeof(sblocks)/sizeof(int); ++block) { uint spotBlockIdx = sblocks[block]; ASSERT(spotBlockIdx &lt; numSpotBlocks.x * numSpotBlocks.y); uint numSpots = blockNumSpotsBuffer[spotBlockIdx]; uint idxThreadInWarp = threadIdx.x % WARP_SIZE; if(idxThreadInWarp &gt;= numSpots) continue; size_t inOffset = (spotBlockIdx * blockSpotsBuffersElementPitch) + idxThreadInWarp; uint32_t coord = blockSpotsBuffers.coord[inOffset]; if(coord == 0) return; // invalid surrounding spot int16_t row, col; UnpackCoordinates(coord, &amp;row, &amp;col); for(int idxLocalSpot = 0; idxLocalSpot &lt; numLocalSpots; ++idxLocalSpot) { Spot* localSpot = &amp;localSpots[idxLocalSpot]; if(localSpot-&gt;row == 0 &amp;&amp; localSpot-&gt;col == 0) continue; if((abs(localSpot-&gt;row - row) &gt;= window) &amp;&amp; (abs(localSpot-&gt;col - col) &gt;= window)) continue; int index = atomicInc_block((unsigned int*)&amp;localSpot-&gt;numSamples, 0xffffffff); if(localSpot-&gt;row == 37 &amp;&amp; localSpot-&gt;col == 977) printf(&quot;%02d &quot;, index); // &lt;-- sometimes indices are skipped or duplicated if(index &gt;= MAX_NUM_SPOTS_IN_WINDOW) continue; // index out of bounds, discard value for median calculation localSpot-&gt;signalSamples[index] = blockSpotsBuffers.signal[inOffset]; } } } </code></pre> <p>Output looks like this:</p> <pre><code>00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 23 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 00 01 02 02 03 03 04 05 06 07 08 09 10 11 12 06 13 14 15 16 17 18 19 20 21 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 23 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 </code></pre> <p>Each line is the output of one execution (the kernel is run multiple times). It is expected that indices appear in different orders. But for example on the third-last line, index 23 is repeated.</p> <p>Using <code>atomicCAS</code> seems to fix it. Also using <code>__syncwarp()</code> between executions on the outer for-loop seems to fix it. But it is not clear why, and if that always fixes it.</p> <hr /> <p><strong>Edit 2:</strong> This is a full program (main.cu) that shows the problem:</p> <p><a href="https://pastebin.com/cDqYmjGb" rel="nofollow noreferrer">https://pastebin.com/cDqYmjGb</a></p> <p>The CMakeLists.txt:</p> <p><a href="https://pastebin.com/iB9mbUJw" rel="nofollow noreferrer">https://pastebin.com/iB9mbUJw</a></p> <p>Must be compiled with -DCMAKE_BUILD_TYPE=Release.</p> <p>It produces this output:</p> <pre><code>00(0:00000221E40003E0) 01(2:00000221E40003E0) 02(7:00000221E40003E0) 03(1:00000221E40003E0) 03(2:00000221E40003E0) 04(3:00000221E40003E0) 04(1:00000221E40003E0) 05(4:00000221E40003E0) 06(6:00000221E40003E0) 07(2:00000221E40003E0) 08(3:00000221E40003E0) 09(6:00000221E40003E0) 10(3:00000221E40003E0) 11(5:00000221E40003E0) 12(0:00000221E40003E0) 13(1:00000221E40003E0) 14(3:00000221E40003E0) 15(1:00000221E40003E0) 16(0:00000221E40003E0) 17(3:00000221E40003E0) 18(0:00000221E40003E0) 19(2:00000221E40003E0) 20(4:00000221E40003E0) 21(4:00000221E40003E0) 22(1:00000221E40003E0) </code></pre> <p>For example the lines with 03 show that two threads (1 and 2), get the same result (3), after calling <code>atomicInc_block</code> on the same counter (at <code>0x00000221E40003E0</code>).</p>
3
4,205
Data Validation should be pulling based off of previous Options. Returning Undefined
<p>The Bid Sheet is ultimately supposed to enable the user to enter the various Options and it will give them a list if Items with those Options. I suspect my attempt to use the same scripting as the single validation Option is insufficient to handle the multiple Options, but I am too inexperienced to know a better path.</p> <p>Everything works except for this piece. Which returns "undefined".</p> <pre><code> var cell = ws.getRange(r,OptionDesc); var FullOptions = ws.getRange(r, 2, 1, 7).getValues(); var listToApplyDesc = FullOptions.map(function (o) { return o[7] }); applyValidationtoCell(listToApplyDesc,cell); </code></pre> <p>I've included the full script and a link to a copy of the Sheet since I'm not confident enough to simplify to the "minimum reproducible example".</p> <p><a href="https://drive.google.com/open?id=1Y0VT3KYD1wbj6QR1gTLepn7KtxU91rQoqRLL2Zg9-FI" rel="nofollow noreferrer">https://drive.google.com/open?id=1Y0VT3KYD1wbj6QR1gTLepn7KtxU91rQoqRLL2Zg9-FI</a></p> <pre><code>var mainWsName = "Bid Sheet"; var nameData = "Data"; var Category = 2; var ManualAutomatic = 3; var OptionA = 4; var OptionB = 5; var OptionC = 6; var OptionD = 7; var OptionE = 8; var OptionDesc = 9; var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mainWsName); var wsData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(nameData); var manAutoOption = wsData.getRange(2, 1,wsData.getLastRow()-1,9).getValues(); //Must change getLastRow Column count to include any added Options function onEdit(e){ var activeCell = e.range; var val = activeCell.getValue(); var r = activeCell.getRow(); var c = activeCell.getColumn(); var designator = ws.getRange(r, 1); var designatorValue = designator.getValue(); if (designatorValue != "x") return;//designator IF only allows the script to run on rows with x. var wsName = activeCell.getSheet().getName(); if (wsName === mainWsName &amp;&amp; c === Category &amp;&amp; r &gt; 10){ OptionsValidation (val,r); } }//end onEdit //OptionsValidation required to clear Option cells on Category change function OptionsValidation (val,r){ if(val === ""){ ws.getRange(r,ManualAutomatic, 1, 7).clearContent(); ws.getRange(r,ManualAutomatic, 1, 7).clearDataValidations(); } else { ws.getRange(r,ManualAutomatic, 1, 7).clearContent(); //Sets a Data Validation Dropdown based off of input from Category var filterOptions = manAutoOption.filter(function(o){ return o[0] === val }); var firstLevelColValue = ws.getRange(r, Category).getValue(); var filterOptions = manAutoOption.filter(function(o){ return o[0] === firstLevelColValue}); var listToApplyMA = filterOptions.map(function (o) { return o[1] }); var cell = ws.getRange(r,ManualAutomatic); applyValidationtoCell(listToApplyMA,cell); var listToApplyA = filterOptions.map(function (o) { return o[2] }); var cell = ws.getRange(r,OptionA); applyValidationtoCell(listToApplyA,cell); var listToApplyB = filterOptions.map(function (o) { return o[3] }); var cell = ws.getRange(r,OptionB); applyValidationtoCell(listToApplyB,cell); var listToApplyC = filterOptions.map(function (o) { return o[4] }); var cell = ws.getRange(r,OptionC); applyValidationtoCell(listToApplyC,cell); var listToApplyD = filterOptions.map(function (o) { return o[5] }); var cell = ws.getRange(r,OptionD); applyValidationtoCell(listToApplyD,cell); var listToApplyE = filterOptions.map(function (o) { return o[6] }); var cell = ws.getRange(r,OptionE); applyValidationtoCell(listToApplyE,cell); var cell = ws.getRange(r,OptionDesc); var FullOptions = ws.getRange(r, 2, 1, 7).getValues(); var listToApplyDesc = FullOptions.map(function (o) { return o[7] }); applyValidationtoCell(listToApplyDesc,cell); } } function applyValidationtoCell(list,cell){ var rule = SpreadsheetApp .newDataValidation() .requireValueInList(list) .setAllowInvalid(false) .build(); cell.setDataValidation(rule); } </code></pre>
3
1,523
Reactivity not working inside the loop for unknown reason in vuejs
<p>I'm struggling to get working the reactivity in vue.js inside the loop. Loop is rendering without any issue, But, when trying to fire an event it updates the content but not visible or render data in the page.</p> <p>I've used the latest version of vue.js with bootstrap and jquery. I've tried adding <code>key</code> in the loop item but not working. But, when to update any other content by using <code>v-model</code> then it works.</p> <p><strong>Markup</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;div id="app"&gt; &lt;div class="props"&gt; &lt;div class="prop-item" v-for="prop in modules.variations.properties"&gt; &lt;p&gt;=== &lt;strong v-text="prop.name"&gt;&lt;/strong&gt; ===&lt;/p&gt; &lt;ul&gt; &lt;li v-for="value in prop.values" @click="activeProp(prop,value)"&gt; &lt;span v-text="value.name"&gt;&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;input type="text" v-model="message"&gt; &lt;pre&gt;{{ actives }}&lt;/pre&gt; &lt;pre&gt;{{ message }}&lt;/pre&gt; &lt;/div&gt; &lt;script&gt; window.spdata = { "variations":{ "properties":[ { "id":1, "name":"Color", "values":[ { "id":1, "name":"Black", }, { "id":2, "name":"Red", }, { "id":3, "name":"Blue", } ] }, { "id":2, "name":"Size", "values":[ { "id":4, "name":"XL", }, { "id":5, "name":"XXL", }, { "id":6, "name":"XXXL", }, ] }, { "id":3, "name": "Type", "values":[ { "id":8, "name":"Premium", }, { "id":9, "name":"Standard", }, { "id":10, "name":"Luxary", } ] } ] } }; &lt;/script&gt; </code></pre> <p><strong>Javascript</strong></p> <pre class="lang-js prettyprint-override"><code> new Vue({ el: "#app", data: { modules: window.spdata, actives: {}, message: '', }, created() { this.modules.variations.properties.forEach((prop) =&gt; { this.actives[prop.id] = null }); }, methods: { activeProp(prop, val) { if (this.actives[prop.id] === val.id) { this.actives[prop.id] = null; } else { this.actives[prop.id] = val.id; } } } }) </code></pre>
3
1,727
Client server authentication with self signed certificate - Curl is working but Apache HttpClient throws exception
<p>I'm trying to implement client and server authentication with Apache HTTPClient, and to test it with a self signed certificate. I've tried to follow several tutorials and answers to similar questions here but with no success. I've tried to detail as much as possible all the steps that I've been doing, hopefully someone can point out what I'm doing wrong:</p> <ol> <li><p>Created a file <code>req.conf</code> for configuration</p> <pre><code>[req] prompt=no distinguished_name = req_distinguished_name [ req_distinguished_name ] O=selfSignedO CN=selfSignedCn DC=selfSignedDc </code></pre></li> <li><p>Generated server private key and the self-signed certificate</p> <pre><code>openssl req \ -config req.conf \ -x509 \ -newkey rsa:4096 \ -keyout server/server-private-key.pem \ -out server/server.crt \ -days 3650 \ -nodes </code></pre></li> <li><p>Created PKCS12 keystore containing the private key and certificate created in the previous step</p> <pre class="lang-sh prettyprint-override"><code> openssl pkcs12 \ -export \ -out server/server-key-store.p12 \ -inkey server/server-private-key.pem \ -in server/server.crt </code></pre> <p>let's say the password I used was <code>123456</code></p></li> <li><p>Generated a client private key and a certificate signing request</p> <pre class="lang-sh prettyprint-override"><code>openssl req \ -config req.conf \ -new \ -newkey rsa:4096 \ -out client/client-request.csr \ -keyout client/client-private-key.pem \ -nodes </code></pre></li> <li><p>Signed the client's certificate signing request with the server's private key and certificate</p> <pre class="lang-sh prettyprint-override"><code>openssl x509 \ -req \ -days 360 \ -in client/client-request.csr \ -CA server/server.crt \ -CAkey server/server-private-key.pem \ -CAcreateserial \ -out client/client-signed-cert.crt \ -sha256 </code></pre></li> <li><p>Created a PKCS12 keystore containing the client's private key and certificate certificate created in the previous step.</p> <pre class="lang-sh prettyprint-override"><code> openssl pkcs12 \ -export \ -out client/client-keystore.p12 \ -inkey client/client-private-key.pem \ -in client/client-signed-cert.crt \ -certfile server/server.crt </code></pre> <p>we used <code>123456</code> as password again.</p></li> <li><p>Generated server trust store containing the client signed certificate</p> <pre class="lang-sh prettyprint-override"><code>keytool \ -import \ -trustcacerts \ -alias root \ -file client/client-signed-cert.crt \ -keystore server/server-trust-store.jks </code></pre> <p>password? <code>123456</code></p></li> <li><p>Curl is working, but only with <code>-k</code></p> <pre class="lang-sh prettyprint-override"><code>curl -k \ --cert client/client-signed-cert.crt \ --key client/client-private-key.pem \ https://localhost:443:/my/endpoint </code></pre> <p>without the <code>-k</code> I get the error:</p> <pre class="lang-sh prettyprint-override"><code>curl: (60) SSL certificate problem: self signed certificate More details here: https://curl.haxx.se/docs/sslcerts.html curl performs SSL certificate verification by default, using a "bundle" of Certificate Authority (CA) public keys (CA certs). If the default bundle file isn't adequate, you can specify an alternate file using the --cacert option. If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL). If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option. HTTPS-proxy has similar options --proxy-cacert and --proxy-insecure. </code></pre></li> <li><p>Configured Apache HTTPClient:</p> <pre class="lang-java prettyprint-override"><code>private HttpClient createClient() throws Exception { String keyPassword = "123456"; KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(resourceAsStream("/client/client-key-store.p12"), keyPassword.toCharArray()); SSLContext sslContext = new SSLContextBuilder() .setProtocol("TLSv1.2") .loadKeyMaterial(ks, keyPassword.toCharArray()) .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build() return HttpClients.custom() .setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } </code></pre> <p>(The construction is done via multiple methods that I squeezed here to one, so if something is weird or missing please let me know, perhaps I miscopy-pasted something.) </p></li> </ol> <p>but when trying to send the same request as with Curl I'm getting:</p> <pre><code>Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.Alerts.getSSLException(Alerts.java:154) at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:2038) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1135) at sun.security.ssl.SSLSocketImpl.waitForClose(SSLSocketImpl.java:1779) at sun.security.ssl.HandshakeOutStream.flush(HandshakeOutStream.java:124) at sun.security.ssl.Handshaker.sendChangeCipherSpec(Handshaker.java:1156) at sun.security.ssl.ClientHandshaker.sendChangeCipherAndFinish(ClientHandshaker.java:1266) at sun.security.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.java:1178) at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:348) at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1052) at sun.security.ssl.Handshaker.process_record(Handshaker.java:987) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1072) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:396) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:355) at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:373) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:394) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56) </code></pre>
3
2,503
Different types JSON file using ObjectMapper
<p>I am using AlamofireObjectMapper to communicate with a backend server. The result of one of the requests is an array of items, which contain two values:</p> <ul> <li>A "typeIdentifier" indicating which type of data the second value ("arbitraryData") is of</li> <li>A "arbitraryData": <ul> <li>If "typeIdentifier" CONTAINS "X", arbitraryData is of type ArbitraryDataTypeX</li> <li>If "typeIdentifier" CONTAINS "Y", arbitraryData is of type ArbitraryDataTypeY</li> </ul></li> </ul> <p>The two ArbitraryDataType classes do not share any common ancestor (except Mappable). It could be even a primitive type, an array, an optional, etc.</p> <p>How can I make AlamofireObjectMapper parse the "arbitraryData" field using the appropriate type.</p> <p>See the following JSON file:</p> <pre><code>{ "arrayOfItems": [ { "typeIdentifier": "X", "arbitraryData": { "value": "BLA", } }, { "typeIdentifier": "Y", "arbitraryData": { "anotherValue": "BLUBB", } } ] } </code></pre> <p>My corresponding Swing file looks like the following:</p> <pre><code>class Item : Mapping { var typeIdentifier = "X" var arbitraryData: Mappable? = nil init?(_ map: Map) { self.init() mapping(map) } func mapping(map: Map) { typeIdentifier &lt;- map["typeIdentifier"] // THIS LINE CONTAINS MY QUESTION: HOW CAN I TELL OBJECTMAPPER, THAT, // IF typeIdentifier CONTAINS "X", arbitraryData IS OF TYPE // ArbitraryDataTypeX, AND IF "Y" arbitraryData IS OF TYPE // ArbitraryDataTypeY? arbitraryData &lt;- map["arbitraryData"] } } class ArbitraryDataTypeX : Mapping { var value = "BLA" init?(_ map: Map) { self.init() mapping(map) } func mapping(map: Map) { value &lt;- map["value"] } } class ArbitraryDataTypeY : Mapping { var anotherValue = "BLUBB" init?(_ map: Map) { self.init() mapping(map) } func mapping(map: Map) { anotherValue &lt;- map["anotherValue"] } } </code></pre> <p>Background information: I am using AlamofireObjectMapper to communicate with a backend server. The result of one of the requests is an array of Item. The typeIdentifier-mechanism (infact it is a little bit more complex, but let's leave this out) is given by the backend and cannot be changed.</p>
3
1,058
PHP calculation result not showing correct currency format
<p>In the following code I am trying to get the results:</p> <pre><code>$time_base_cost_day; </code></pre> <p>and</p> <pre><code>$time_base_cost_month; </code></pre> <p>to show with correct currency comma separators like <code>$1,456.00</code> or <code>$100,456.00</code></p> <p>I have tried a couple of examples but not sure where I am not adding the function correctly. </p> <p>Thank you for your help</p> <pre><code>&lt;?php $choose_industry = $_POST['choose_industry']; $company_name = $_POST['company_name']; $hourly_rate = $_POST['hourly_rate']; $billable_rate = $_POST['billable_rate']; $working_days = $_POST['working_days']; $wasted_time_per_day = $_POST['wasted_time_per_day']; $no_of_trucks = $_POST['no_of_trucks']; $fuel_price_per_liter = $_POST['fuel_price_per_liter']; $fuel_wasted_per_hr = $_POST['fuel_wasted_per_hr']; $time_base_cost_day = $hourly_rate*$wasted_time_per_day; $time_base_cost_month = $time_base_cost_day*$working_days; $productivity_costs_day = $billable_rate*$wasted_time_per_day; $productivity_costs_month = $productivity_costs_day*$working_days; $fuel_base_cost_day = $wasted_time_per_day*$fuel_price_per_liter*$fuel_wasted_per_hr; $fuel_base_cost_month = $fuel_base_cost_day*$working_days; $monthly_cost_per_unit = 35; $lost_per_vehicle_per_month = ($time_base_cost_month+$productivity_costs_month+$fuel_base_cost_month) - $monthly_cost_per_unit ; $monthly_savings_per_truck = $lost_per_vehicle_per_month;//Monthly Savings = (Monthly Time Based Costs + Monthly Productivity Costs + Monthly Fuel Based Costs) – Monthly Costs per Unit. $monthly_savings_per_fleet = $monthly_savings_per_truck*$no_of_trucks; $monthly_cost_per_fleet = $no_of_trucks*$monthly_cost_per_unit; $link = mysql_connect('##', '##', '##'); mysql_select_db('##', $link); if( (!empty($choose_industry)) &amp;&amp; (!empty($company_name)) &amp;&amp; (!empty($hourly_rate)) &amp;&amp; (!empty($billable_rate)) &amp;&amp; (!empty($working_days)) &amp;&amp; (!empty($wasted_time_per_day)) &amp;&amp; (!empty($no_of_trucks)) &amp;&amp; (!empty($fuel_price_per_liter)) &amp;&amp; (!empty($fuel_wasted_per_hr)) &amp;&amp; (!empty($time_base_cost_day)) &amp;&amp; (!empty($time_base_cost_month)) &amp;&amp; (!empty($productivity_costs_day)) &amp;&amp; (!empty($productivity_costs_month)) &amp;&amp; (!empty($fuel_base_cost_day)) &amp;&amp; (!empty($fuel_base_cost_month)) &amp;&amp; (!empty($monthly_savings_per_truck)) &amp;&amp; (!empty($monthly_savings_per_fleet)) ){ $result = mysql_query("INSERT into wp_calculate (id, choose_industry, company_name, hourly_rate, billable_rate, working_days, wasted_time_per_day, no_of_trucks, fuel_price_per_liter, fuel_wasted_per_hr, time_base_cost_day, time_base_cost_month, productivity_costs_day, productivity_costs_month, fuel_base_cost_day, fuel_base_cost_month, monthly_savings_per_truck, monthly_savings_per_fleet, monthly_cost_per_unit, monthly_cost_per_fleet, Date ) values ('', '$choose_industry','$company_name', '$hourly_rate', '$billable_rate', '$working_days', '$wasted_time_per_day', '$no_of_trucks', '$fuel_price_per_liter', '$fuel_wasted_per_hr', '$time_base_cost_day', '$time_base_cost_month', '$productivity_costs_day', '$productivity_costs_month', '$fuel_base_cost_day', '$fuel_base_cost_month', '$monthly_savings_per_truck', '$monthly_savings_per_fleet', '$monthly_cost_per_unit', '$monthly_cost_per_fleet', now() )"); $last_id = mysql_insert_id(); $sql = "UPDATE wp_calculate SET pdf_link='/main/downloadpdf.php?user_id=$last_id' WHERE id=$last_id"; $retval = mysql_query($sql); ?&gt; &lt;div class="offset-wrapper push-down3" id="cost_based"&gt; &lt;!--&lt;div class="span6"&gt;&lt;/div&gt; &lt;div class="span6"&gt;&lt;/div&gt;--&gt; &lt;div class="row cost_row" id="cost_row"&gt; &lt;div class="custom-calc-inner-2 wow bounceInLeft" data-wow-duration="3s" data-wow-delay="1s"&gt; &lt;h4&gt;Time Based Costs&lt;/h4&gt; &lt;p&gt;Cost of wasted time (per driver)&lt;/p&gt; &lt;div class="result"&gt; &lt;div class="pos-left"&gt; &lt;p class="value"&gt;DAY&lt;/p&gt;&lt;p class="lbl"&gt;$&lt;?php echo $time_base_cost_day; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="pos-right"&gt; &lt;p class="lbl"&gt;$&lt;?php echo $time_base_cost_month; ?&gt;&lt;/p&gt;&lt;p class="value"&gt;MONTH&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
3
1,923
Emulator crashes after running code
<p>This is the XML file for the main fragment that i am currently dealing with. the problem i am having is that when i clean the project it does not give me any errors but when i run the program the emulator crashes.</p> <pre><code> &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.budgetfuel.MainActivity$PlaceholderFragment" &gt; &lt;LinearLayout android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingBottom="20dp" &gt; &lt;TextView android:id="@+id/textView3" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Select Car:" android:textAppearance="?android:attr/textAppearanceSmall" /&gt; &lt;Spinner android:id="@+id/spinner1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/LinearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="20dp" &gt; &lt;TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Price Per Litre:" android:textAppearance="?android:attr/textAppearanceSmall" /&gt; &lt;EditText android:id="@+id/editText1" android:layout_width="171dp" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" /&gt; &lt;/LinearLayout&gt; &lt;Space android:id="@+id/Space1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="fill_vertical" /&gt; &lt;LinearLayout android:id="@+id/LinearLayout3" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="20dp" &gt; &lt;TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.66" android:text="Litres:" android:textAppearance="?android:attr/textAppearanceSmall" /&gt; &lt;EditText android:id="@+id/editText2" android:layout_width="171dp" android:layout_height="wrap_content" android:layout_weight="0.27" android:ems="10" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/LinearLayout4" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingBottom="20dp" &gt; &lt;TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="34dp" android:layout_weight="0.80" android:text="Odo Reading:" android:textAppearance="?android:attr/textAppearanceSmall" /&gt; &lt;EditText android:id="@+id/editText3" android:layout_width="186dp" android:layout_height="wrap_content" android:layout_weight="0.40" android:ems="10" &gt; &lt;requestFocus /&gt; &lt;/EditText&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/LinearLayout5" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingBottom="20dp" &gt; &lt;TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.20" android:text="Date:" android:textAppearance="?android:attr/textAppearanceSmall" /&gt; &lt;Button android:id="@+id/buttonDateSet" android:layout_width="140dp" android:layout_height="wrap_content" android:text="Change Date:" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:id="@+id/LinearLayout6" android:layout_height="wrap_content" &gt; &lt;TextView android:id="@+id/Output" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre>
3
2,570
Why does this boost::spirit::qi rule not match the input?
<p>I tried to continue to work on my previous example and expand the rules. My problem is, that rules that use ID_IDENTIFIER do not work - although I know that the lexer is working (using unit tests).</p> <p>Here's the example:</p> <pre><code>#include &lt;boost/spirit/include/qi.hpp&gt; #include &lt;boost/spirit/include/lex_lexertl.hpp&gt; namespace qi = boost::spirit::qi; namespace lex = boost::spirit::lex; enum LexerIDs { ID_IDENTIFIER, ID_WHITESPACE, ID_INTEGER, ID_FLOAT, ID_PUNCTUATOR }; template &lt;typename Lexer&gt; struct custom_lexer : lex::lexer&lt;Lexer&gt; { custom_lexer() : identifier ("[a-zA-Z_][a-zA-Z0-9_]*") , white_space ("[ \\t\\n]+") , integer_value ("[1-9][0-9]*") , hex_value ("0[xX][0-9a-fA-F]+") , float_value ("[0-9]*\\.[0-9]+([eE][+-]?[0-9]+)?") , float_value2 ("[0-9]+\\.([eE][+-]?[0-9]+)?") , punctuator ("\\[|\\]|\\(|\\)|\\.|&amp;&gt;|\\*\\*|\\*|\\+|-|~|!|\\/|%|&lt;&lt;|&gt;&gt;|&lt;|&gt;|&lt;=|&gt;=|==|!=|\\^|&amp;|\\||\\^\\^|&amp;&amp;|\\|\\||\\?|:|,")// [ ] ( ) . &amp;&gt; ** * + - ~ ! / % &lt;&lt; &gt;&gt; &lt; &gt; &lt;= &gt;= == != ^ &amp; | ^^ &amp;&amp; || ? : , { using boost::spirit::lex::_start; using boost::spirit::lex::_end; this-&gt;self.add (identifier , ID_IDENTIFIER) /*(white_space , ID_WHITESPACE)*/ (integer_value, ID_INTEGER) (hex_value , ID_INTEGER) (float_value , ID_FLOAT) (float_value2 , ID_FLOAT) (punctuator , ID_PUNCTUATOR); this-&gt;self("WS") = white_space; } lex::token_def&lt;std::string&gt; identifier; lex::token_def&lt;lex::omit&gt; white_space; lex::token_def&lt;int&gt; integer_value; lex::token_def&lt;int&gt; hex_value; lex::token_def&lt;double&gt; float_value; lex::token_def&lt;double&gt; float_value2; lex::token_def&lt;&gt; punctuator; }; template&lt; typename Iterator, typename Skipper&gt; struct custom_grammar : qi::grammar&lt;Iterator, Skipper&gt; { template&lt; typename TokenDef &gt; custom_grammar(const TokenDef&amp; tok) : custom_grammar::base_type(ges) { ges = qi::token(ID_IDENTIFIER); BOOST_SPIRIT_DEBUG_NODE(ges); } qi::rule&lt;Iterator, Skipper &gt; ges; }; int main(int argc, _TCHAR* argv[]) { std::string test("testidentifier"); typedef char const* Iterator; typedef lex::lexertl::token&lt;Iterator, lex::omit, boost::mpl::true_&gt; token_type; typedef lex::lexertl::lexer&lt;token_type&gt; lexer_type; typedef qi::in_state_skipper&lt;custom_lexer&lt;lexer_type&gt;::lexer_def&gt; skipper_type; typedef custom_lexer&lt;lexer_type&gt;::iterator_type iterator_type; custom_lexer&lt;lexer_type&gt; my_lexer; custom_grammar&lt;iterator_type, skipper_type&gt; my_grammar(my_lexer); Iterator first = test.c_str(); Iterator last = &amp;first[test.size()]; bool r = lex::tokenize_and_phrase_parse(first,last,my_lexer,my_grammar,qi::in_state( "WS" )[ my_lexer.self ]); std::cout &lt;&lt; std::boolalpha &lt;&lt; r &lt;&lt; "\n"; std::cout &lt;&lt; "Remaining unparsed: '" &lt;&lt; std::string(first,last) &lt;&lt; "'\n"; return 0; } </code></pre> <p>a similar rule with ID_INTEGER matches fine for "1234"</p>
3
1,676
RuntimeError: Can't determine home directory
<p>I'm trying to run a PYthon Script on a server using xampp. When trying to import matplotlib I get the following error:</p> <pre><code>[Fri Mar 13 10:46:36.219708 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: File "C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py", line 5, in &lt;module&gt;\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.220702 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: from LambWaveModes import *\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.220702 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: File "C:\\Users\\gfranosc\\Downloads\\xampp-portable-win32-7.2.1-0-VC15\\xampp\\htdocs\\Python\\LambWaveModes.py", line 13, in &lt;module&gt;\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.221697 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: from matplotlib import pyplot as plt\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.221697 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: File "C:\\Users\\gfranosc\\Downloads\\Python\\lib\\site-packages\\matplotlib\\pyplot.py", line 32, in &lt;module&gt;\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.221697 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: import matplotlib.colorbar\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.222692 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: File "C:\\Users\\gfranosc\\Downloads\\Python\\lib\\site-packages\\matplotlib\\colorbar.py", line 31, in &lt;module&gt;\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.222692 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: import matplotlib.contour as contour\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.223688 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: File "C:\\Users\\gfranosc\\Downloads\\Python\\lib\\site-packages\\matplotlib\\contour.py", line 16, in &lt;module&gt;\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.223688 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: import matplotlib.font_manager as font_manager\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.224683 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: File "C:\\Users\\gfranosc\\Downloads\\Python\\lib\\site-packages\\matplotlib\\font_manager.py", line 103, in &lt;module&gt;\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.224683 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: os.path.join(str(Path.home()), r'AppData\\Local\\Microsoft\\Windows\\Fonts'),\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.225680 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: File "C:\\Users\\gfranosc\\Downloads\\Python\\lib\\pathlib.py", line 1079, in home\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.225680 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: return cls(cls()._flavour.gethomedir(None))\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.225680 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: File "C:\\Users\\gfranosc\\Downloads\\Python\\lib\\pathlib.py", line 264, in gethomedir\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.226676 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: raise RuntimeError("Can't determine home directory")\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.226676 2020] [cgi:error] [pid 15320:tid 2012] [client ::1:54631] AH01215: RuntimeError: Can't determine home directory\r: C:/Users/gfranosc/Downloads/xampp-portable-win32-7.2.1-0-VC15/xampp/htdocs/Python/test.py [Fri Mar 13 10:46:36.228667 2020] [authz_core:error] [pid 15320:tid 2012] [client ::1:54631] AH01630: client denied by server configuration: C:/xampp/apache </code></pre> <p>Can someone help me? Do I "just" have to clarify the home directory? If yes, how can I do that?</p>
3
2,187
Papaparse local file not showing any data
<p>I'm trying to parse a local relative csv file using papaparse however it doesn't return any data at all. The two files are located in the same folder locally. Not sure what im doing wrong here.</p> <p>Here is my code so far....</p> <p><strong>index.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Document&lt;/title&gt; &lt;!-- scripts --&gt; &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;js/papaparse.min.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;CSV Analytics&lt;/h1&gt; &lt;div class=&quot;row&quot; id=&quot;csv_list&quot;&gt;&lt;/div&gt; &lt;!-- scripts --&gt; &lt;script type=&quot;text/javascript&quot;&gt; $(document).ready(function () { parseDataFile(); function parseDataFile() { console.log(&quot;loading...&quot;); const file = new File([&quot;csv&quot;], &quot;data.csv&quot;, { type: &quot;text/plain&quot;, }); Papa.parse(file, { delimiter: &quot;auto&quot;, header: true, dynamicTyping: true, complete: displayData, }); } function displayData(results) { console.log(results); } }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>data.csv</strong></p> <pre><code>For Reorder,Inventory ID,Name,Description,Unit Price,Quantity in Stock,Inventory Value,Reorder Level,Reorder Time in Days,Quantity in Reorder,Discontinued? 0,IN0001,Item 1,Desc 1,$51.00,25,&quot;$1,275.00&quot;,29,13,50, 0,IN0002,Item 2,Desc 2,$93.00,132,&quot;$12,276.00&quot;,231,4,50, 0,IN0003,Item 3,Desc 3,$57.00,151,&quot;$8,607.00&quot;,114,11,150, 0,IN0004,Item 4,Desc 4,$19.00,186,&quot;$3,534.00&quot;,158,6,50, 0,IN0005,Item 5,Desc 5,$75.00,62,&quot;$4,650.00&quot;,39,12,50, 0,IN0006,Item 6,Desc 6,$11.00,5,$55.00,9,13,150, 0,IN0007,Item 7,Desc 7,$56.00,58,&quot;$3,248.00&quot;,109,7,100,Yes 0,IN0008,Item 8,Desc 8,$38.00,101,&quot;$3,838.00&quot;,162,3,100, 0,IN0009,Item 9,Desc 9,$59.00,122,&quot;$7,198.00&quot;,82,3,150, 0,IN0010,Item 10,Desc 10,$50.00,175,&quot;$8,750.00&quot;,283,8,150, 0,IN0011,Item 11,Desc 11,$59.00,176,&quot;$10,384.00&quot;,229,1,100, 0,IN0012,Item 12,Desc 12,$18.00,22,$396.00,36,12,50, 0,IN0013,Item 13,Desc 13,$26.00,72,&quot;$1,872.00&quot;,102,9,100, 0,IN0014,Item 14,Desc 14,$42.00,62,&quot;$2,604.00&quot;,83,2,100, 0,IN0015,Item 15,Desc 15,$32.00,46,&quot;$1,472.00&quot;,23,15,50, 0,IN0016,Item 16,Desc 16,$90.00,96,&quot;$8,640.00&quot;,180,3,50, 0,IN0017,Item 17,Desc 17,$97.00,57,&quot;$5,529.00&quot;,98,12,50,Yes 0,IN0018,Item 18,Desc 18,$12.00,6,$72.00,7,13,50, 0,IN0019,Item 19,Desc 19,$82.00,143,&quot;$11,726.00&quot;,164,12,150, 0,IN0020,Item 20,Desc 20,$16.00,124,&quot;$1,984.00&quot;,113,14,50, 0,IN0021,Item 21,Desc 21,$19.00,112,&quot;$2,128.00&quot;,75,11,50, 0,IN0022,Item 22,Desc 22,$24.00,182,&quot;$4,368.00&quot;,132,15,150, 0,IN0023,Item 23,Desc 23,$29.00,106,&quot;$3,074.00&quot;,142,1,150,Yes 0,IN0024,Item 24,Desc 24,$75.00,173,&quot;$12,975.00&quot;,127,9,100, 0,IN0025,Item 25,Desc 25,$14.00,28,$392.00,21,8,50, </code></pre>
3
1,904
How to run DatabaseUtil.precomputedKNNQuery method of LOF class on two different threads
<p>I want to reduce runtime of DatabaseUtil.precomputedKNNQuery method by running this method on two different threads and KNNQuery is an interface.</p> <pre><code> KNNQuery&lt;O&gt; knnq = DatabaseUtil.precomputedKNNQuery(database, relation, getDistanceFunction(), k); </code></pre> <p>I divided this method of LOF class in two parts like this</p> <pre><code> Callable&lt;KNNQuery&gt; task1(Database database, Relation&lt;O&gt; relation){ DBIDs idss = relation.getDBIDs(); ArrayDBIDs aids = (ArrayDBIDs) idss; aids = aids.slice(0, (aids.size() / 2)); aids.size(); ProxyView&lt;O&gt; pv = new ProxyView&lt;&gt;(aids, relation); return () -&gt; { return DatabaseUtil.precomputedKNNQuery(database, pv, getDistanceFunction(), k); }; } Callable&lt;KNNQuery&gt; task2(Database database, Relation&lt;O&gt; relation) { DBIDs idss = relation.getDBIDs(); ArrayDBIDs aids = (ArrayDBIDs) idss; aids = aids.slice(((aids.size() / 2) - 1), aids.size()); aids.size(); ProxyView&lt;O&gt; pv2 = new ProxyView&lt;&gt;(aids, relation); return () -&gt; { return DatabaseUtil.precomputedKNNQuery(database, pv2, getDistanceFunction(), k); }; } </code></pre> <p>Then i invoked both these tasks on two different threads like this in run() method of LOF class </p> <pre><code> public OutlierResult run(Database database, Relation&lt;O&gt; relation) { StepProgress stepprog = LOG.isVerbose() ? new StepProgress("LOF", 3) : null; DBIDs ids = relation.getDBIDs(); LOG.beginStep(stepprog, 1, "Materializing nearest-neighbor sets."); ExecutorService executor = Executors.newFixedThreadPool(2); List&lt;Callable&lt;KNNQuery&gt;&gt; callables = Arrays.asList( task1(database, relation), task2(database, relation)); for (Future&lt;KNNQuery&gt; future : executor.invokeAll(callables)) { KNNQuery&lt;O&gt; knnq = future.get(); // Compute LRDs // compute LOF_SCORE of each db object // Build result representation } } </code></pre> <p>But i am getting exception which is saying something like this because forEach is providing only output of first future in knnq variable but not the combined output of both future's. Please help me how can i get rid of this exception with example thanks?</p> <pre><code>de.lmu.ifi.dbs.elki.datasource.FileBasedDatabaseConnection.load: 505 ms LOF #1/3: Materializing nearest-neighbor sets. de.lmu.ifi.dbs.elki.index.preprocessed.knn.MaterializeKNNPreprocessor.k: 4 de.lmu.ifi.dbs.elki.index.preprocessed.knn.MaterializeKNNPreprocessor.k: 4 Materializing k nearest neighbors (k=4): 21751 [100%] de.lmu.ifi.dbs.elki.index.preprocessed.knn.MaterializeKNNPreprocessor.precomputation-time: 21470 ms Materializing k nearest neighbors (k=4): 21750 [100%] de.lmu.ifi.dbs.elki.index.preprocessed.knn.MaterializeKNNPreprocessor.precomputation-time: 22355 ms LOF #2/3: Computing Local Reachability Densities (LRD). Task failed de.lmu.ifi.dbs.elki.database.datastore.ObjectNotFoundException: Object 21751 was not found in the database. at de.lmu.ifi.dbs.elki.database.datastore.memory.ArrayStore.get(ArrayStore.java:69) at de.lmu.ifi.dbs.elki.index.preprocessed.knn.AbstractMaterializeKNNPreprocessor.get(AbstractMaterializeKNNPreprocessor.java:118) at de.lmu.ifi.dbs.elki.database.query.knn.PreprocessorKNNQuery.getKNNForDBID(PreprocessorKNNQuery.java:84) at de.lmu.ifi.dbs.elki.algorithm.outlier.lof.LOF.computeLRD(LOF.java:292) at de.lmu.ifi.dbs.elki.algorithm.outlier.lof.LOF.computeLRDs(LOF.java:277) at de.lmu.ifi.dbs.elki.algorithm.outlier.lof.LOF.run(LOF.java:244) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm.run(AbstractAlgorithm.java:89) at de.lmu.ifi.dbs.elki.workflow.AlgorithmStep.runAlgorithms(AlgorithmStep.java:100) at de.lmu.ifi.dbs.elki.KDDTask.run(KDDTask.java:109) at de.lmu.ifi.dbs.elki.application.KDDCLIApplication.run(KDDCLIApplication.java:58) at [...] </code></pre>
3
1,694
JPA Hibernate Configuration Errors
<p>I want to enable JPA for an EJB module, in an IntelliJ J2E project. I don't have an existing database schema to import; I want to generate the schema and tables from my EJB POJO class. I then want to generate ORM mappings.</p> <p>I've enabled JavaEE Persistence framework support in IntelliJ, with Hibernate as the provider. I've updated persistence.xml and assigned MySQL@localhost as the data source, to the JPA persistence unit. I've also added the JPA descriptor to the ear artifact.</p> <p>When I try to add the JPA annotations to my POJO, e.g. @Table, @Column etc, I get an error "Cannot resolve table 'TABLE_NAME'"...same applies for columns. The context action I get is 'Assign Data Sources', but the data source is showing as assigned to the persistence unit.</p> <p>I've run the code and now just get a huge stack trace.</p> <p>The tutorials i've found are either for importing an existing schema (which I don't have), or use other IDEs. My persistence.xml and one of my pojos are included below</p> <p>Thanks in advance..</p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd" version="2.2"&gt; &lt;persistence-unit name="NewPersistenceUnit" transaction-type="JTA"&gt; &lt;provider&gt;org.hibernate.jpa.HibernatePersistenceProvider&lt;/provider&gt; &lt;properties&gt; &lt;property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/&gt; &lt;property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/MySQL"/&gt; &lt;property name="javax.persistence.jdbc.user" value="root"/&gt; &lt;property name="javax.persistence.jdbc.password" value="***"/&gt; &lt;!--Hibernate properties--&gt; &lt;property name="hibernate.show_sql" value="false"/&gt; &lt;property name="hibernate.format_sql" value="false"/&gt; &lt;property name="hibernate.hbm2ddl.auto" value="update"/&gt; &lt;property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p>POJO</p> <pre><code>@Entity @Table(name = "CATALOG_ITEM") public class CatalogItem { @Id @Column(name = "CATALOG_ITEM_ID") private Long itemID; private String name; private String manufacturer; private String description; private Date availableDate; public CatalogItem() { } </code></pre> <p>GlassFish Log</p> <pre><code>[2020-05-29 12:56:46,830] Artifact jpa:ear: Error during artifact deployment. See server log for details. [2020-05-29 12:56:46,830] Artifact jpa:ear: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while preparing the app : [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory. Please see server.log for more details. Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method : javax.persistence.PersistenceException: [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory </code></pre> <p>Server Log</p> <pre><code>[2020-05-29T00:56:46.782+0100] [glassfish 5.1] [SEVERE] [] [] [tid: _ThreadID=52 _ThreadName=Thread-9] [timeMillis: 1590710206782] [levelValue: 1000] [[ org.glassfish.deployment.common.DeploymentException: [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:158) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:901) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:410) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:195) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:467) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:516) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:512) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:360) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:511) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:542) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:534) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:360) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:533) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1441) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:86) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1823) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1699) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:510) at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:200) at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:166) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:439) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:144) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:515) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549) at java.lang.Thread.run(Thread.java:748) Caused by: javax.persistence.PersistenceException: [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1314) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1240) at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:141) at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:175) at org.glassfish.persistence.jpa.PersistenceUnitLoader.&lt;init&gt;(PersistenceUnitLoader.java:83) at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:199) at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486) at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:206) at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:144) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:901) at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:285) at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:64) at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:131) at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:128) at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:208) at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:217) RAR5038:Unexpected exception while creating resource for pool DerbyPool. Exception : javax.resource.spi.ResourceAllocationException: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused (Connection refused).]] RAR5117 : Failed to obtain/create connection from connection pool [ DerbyPool ]. Reason : com.sun.appserv.connectors.internal.api.PoolingException: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused (Connection refused).]] RAR5114 : Error allocating connection : [Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused (Connection refused).]]] HHH000342: Could not obtain connection to query metadata : Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused (Connection refused).]] at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:243) at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:128) ... 40 more Caused by: org.hibernate.HibernateException: DdlTransactionIsolatorJtaImpl could not locate TransactionManager to suspend any current transaction; base JtaPlatform impl (org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform@45dad759)? at org.hibernate.resource.transaction.backend.jta.internal.DdlTransactionIsolatorJtaImpl.&lt;init&gt;(DdlTransactionIsolatorJtaImpl.java:46) at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl.buildDdlTransactionIsolator(JtaTransactionCoordinatorBuilderImpl.java:46) at org.hibernate.tool.schema.internal.HibernateSchemaManagementTool.getDdlTransactionIsolator(HibernateSchemaManagementTool.java:175) at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:94) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73) at org.hibernate.internal.SessionFactoryImpl.&lt;init&gt;(SessionFactoryImpl.java:314) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1237) ... 56 more ]] [2020-05-29T00:56:46.784+0100] [glassfish 5.1] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=52 _ThreadName=admin-listener(4)] [timeMillis: 1590710206784] [levelValue: 1000] [[ Exception while preparing the app]] [2020-05-29T00:56:46.784+0100] [glassfish 5.1] [SEVERE] [NCLS-CORE-00026] [javax.enterprise.system.core] [tid: _ThreadID=52 _ThreadName=admin-listener(4)] [timeMillis: 1590710206784] [levelValue: 1000] [[ Exception during lifecycle processing org.glassfish.deployment.common.DeploymentException: [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:158) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:901) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:410) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:195) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:467) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:516) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:512) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:360) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:511) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:542) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:534) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:360) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:533) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1441) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:86) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1823) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1699) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:510) at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:200) at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:166) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:439) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:144) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:515) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549) at java.lang.Thread.run(Thread.java:748) Caused by: javax.persistence.PersistenceException: [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1314) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1240) at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:141) at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:175) at org.glassfish.persistence.jpa.PersistenceUnitLoader.&lt;init&gt;(PersistenceUnitLoader.java:83) at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:199) at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486) at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:206) at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:144) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:901) at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:285) at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:64) at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:131) at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:128) at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:208) at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:217) at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:243) at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:128) ... 40 more Caused by: org.hibernate.HibernateException: DdlTransactionIsolatorJtaImpl could not locate TransactionManager to suspend any current transaction; base JtaPlatform impl (org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform@45dad759)? at org.hibernate.resource.transaction.backend.jta.internal.DdlTransactionIsolatorJtaImpl.&lt;init&gt;(DdlTransactionIsolatorJtaImpl.java:46) at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl.buildDdlTransactionIsolator(JtaTransactionCoordinatorBuilderImpl.java:46) at org.hibernate.tool.schema.internal.HibernateSchemaManagementTool.getDdlTransactionIsolator(HibernateSchemaManagementTool.java:175) at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:94) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73) at org.hibernate.internal.SessionFactoryImpl.&lt;init&gt;(SessionFactoryImpl.java:314) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1237) ... 56 more ]] [2020-05-29T00:56:46.812+0100] [glassfish 5.1] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=52 _ThreadName=admin-listener(4)] [timeMillis: 1590710206812] [levelValue: 1000] [[ Exception while preparing the app : [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory javax.persistence.PersistenceException: [PersistenceUnit: NewPersistenceUnit] Unable to build Hibernate SessionFactory at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1314) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1240) at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:141) at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:175) at org.glassfish.persistence.jpa.PersistenceUnitLoader.&lt;init&gt;(PersistenceUnitLoader.java:83) at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:199) at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486) at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:206) at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:144) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:901) at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:285) at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:64) at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:131) at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:128) at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:208) at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:217) at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:243) at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:128) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:901) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:410) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:195) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:467) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:516) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:512) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:360) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:511) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:542) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:534) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:360) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:533) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1441) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:86) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1823) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1699) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:510) at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:200) at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:166) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:439) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:144) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:515) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549) at java.lang.Thread.run(Thread.java:748) Caused by: org.hibernate.HibernateException: DdlTransactionIsolatorJtaImpl could not locate TransactionManager to suspend any current transaction; base JtaPlatform impl (org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform@45dad759)? at org.hibernate.resource.transaction.backend.jta.internal.DdlTransactionIsolatorJtaImpl.&lt;init&gt;(DdlTransactionIsolatorJtaImpl.java:46) at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl.buildDdlTransactionIsolator(JtaTransactionCoordinatorBuilderImpl.java:46) at org.hibernate.tool.schema.internal.HibernateSchemaManagementTool.getDdlTransactionIsolator(HibernateSchemaManagementTool.java:175) at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:94) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73) at org.hibernate.internal.SessionFactoryImpl.&lt;init&gt;(SessionFactoryImpl.java:314) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1237) ... 56 more ]] </code></pre>
3
9,617
Text shows in header instead of new section BS4
<p>I have a problem with my one-page website. My new text section shows in my header video. instead in my new section. I want it after video header. What am I doing wrong?</p> <p>My HTML</p> <pre><code>&lt;header&gt; &lt;div class="container"&gt; &lt;div class="bg-wrap"&gt; &lt;video poster="poster.png" autoplay="true" loop muted&gt; &lt;source src="img/video.mp4" type="video/mp4"&gt; &lt;source src="img/video.webm" type="video/webm"&gt; &lt;/video&gt; &lt;div class="header-text"&gt; &lt;h1&gt;Elektro Sikora&lt;/h1&gt; &lt;p&gt;Informační portál Elektro Sikora Český Těšín&lt;/p&gt; &lt;/div&gt; &lt;div id="scroll"&gt; &lt;div class="round"&gt; &lt;div class="wheel"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="scrolling"&gt; &lt;span class="arrow"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt; &lt;section id="content-space"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-12 text-center"&gt; &lt;p&gt; Kompletní nabídka produktů, které nabízíme. Najdete zde od elektroniky až po zdravou výživu. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p>My CSS</p> <pre><code>/* Nav */ .navbar { padding: 1,2rem; } /* Video */ .bg-wrap { position: fixed; z-index: -1000; width: 100%; height: 100%; overflow: hidden; top: 0; left: 0; } video { top: 70px; left: 0; min-height: 100%; min-width: 100%; } .header-text { position: absolute; width: 100%; min-height: 100%; z-index: 1000; background-color: rgba(0, 0, 0, 0.4); } .header-text h1 { text-align: center; font-size: 65px; text-transform: uppercase; font-weight: 300; color: #fff; padding-top: 15%; margin-bottom: 10px; } .header-text p { text-align: center; font-size: 20px; letter-spacing: 3px; color: #fff; } #scroll { cursor: pointer; display: block; position: absolute; bottom: 50px; left: 50%; z-index: 1000; } .round { height: 21px; width: 14px; border-radius: 10px; transform: none; border: 2px solid #fff; top: 170px; } .wheel { animation-delay: 0s; animation-duration: 1s; animation-iteration-count: infinite; animation-name: scrolling; animation-play-state: running; animation-timing-function: linear; background: #fff none repeat scroll 0 0; border-radius: 10px; height: 3px; margin-left: auto; margin-right: auto; position: relative; top: 4px; width: 2px; } .scrolling span { display: block; width: 5px; height: 5px; -ms-transform: rotate(45deg); -o-transform: rotate(45deg); -moz-transform: rotate(45deg); -webkit-transform: rotate(45deg); transform: rotate(45deg); border-right: 2px solid #fff; border-bottom: 2px solid #fff; margin: 3px 0 3px 5px; } .arrow { margin-top: 6px; } header { height: 100vh; overflow: hidden; } </code></pre> <p><a href="https://i.stack.imgur.com/Jzm3k.jpg" rel="nofollow noreferrer">Nav dissapear and scrollable video</a></p>
3
1,461