text:
Q: To get Stable Keyboard Configs for 90 WPM and Dvorak in Debian? I am trying to set stable keyboard configurations for the user with 90 WPM of correct words per minute and the keyboard layout Dvorak.
The cursor location is behaving unstably for instance in editors when typing in Debian 8.1, much differently than in OSX.
The cursor also inactivates sometimes suddenly where the test with the typeracer confirms that: the cursor inactivates at the start of each game in any browsers: Google-chrome used here as a benchmark.
Settings
I disabled every keybinding in Keyboard > Shortcuts such that no effect on my typing anymore.
However, still unstable keyboard behaviour is occurring.
My keyboard config is the following by which I can reach 95-105 WPM in single games but not on average because the keyboard cursor is moving unstably, particularly at the start of the typeracer -game used as another benchmark here.

Typeracer -test in many games
It occurs sometimes that at the start of the game, the cursor location is not active.
You need to press the mouse to the box to get active again.
Problem in Editors such as gedit
The typeracer -problem is duplicating in standard text editors.
The cursor moves suddenly from the original location to somewhere random location.
Why does the cursor location changes after each game in typingracer in any browser of Linux?
How can you make the typing more stable in Debian 8.1?
What is causing the sudden changes in the cursor position?


text:
Q: Setting width and height to child of GridView not working I am trying to set a custom width and height to the children of a GridView. I tried the following, but it's not working:
GridView.count(
      shrinkWrap: true,
      crossAxisCount: 5,
      children: coolArray.map((String currentItem) {
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
          width: 17,
          height: 10,
          color: Colors.red,
          child: Text('currentItem'),
        );
      }).toList(),
    )

The items have their own height which I don't know how they're calculated.

A: You can use childAspectRatio, example
  GridView.count(
  shrinkWrap: true,
  crossAxisCount: 5,
  childAspectRatio:width/height,
  children: coolArray.map((String currentItem) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
      color: Colors.red,
      child: Text('currentItem'),
    );
  }).toList());

redpajama_set_name: RedPajamaStackExchange


text:
Q: python script does not rewrite the file on itself so first and foremost i wanted to connect multiple lines into one and add ","
so in example
line1
line2
line2

to
line1,line2,line3

i managed to make it work with this script right here
filelink = input("Enter link here ")

fix = file = open(filelink, "r")

data=open(filelink).readlines()
for n,line in enumerate(data):
    if line.startswith("line"):
       data[n] = "\n"+line.rstrip()
    else:
       data[n]=line.rstrip()
print(','.join(data))

HOWEVER in the terminal itself it shows it executed perfectly but in the text file itself it's still remains the same no connected lines and no commas
side note. i would love some explanations how does the loop work and what "enumerate" stands for and why specifically this code i tried googling each one separately and understand the code but i didn't manage to find what i was looking for if anyone keen to explain the code line by line shortly i would be very appreciative
Thanks in advance <3

A: This is somewhat superfluous:
fix = file = open(filelink, "r")

That's assigning two names to the same file object, and you don't even use fix, so at least drop that part.
For handling files, you would be better using a context manager. That means that you can open a resource and they will automatically get closed for you once you're done (usually).
In any case, you opened in read mode with open(filelink, "r") so you'll never change the file contents. print(','.join(data)) will probably show you what you expect, but print() writes to stdout and the change will only be in your terminal. You will not modify the base file with this. But, I think you're sufficiently close that I'll try close the missing connection.
In this case, you need to:

*

*open the file first in read mode to pull the data out.

*Do the transform in python to the data

*Open the file again in write mode (which wipes the existing contents)

*Write the transformed data

So, like this:
filelink = input("Enter link here ")

with open(filelink) as infile: # context manager, by default in "r" mode
    data = [item.strip() for item in infile.readlines()]

data = ','.join(data)

# Now write it back out

with open(filelink, "w") as outfile:
    outfile.write(data)


text:
Q: iOS:How to make statusBar position animate? I recently get a demand,which is make navigation bar move up to dismiss, that is let navigation bar do position animation.
Somebody know how to do that?

A: I have token a method to animate my navigation bar like this:
[UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.navigationController.navigationBar.frame = CGRectMake(frame.origin.x, frame.origin.y-NAVIGATIONBARHEIGHT, frame.size.width, frame.size.height);}
                     completion:^(BOOL completion){

                     }];


text:
Q: Adding additional parameter to form submit I have a form declaration in my Razor view
<form method="post" action="/Lot/LotList?auctionEventId=@auctionEventId" id="filterForm">

(Incidentally, I chose to write it out like this rather than use Html.BeginFrom because I needed to give it an id and didn't know how to do that with Html.BeginFrom - but that is not the issue here)
Outside of this form I have a button which submits this form (there is also a submit button in the form)
<input type="button" onclick="$('#filterForm').submit();" value="Show all" />

Now, the issue is that if this button is used to submit the form I want the action in the form to change to
action="/Lot/LotList?auctionEventId=@auctionEventId&showAll=true"

How do I alter the action and pass this additional parameter?  Is there a totally better way of doing all this?

A: I know you said this is not the issue but you can add attributes to Html.BeginForm like this:
 @using (Html.BeginForm("ActionName","ControllerName", FormMethod.Post, new { id = "filterform" })){

A: how about putting a hidden input
<form method="post" action="/Lot/LotList?auctionEventId=@auctionEventId" id="filterForm">

<input type="hidden" id="showAll" name="showAll" value=""/>

on your button
<input type="button" onclick="submitForm()" value="Show all" />

on your script somewhere
function submitForm(){
$('#showAll').val('true');
$('#filterForm').submit();

}

A: Appending query string parameters onto the form action, and trying to change that at runtime is tricky (but not impossible). Far easier is to use hidden fields:
<form method="post" action="/Lot/LotList" id="filterForm">
  <input type="hidden" name="auctionEventId" value="@auctionEventId" />
  ...

So now all you have to do is add another hidden field for "showAll"
<form method="post" action="/Lot/LotList" id="filterForm">
  <input type="hidden" name="auctionEventId" value="@auctionEventId" />
  <input type="hidden" name="showAll" value="false" id="showAllField" />
  ...

And just hook up a jquery event on your showAll button:
<input id="showAllButton" type="button"/>

jQuery:
$('#showAllButton').click(function(){
     $('#showAllField').val("true");
     $('#filterForm').submit();
});

A: If you are within a form you can add the route to a button element. You can override the native action of the form by using formAction and formMethod. You can also have multiple buttons with other formActions and formMethods

<form action="/somewhere" method="get">
    <input type="type" name="name" value=" " />

    <button formaction="/Lot/LotList?auctionEventId=@auctionEventId&showAll=true" formmethod="post">Show All</button>
</form>

A: If you have multiple submit buttons for the same form, and you need to pass a different parameter for each of them, you can use the asp-route attribute to accomplish this task.
 <input type="submit" value="Save"/>

 <input id="btnComplete" type="submit"
        asp-route-addNewOneAfterSave="@true"
        value="Save And Create New One">

Just remember to have your parameter in the OnPost method, for examples:
public async Task<IActionResult> OnPostAsync(bool? addNewOneAfterSave)
        {
             //Your code ....
        }

You can read more about the asp-route anchor tag helper from this article.

A: Hello I found this to work very well
 @using (Html.BeginForm("ActionName","ControllerName",  new { id = "filterform" },FormMethod.Post)){

I had tired to do the 'FormMethod.Post' before the param but it didn't work and never passed the value. Only through trial and error did I manage to solve it and figured out that it should be like the code I posted.
Hope that helps


text:
Q: Variables inside Executor's Runnable Suppose I have a Runnable that does a simple file writing operation, and this Runnable is called with an executor.
With executor being a single thread Executor class..
public void doThis() {
    executor.execute(new Runnable() {
        @Override
        public void run() {
            file.write(_data);
        }
    });
}

does the immediate contents of _data get saved the moment execute() is called? Which means that once the runnable has been submitted to the queue, I can go ahead and make changes to _data, and the changes will not be written to the file?
_data = something
doThis();
_data = something else

is there a chance that I will end up doing file.write(something else)?

A: no to your first and second questions, and yes to your third question ... if the single thread that the executor is running on is a separate thread from the calling thread, then this is not a thread-safe operation. unless .execute() executes on the same exact thread as the caller, you need to avoid making changes to _data until .write is done.
A common way of working around this is to simply make a copy of _data before passing it off to the executor.


text:
Q: Is there a way to display an element as just a plain text in HTML? I need to have this as an output:
New element <Canada> inserted.
I tried doing this:

New element <Canada> inserted.

But I end up with this:
New element inserted.

I appreciate the help.

A: There are several ways you can do this. I would use the HTML-entities:

New element <Canada> inserted.

A short lesson about HTML entities

A: You can do it like that

New element <Canada> inserted.


text:
Q: Testing the validation of a text box using Selenium I am trying to test a webpage using Selenium and NUnit. One of my test cases entails the validation of text boxes. Using Selenium and C#, I am able to retrieve the value entered in the text box. But when the validation of the text box fails, an error message is displayed next to the text box.
So, here are my questions:
1. How can I test if an error was raised due to validation failure.
2. Can I get the text of that error.
3. Or, am I way off the mark and what I am trying to do is not at all possible.
I have tried reading the value of the element, but it always seems to be an empty string.
Say, for example, I am trying to test the webpage https://edit.yahoo.com/registration . When I enter "**myname&&" in the First Name field, an error appears stating "Only letters, spaces, hyphens, and apostrophes are allowed". I want to be able to test that this error was raised.
Also, I noticed that when Selenium opens the webpage and enters an incorrect value in the text box, the error message does not get displayed next to this text box. Whereas, when I open the webpage myself and enter an incorrect text, the error message is displayed
Thanks!!

A: You will have to use thread.sleep, but in a better way. It's better to write a function like this (I am writing this in JAVA, you should be able to write it for C#). This method will wait for the specified number of seconds for the element to be visible. If the element is not visible even after the specified number of seconds, then the method will return false. If it becomes visible then the method will return true.
Alternatively, you can use an assertion instead of returning a false condition so that your test fails.
public boolean waitForErrorMessage(String elementToWaitFor, int waitTimeInSeconds)
{
 int timeOut=0;
 while(!selenium.isVisible(elementToWaitFor))
  {
    if(timeOut<waitTimeInSeconds){
       #sleep for one second
       Thread.Sleep(1000);
     }
    else {
       return false;
    }
    timeOut=timeOut+1;
  }
  return true;
}


text:
Q: onActivityResult() called prematurely while calling Settings activity I'm facing the known issue onActivityResult getting called immediately.
I read the reason behind it on some  link
where it is advice to change launch mode of called activity.
But in my case I'm starting(navigating to) settings activity, to let the user enable data connection.
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS),
                            Constants.REQUEST_ENABLE_DATA_CONNECTION);

So I can't change launch mode of Settings activity.
I tried setting some flags to Intent e.g. intent.setFlags(0); but its not working.

A: I think there is some problem with your request code "Constants.REQUEST_ENABLE_DATA_CONNECTION".What is your request code value.
I think you should use zero "0" value like this.
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
but if you need to open wifi settings then use this code.
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
and see this Setting actions link for other setting actions.
I hope,this will help you.


text:
Q: Hugo-ish way to refer to a static file (resource) _indirectly_ so filename can be changed in one place and all content links change I want to have a file, in /static that I update every once in awhile.  For example, my resume. The actual filename will have a date in it, e.g. resume-2021-04-28.pdf.  It will be referred to in multiple places, e.g., posts that refer directly to it, in header or footer templates, etc.  So I'd like all those references to use a single ... thing ... an easy-to-type thing ... to refer to, say resume, and then somewhere I have a ... thing ... that maps resume to the current file name resume-2021-04-28.pdf.
Oh, and the posts that refer to this are in varied locations (as described above) so page bundles won't work.  I think.
Not sure whether this is done with site params, or a partial, or what.  What's the Hugo-ish way to do it?


text:
Q: Application selection on google cloud messaging This may be a weird question but, normally when I register a receiver for an action (such as sms receiving) I specify a priority value as high as possible to my application. So that my application can get sms before other applications, and I can do whatever I want (like abort broadcast) before them.
I didn't give a priority or haven't done anything special for GCM. I added uses permission for GCM Receive, and registered a receiver in manifest file.
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
.
.
.
<receiver
    android:name="com.google.android.gcm.GCMBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
    </intent-filter>
</receiver>

So suppose another application also added these to its manifest file. How does GCM calls my broadcast receiver instead of other application's broadcast receiver?

A: Per the GCM Client Manifest Setup:

[You must add] an applicationPackage + ".permission.C2D_MESSAGE" permission to prevent other Android applications from registering and receiving the Android application's messages. The permission name must exactly match this pattern—otherwise the Android application will not receive the messages.

I.e.,
<permission android:name="com.example.app.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.example.app.permission.C2D_MESSAGE" />

<application ...>
    <receiver
        android:name=".GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.example.app" />
        </intent-filter>
    </receiver>
    <service android:name=".GcmIntentService" />
</application>

where com.example.app needs to be replaced with your package name.


text:
Q: Shopify: Is there way to update products with SKU? I have around 10k products imported to Shopify, and I'm adding products through API regularly.
I'm not able to find the API (REST or GRAPH) to update the product using the SKU.
When I add the product through API I get the product_id in response so I'm able to update the product later using it. But If I'm able to update the product with SKU then I will not have to maintain product ids of Shopify. So is there any API to update the product with SKU? I couldn't find it in docs...

A: No, there isn't any Shopify API to update Product by SKU. If you look at Product and Product Variant properties, you will see that SKU is the property of Product Variant rather than Product as stated in your question.
To seamlessly integrate this into your existing system where you want to update Products based on SKU value, keep a mapping of SKU to Product Id. This mapping can be in a form of CSV, JSON or some database. Given the SKU values as input, map them to their Shopify product Ids and send update request.
Or use some third party app like Excelify that also does the same thing under the hood.


text:
Q: OkHttp request is slow I use OkHttp 3. Sometimes API call takes a longer than expected, up to 10 sec. Next time the same call may take some millis.
Here is my client
private HttpClient() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.e(TAG, message);
        }
    });
    if (BuildConfig.DEBUG_VERSION.equals(BuildConfig.VERSION_NAME)) {
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    } else {
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    }
    retryRequestInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);

            int retryCode = 429; //retry request if this code received
            int tryCount = 0;
            int maxLimit = 1;

            while (response.code() == retryCode && tryCount < maxLimit) {
                Log.e(TAG, "Request failed, got " + response.code() + ". Retrying");
                tryCount++;
                response = chain.proceed(request);
            }
            return response;
        }
    };
    cache = new Cache(AppContext.getContext().getCacheDir(), cacheSize);
    client = buildClient(builder);
    request = new Request.Builder()
            .addHeader("Content-Type", "application/vnd.api+json");
    String versionName = BuildConfig.VERSION_NAME;
    int versionCode = BuildConfig.VERSION_CODE;
    if (versionCode < 0) {
        versionName = versionName.replaceFirst(String.valueOf(versionCode), "0-dev");
    }
    request.header("User-Agent", "NTR/" + String.valueOf(versionName));
}

private OkHttpClient buildClient(OkHttpClient.Builder builder) {
    builder.addInterceptor(httpLoggingInterceptor);
    builder.addInterceptor(retryRequestInterceptor);
    builder.cache(cache);
    return builder.build();
}

public static HttpClient getInstance() {
    if (instance == null) {
        instance = new HttpClient();
    }
    return instance;
}

I added HttpLoggingInterceptor and got this
12-30 05:34:41.342  2400 10846 E DEBUG   : 0.001 connectionAcquired
12-30 05:34:41.353  2400 10846 E DEBUG   : 0.013 requestHeadersStart
12-30 05:34:41.354  2400 10846 E DEBUG   : 0.014 requestHeadersEnd
12-30 05:34:41.354  2400 10846 E DEBUG   : 0.014 requestBodyStart
12-30 05:34:41.355  2400 10846 E DEBUG   : 0.014 requestBodyEnd
12-30 05:34:41.358  2400 10846 E DEBUG   : 0.017 responseHeadersStart
12-30 05:34:45.435  2400 10846 E DEBUG   : 4.095 responseHeadersEnd

The delay is always here, between the headers start and end.
Why does it happening?


text:
Q: Scrapy - Broad crawler for domain collecting I'm trying to build a Scrapy crawler for domain collecting.
What I want is to collect websites with '.sk' or '.cz' suffixes.
My idea is to give a list of start urls (1000 sk and cz urls) and crawler would go to url like www.example.com, check for links, if these links has the correct suffixes, then yield Request objects of these urls - basic forms.
So crawler goes to example.com, it extracts two links: https://www.page.cz/about and https://www.liss.cz/info/45 and yield two requests with these urls:  https://www.page.cz and https://www.liss.cz.
I've created a simple spider now but It doesn't find any links and ends.
Do you have any ideas to improve this spider?
class doSpider(CrawlSpider):
    name = "do_crawler"
    start_urls = [
              "https://www.seznam.cz/",
    ]

    def __init__(self, *args, **kwargs):
        self.extractor = LxmlLinkExtractor(allow='/.cz|.sk/')
        super(doSpider, self).__init__(*args, **kwargs)

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, callback=self.parse_links, meta={})

    def parse_links(self, response):
        for url in self.extractor.extract_links(response):
            # parse and save to db
            yield scrapy.Request(url, callback=self.parse_links, meta={})


text:
Q: Three.js emissive materials don't cast shadow Conext
I'm using three.js, @react-three/drei and @react-three/fiber.
I'm loading a GLTF file that contains emissive materials using
const gltf = useLoader(GLTFLoader, '/model.glb')

When I inspect the loaded data like this:
for (const key of Object.keys(gltf.materials)) {
      const v = gltf.materials[key] as MeshStandardMaterial & Material
      if (!v.isMeshStandardMaterial) return

      console.log(key, v, v.emissive, v.emissiveIntensity, v.emissiveMap)
}

I can see that certain materials have a color set and their emissiveIntensity is equal to 1.
Problem
Objects made of these emissive materials load and display correctly on the scene. They have the desired color. There is, however, one problem. I would like those emissive materials to behave like a directonalLight/pointLight - i.e. cast shadows and cause reflections. Right now, they only display as shiny blobs, but their light doesn't affect other objects.
Question
How do I make emissive materials cast shadows and create reflections? Do I need a shader or is there some hidden option that I'm not seeing?


text:
Q: Create a WordPress post with private custom fields (_customfieldname) not working I am creating posts using WordPressSharp, but fail to set private custom field values that begin with an underscore upon creating the post.
I have read a ton of posts about modifying the file meta.php on the WordPress-site to alter register_meta and/or is_protected_meta, but have still not managed to get those custom fields to save the data I pass when creating the post.
using (var client = new WordPressClient(new WordPressSiteConfig
        {
            BaseUrl = "http://example.com",
            Username = "username",
            Password = "pass",
            BlogId = 1
        }))
        {
            Term t = new Term();
            t = client.GetTerm("category", 6);

            var terms = new List<Term>();
            terms.Add(t);

            var customFields = new[]
            {
                new CustomField
                {
                    Key = "_ct_text_5401d2f94abc9",
                    Value = "123"
                }
            };

            var post = new Post
            {
                PostType = "video",
                Title = "title",
                Content = "description",
                PublishDateTime = DateTime.Now,
                Status = "draft",
                CustomFields = customFields
            };

            var id = client.NewPost(post);
        }

The post is created successfully without issues, but why the private custom field is not getting the value set?
I have tried using both XMLRPC version 3 as well as 2.5, which is a common answer, but it does not apply to this particular issue.

A: Actually finally found a solution to the issue. I have removed the protection of the custom fields through the addition of the below line to functions.php
add_filter( 'is_protected_meta', '__return_false' );

I do not know if this is the optimal solution security-wise, but it works.


text:
Q: what's the best way to organize game modules I'm writing a game and have made the 1st chapter to the end already. It has around 10 modules + the game engine. I'm not asking for a step-by-step guide, but if you could tell me where to look for info that would be great!

*

*can engine code access my modules somehow when if I place them in the different folder?(I want to sort them at least for different chapters in different folders)

*is there a different, better way to do the engine code?(let's say I will have 50 chapters in game, it would be around 500 modules so it will be around 1000 more lines of engine code just to import and call them which is very very bad style)

here's the engine code:
from sys import exit
from random import randint

import module_intro
import module_house_one
import module_package_zoom
import module_house_two
import module_unboxing
import module_key_letter
import module_letter_key
import module_house_three
import module_end_game

class Engine(object):
def __init__(self, scene_map):
    self.scene_map = scene_map

def play(self):
    current_scene = self.scene_map.opening_scene()
    last_scene = self.scene_map.next_scene('finished')

    while current_scene != last_scene:
        next_scene_name = current_scene.enter()
        current_scene = self.scene_map.next_scene(next_scene_name)

    current_scene.enter()

class Map(object):
scenes = {
'intro': module_intro.Intro(),
'house_one': module_house_one.HouseOne(),
'package_zoom': module_package_zoom.PackageZoom(),
'house_two': module_house_two.HouseTwo(),
'unboxing': module_unboxing.Unboxing(),
'key_letter': module_key_letter.KeyLetter(),
'letter_key': module_letter_key.LetterKey(),
'house_three': module_house_three.HouseThree(),
'end_game': module_end_game.EndGame()
}

def __init__(self, start_scene):
    self.start_scene = start_scene

def next_scene(self, scene_name):
    val = Map.scenes.get(scene_name)
    return val

def opening_scene(self):
    return self.next_scene(self.start_scene)

a_map = Map('intro')
a_game = Engine(a_map)
a_game.play()

A: You can use, for example, this directory structure or something similar to put each chapter into the separate folder:
├── game
│   ├── chapter_one
│   │   ├── __init__.py
│   │   └── main.py
│   ├── chapter_two
│   │   ├── __init__.py
│   │   └── main.py
│   ├── engine.py
│   └── __init__.py
└── main.py

The main.py in the root folder will load all the chapters and start the game, it can look this way:
import game.chapter_one.main
import game.chapter_two.main
from game.engine import Engine, SceneMap

print("Starting the engine...")
a_map = SceneMap()
a_game = Engine(a_map)
a_game.play()

And the Scene objects can automatically register inside the SceneMap, so you don't have to do this manually, for example the game.chapter_one.main.py:
from ..engine import SceneMap

class Scene(object):

    def enter(self):
        print('Enter chapter 1')

SceneMap.register('intro', Scene)

and game.chapter_two.main.py:
from ..engine import SceneMap

class Scene(object):

    def enter(self):
        print('Enter chapter 2')

SceneMap.register('chapter 2', Scene)

The SceneMap can look like this:
class SceneMap(object):

    scenes = OrderedDict()

    @classmethod
    def register(cls, name, map_fn):
        cls.scenes[name] = map_fn

The rest of your logic can be similar to what you have now (each scene returns the next scene to play).
Or, you can simplify it even more and rely on the chapters import order in the main.py.
So if you swap import of the chapter_one / chapter_two in the main.py, they will be played in backwards order.
See the full example of this approach here.


text:
Q: Subclass ViewController from Storyboard I created ViewController in Storyboard and I am using
instantiateViewControllerWithIdentifier:

to load it. But I need to have this VC as base class and use 3-4 subclasses to change its properties.
How can I get an instance of my subclass with instantiateViewControllerWithIdentifier?

A: You will have to use object c runtime. Override init method of your subclass. Create a BaseViewController object using 'instantiateViewControllerWithIdentifier'. Then set the class for created object using objc_setClass method.
Following code will go into SubclassViewController.m.
    - (instancetype)init {
      UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"main" bundle:[NSBundle mainBundle]];
      UIViewController *baseClassViewController = [storyboard instantiateViewControllerWithIdentifier:@"baseClassIdentifier"];

      object_setClass(baseClassViewController, [SubclassViewController class]);
      return (SubclassViewController *)baseClassViewController;
    }

After this, you can simply create SubclassViewController object using simple [[SubclassViewController alloc] init].

A: @Bhagyesh version in Swift 3:
class func instantiateFromSuperclassStoryboard() -> SubclassViewController {
    let stroryboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = stroryboard.instantiateViewController(withIdentifier: "BaseViewController")
    object_setClass(controller, SubclassViewController.self)

    return controller as! SubclassViewController
}

A: Just cast it.
MyController *controller = (MyController *)[self.storyboard instantiateViewControllerWithIdentifier:@"myController"];

or Swift:
let controller = storyboard?.instantiateViewControllerWithIdentifier("myController") as! MyController


text:
Q: Find the points at which $f$ has an absolute maximum or minimum on $I$ without graphing Assume $I=[0.9,3.1], f:I\rightarrow\mathbb{R}$ is defined by $f(x):=|x^2-4x+3|, x\in I$. Without sketching the graph of $f$ on $I$, find points at which $f$ has an absolute minimum on $I$ and points at which $f$ has an absolute minimum on $I$.
We know that $f(0.9)=0.21$ and $f(3.1)=0.21$. I am a bit confused on how I can find the absolute minimum/maximum, however, without being able to differentiate since $f$ is not differentiable on $I$.
I know that obviously the max occurs at $x=2$ and the mins occur at $x=1,3$, but I am not sure how to show this without graphing.

A: Since $x^2-4x+3=(x-1)(x-3),$ the absolute value will be nondifferentiable at $1$ and $3$, each of which is in your interval $[0.9,3.1]$ and are therefore critical numbers to be tested. [each will give $f(x)=0$] Then the absolute value will be $+(x^2-4x+3)$ with derivative $2x-4$ outside of $[1,3]$ and this could contributes a new critical number at 2 but 2 is not outside of $[1,3]$. Similarly the absolute value inside $(1,3)$ is $-(x^2-4x+3)$ with derivative $-2x+4$ again possibly making the critical number 2, but this time 2 indeed is inside $(1,3)$ so is a critical number to be tested. At this point you have the endpoints $0.9,\ 3.1$ along with the three internal critical numbers at $1,2,3$ and all these should be put into $f(x)$ to get the absolute max and min.
Edit:Initially I erroneously threw out $2$ as a critical number above. I re-typed things to include that critical number.

A: For the minimum, it is easy to see that it must be greater or equal zero. Thus, you can first assume it to be zero and solve the equation $ x^2-4x+3=0 $. Either this equation has a real solution in your interval (in this case you are done), or not. In the latter case you would know that the curve does not cross $ y=0 $, and since $ y (2)> 0 $ and since the curve is continuous, you could look on the curve without absolute value and solve it normally.


text:
Q: How does Tensorflow know which trainable variables need to be minimised? I'm trying to understand the GradientDescentOptimizer API in isolation and have created a minimal example to figure out what is going on:
import tensorflow as tf

# Guess 2.5 as a starting point
x = tf.Variable(2.5, name='x', dtype=tf.float32)
log_x_squared = tf.square(tf.log(x))

optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(log_x_squared)

init = tf.global_variables_initializer()

with tf.Session() as session:
    session.run(init)
    print("start ", "x:", session.run(x), "log(x)^2:", session.run(log_x_squared))
    for step in range(10):
      session.run(train)
      print("step", step, "x:", session.run(x), "log(x)^2:", session.run(log_x_squared))

Which outputs ...
start  x: 2.5 log(x)^2: 0.83958876
step 0 x: 2.1334836 log(x)^2: 0.57419443
step 1 x: 1.7783105 log(x)^2: 0.33138883
step 2 x: 1.4545966 log(x)^2: 0.14042155
step 3 x: 1.1969798 log(x)^2: 0.032328587
step 4 x: 1.0467671 log(x)^2: 0.002089082
step 5 x: 1.0031027 log(x)^2: 9.596717e-06
step 6 x: 1.0000144 log(x)^2: 2.0805813e-10
step 7 x: 1.0 log(x)^2: 0.0
step 8 x: 1.0 log(x)^2: 0.0
step 9 x: 1.0 log(x)^2: 0.0

The minimize method is described in the API docs as:

Add operations to minimize loss by updating var_list.
This method simply combines calls compute_gradients() and
  apply_gradients(). If you want to process the gradient before applying
  them call compute_gradients() and apply_gradients() explicitly instead
  of using this function.
Args:
loss: A Tensor containing the value to minimize.
global_step: Optional Variable to increment by one after the variables have
             been updated.
var_list: Optional list or tuple of Variable objects to update to minimize
          loss.  Defaults to the list of variables collected in the
          graph under the key GraphKeys.TRAINABLE_VARIABLES.

If I add some code to output the TRAINABLE_VARIABLES:
for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES):
    print(v)

I see:
<tf.Variable 'x:0' shape=() dtype=float32_ref>

If I add another Variable to my code, it also gets output as a trainable variable, but only the x variable seems to be used by my minimize() method.  I have seen on another question that it is possible to pass 'trainable=false' to variable declarations, but that doesn't seem to be needed.
Does Tensorflow inspect the minimize operation to identify which trainable variables are part of the function and then only update those variables?

A:
Does Tensorflow inspect the minimize operation to identify which trainable variables are part of the function and then only update those variables?

In short, yes. When you're executing your session.run(train), this is calling the optimizer.minimize function on log_x_squared. If you were to define another variable that had no reference to the rest of the graph, it would not be incorporated as it is not referenced at any other part.
diagram of graph visibility when session.run(train) is executed


text:
Q: Foreign key on identifying relationships Let's start by a quick definition of an identifying relationship that I found on the web :
An identifying relationship is when the existence of a row in a child table depends on a row in a parent table, this means the primary key of a child table contains a column that belongs to a foreign key referencing a parent table.
My example: I use SQL Server and my example is the following :

*

*I created a data table to store data about schemas (metadata), and yes, sys views information are not enough in case you are wondering :)
My metadata table is called Schemas_Metadata and has a Name column as the  primary key.
Schemas_Metadata
----------------
PK (Name)

*I created another metadata table to store data about tables and my metadata table is called Tables_Metadata and has a Name column and a Schema_Name column (foreign key referencing the Name column in the Schemas_Metadata table) and a composed primary key (Schema_Name, Name). This is an identifying relationship.
Tables_Metadata
PK (Schema_Name, Name)

*I created another metadata table to store data about columns called Columns_Metadata and it too has a Name column, a Table_Name column and unfortunately a Schema_Name column (Table_Name, Schema_Name are a foreign key referencing the Schema_Name,Name columns in the Tables_Metadata table) and a composed primary key of (Schema_Name, Table_Name, Name). This also is an identifying relationship.
Columns_Metadata
PK (Schema_Name, Table_Name, Name)

My question:
At the third level, do I need to create two columns Schema_Name and Table_Name in Columns_Metadata table and do I have to create columns I don't need each time I create a foreign key on an identifying relationship, or is there a better way to do it ?

A: First, let me express my opinion that the already existent design of the information schema and the sys schema are very elaborate, in-depth and intricate compared to your question which, if we forget for a moment that its CONTENT concerns metadata, is a very simple case of table design. Thus, I doubt you need to make another schema.
To answer your question: I would create an id column on Tables_Metadata, put the PK on id alone, and add a check constraint unique (schema_name,name).
Then, The Columns_Metadata table need only have two fields: Name, and Tables_Metadata_id FK to  Tables_Metadata.id


text:
Q: How to move the Child Classes into their respective files and build them as Shared Objects in Linux using CPP I was trying to implement Shared Objects so before that, I was trying to experiment with that and I got stuck in the following.
#include <iostream>
using namespace std;
class Animal{
    public:
        virtual void walk(void)=0;
};
class Human : public Animal{
    public:
        void walk(void){
            cout<<"Hi I am a human-being. I have only 2 legs!"<<endl;
        }
};

#include <iostream>
using namespace std;
class Animal{
    public:
        virtual void walk(void)=0;
};
class Tiger : public Animal{
    public:
        void walk(void){
            cout<<"Hi I am a Tiger. I have only 4 legs!"<<endl;
        }
};

So these are the 2 child classes in two separate files which I have named as "Tiger.cpp" and "Human.cpp"
and I have compiled them as "g++ -shared -fPIC -o libTiger.so Tiger.cpp" and for the other also.
#include <iostream>
#include "Human.cpp"
#include "Tiger.cpp"
using namespace std;

int main(void){
    Animal *aptr; // Declaring a pointer var. of type Animal class
    Human hobj; // Declaring an obj. of type Human
    Tiger tobj; // Declaring an obj. of type Tiger

    aptr = &hobj; // Assigning the addr. of Human object into aptr;
    aptr->walk(); // Will call the Human version of walk();

    aptr = &tobj;
    aptr->walk(); // Will call the Tiger version of walk();
    return 0;
}

Now when I tried to build the main() function using g++ it's showing an error as the Animal class is getting defined twice so I understood that and then I tried to move the Parent class into a separate header file and included that in the two-child class and removed from the main file but that's approach is also not working.
The error that is:
++ Animal.cpp -L/home//sugatak99/POC/ -llibrary -o Animal
In file included from Animal.cpp:3:
Tiger.cpp:3:7: error: redefinition of 'class Animal'
    3 | class Animal{
      |       ^~~~
In file included from Animal.cpp:2:
Human.cpp:3:7: note: previous definition of 'class Animal'
    3 | class Animal{
      |


text:
Q: Speed-efficient classification for complex vectors in MATLAB I am trying to optimize this piece of code and get rid of the nested loop implemented. I am finding difficulties in applying a matrix to pdist function
For example, 1+j // -1+j // -1+j // -1-j are the initial points and i am trying to detect 0.5+0.7j to with point it belong by min distance approach .
any help is appreciated
function result = minDisDetector( newPoints, InitialPoints)
result = [];
for i=1:length(newPoints)
    minDistance = Inf;
    for j=1:length(InitialPoints)

        X = [real(newPoints(i)) imag(newPoints(i));real(InitialPoints(j)) imag(InitialPoints(j))];
        d = pdist(X,'euclidean');

        if d < minDistance
            minDistance = d;
            index = j;
        end
    end
    result = [result; InitialPoints(index)];
end
end

A: You can use efficient euclidean distance calculation as listed in Speed-efficient classification in Matlab for a vectorized solution -
%// Setup the input vectors of real and imaginary into Mx2 & Nx2 arrays
A = [real(InitialPoints) imag(InitialPoints)];
Bt = [real(newPoints).' ; imag(newPoints).'];

%// Calculate squared euclidean distances. This is one of the vectorized
%// variations of performing efficient euclidean distance calculation using
%// matrix multiplication linked earlier in this post.
dists = [A.^2 ones(size(A)) -2*A ]*[ones(size(Bt)) ; Bt.^2 ; Bt];

%// Find min index for each Bt & extract corresponding elements from InitialPoints
[~,min_idx] = min(dists,[],1);
result_vectorized = InitialPoints(min_idx);

Quick runtime tests with newPoints as 400 x 1 & InitialPoints as 1000 x 1:
-------------------- With Original Approach
Elapsed time is 1.299187 seconds.
-------------------- With Proposed Approach
Elapsed time is 0.000263 seconds.

A: The solution is very simple. However you do need my cartprod.m function to generate a cartesian product.
First generate random complex data for each variable.
newPoints = exp(i * pi * rand(4,1));
InitialPoints = exp(i * pi * rand(100,1));

Generate the cartesian product of newPoints and InitialPoints using cartprod.
C = cartprod(newPoints,InitialPoints);

The difference of column 1 and column 2 is the distance in complex numbers. Then abs will find the magnitude of the distance.
A = abs( C(:,1) - C(:,2) );

Since the cartesian product is generated so that it permutates newPoints variables first like this:
 1     1
 2     1
 3     1
 4     1
 1     2
 2     2
 ...

We need to reshape it and get the minimum using min to find the minimum distance. We need the transpose to find the min for each newPoints. Otherwise without the transpose, we will get the min for each InitialPoints.
[m,i] = min( reshape( D, length(newPoints) , [] )' );

m gives you the min, while i gives you the indices. If you need to get the minimum initialPoints, just use:
result = initialPoints( mod(b-1,length(initialPoints) + 1 );

A: It is possible to eliminate the nested loop by introducing element-wise operations using the euclidean norm for calculating the distance as shown below.
    result = zeros(1,length(newPoints)); % initialize result vector
    for i=1:length(newPoints)
        dist = abs(newPoints(i)-InitialPoints); %calculate distances
        [value, index] =  min(dist);
        result(i) = InitialPoints(index);
    end


text:
Q: CSS - Stretch A Background Image - Not Maintaining Aspect Ratio How do you stretch a background image to completely fill a container without maintaining the aspect ratio like background-size: cover?

A: Simply apply the following CSS:
#image_container {
    background-size: 100% 100%;
}


text:
Q: Firebase Functions - Blurring image with ImageMagick fails with error code 4 I'm trying to write a basic firebase function which blurs images. The code is based mainly on the firebase function samples:
async function blurImage(filePath, bucketName, metadata) {
  const tempLocalFile = path.join(os.tmpdir(), filePath);
  const tempLocalDir = path.dirname(tempLocalFile);
  const bucket = admin.storage().bucket(bucketName);

  // Create the temp directory where the storage file will be downloaded.
  await mkdirp(tempLocalDir);

  // Download file from bucket.
  await bucket.file(filePath).download({destination: tempLocalFile});

  // Blur the image using ImageMagick.
  await spawn('convert', [tempLocalFile, '-channel', 'RGBA', '-blur', '0x8', tempLocalFile]);

  // Uploading the Blurred image.
  await bucket.upload(tempLocalFile, {
    destination: `${BLURRED_FOLDER}/${filePath}`,
    metadata: {metadata: metadata}, // Keeping custom metadata.
  });

  // Clean up the local file
  fs.unlinkSync(tempLocalFile);
}

I am trying to test this locally using firebase functions:shell and a testData.json file, however keep getting the error:
ChildProcessError: "convert C:\filePath -channel RGBA -blur 0x8 C:\filePath" failed with code 4
Can someone please tell me how to fix this?

A: If you use this code to blur the image instead of spawn, you'll see a more detailed version of the error:
const gm = require('gm').subClass({imageMagick: true});

...

await new Promise((resolve, reject) => {
    gm(tempLocalFile)
      .blur(0, 16)
      .write(tempLocalFile, (err, stdout) => {
        if (err) {
          console.error('Failed to blur image.', err);
          reject(err);
        } else {
          console.log(`Blurred image: ${filePath}`);
          resolve(stdout);
        }
    });
  });

The error will tell you that gm/convert binaries can't be found. Since you're using Windows, install the binaries and follow the instructions from this answer. I will note it here:

If you use gm on windows you should download windows binaries here and add gm.exe to your windows environment PATH variable. After that you have to restart your PC. Then install corresponding node package with npm install gm and it will work.

Additional References:
Another code example to blur images


text:
Q: Python PyQt: how to get mouse position x and y I'm trying to get the x and y position from a QCursor variable
def run(self):
   pos = QCursor.pos()
   print(pos.toPoint())

this prints the following:

PyQt6.QtCore.QPoint(523, 590)

if i try to print pos.x or pos.y it prints the following:

<built-in method x of QPoint object at 0x7fe85027b0b0

When i googled i found out the mapFromGlobal() method, but i couldn't make it work.
Is there any way to get X and Y values?
thanks

A: pos.x and pos.y are methods, not properties so they need to be called.
try:
pos.x()
pos.y()

Anytime you print an object in python and it looks like <built-in method ... that means the attribute is a method and needs to be invoked.

A: You are printing the PyQt6 object class.
If you are calling the X and Y functions from the QPoint class correctly and it won't work then try converting the X and Y values to a string.


text:
Q: Python plotting colors & labels for an unknown number of lines without loop Researching this, I have found answers which involved using an iterator and a loop to plot n sets of data.
Is there a way to do it without using a loop?
I have an array odata which contains n columns. The first column is the abscissa. I want to plot the rest.
I have a line of code like this:
plt.plot(odata[:,0],odata[:,1:],'-')

This does the plot, But I want to add my own colors and labels. How?

A: You can access the Line2D objects that are created using the return value of plt.plot, and set the legend directly based on that list:
labels = ['a', 'b', 'c']
lines = plt.plot(odata[:, 0], odata[:, 1:], '-')
plt.legend(lines, labels)

The number of labels and lines does not necessarily have to match. If there are fewer lines, some of the labels will be unused. If there are fewer labels, some of the lines will be unlabeled. Here is the legend guide in the documentation.
To seamlessly change the order of the colors, you would need to set the cycler in the global configuration via matplotlib.rc as in this example from the docs, or use the object-oriented API to do your plotting. Then you can use set_prop_cycle on your individual axes without messing around with the global settings.
Here are three approaches for setting the color cycler in order of increasing personal preference. Note that I am only showing how to set the color here, but you can also control the sequence of line styles and probably other attributes as well:

*

*Set the global configuration:
import matplotlib as mpl
from matplotlib import cycler
from matplotlib import pyplot as plt

labels = ['a', 'b', 'c']
colors = ['r', 'g', 'b']

mpl.rc('axes', prop_cycle=cycler('color', ['r', 'g', 'b', 'y']))

lines = plt.plot(odata[:, 0], odata[:, 1:], '-')
plt.legend(lines, labels)

*Set the global configuration, but using the rc_context context manager to make the changes effectively local to your plot:
import matplotlib as mpl
from matplotlib import cycler,rc_context
from matplotlib import pyplot as plt

labels = ['a', 'b', 'c']
colors = ['r', 'g', 'b']

with rc_context(rc={'axes.prop_cycle': cycler('color', ['r', 'g', 'b', 'y'])}):
    lines = plt.plot(odata[:, 0], odata[:, 1:], '-')
    plt.legend(lines, labels)

*Set up the plot using the object-oriented API to begin with, and apply changes only to the Axes that you actually want to modify:
from matplotlib import pyplot as plt

labels = ['a', 'b', 'c']
colors = ['r', 'g', 'b']

fig, ax = plt.subplots()
ax.set_prop_cycle('color', colors)
ax.plot(odata[:, 0], odata[:, 1:], '-')
ax.legend(labels)

I would recommend the object-oriented API as a general rule, especially within standalone scripts because it offers much greater flexibility, and also clarity in terms of knowing exactly what objects will be operated on.


text:
Q: CALayer memory management I have discovered that CALayer uses up a lot of memory. Since i have many images, removing the layer, I have seen it is very fast:
CALayer * l = [image1 layer];
[l setMasksToBounds:YES];
[l setCornerRadius:6.0];

Can I do this instead:
image1.layer.cornerRadius = 6.0;
                image1.layer.masksToBounds = YES;

Will it take up less memory?? Is there another way??

A: No it won't take up less memory. Storing a reference in a variable to an object doesn't copy the object - the two approaches are equivalent and both of them are correct.


text:
Q: Will ios app get killed if UIThread is blocked for long time? I have a strange issue. My app gets killed if my UI thread is blocked for long time ( say 10s). I want to repeatedly take screenshots after updating view in a loop. This is a time consuming process. But my app gets killed and no memory warning is received. My question is will my app get terminated if UI Thread is blocked for long time?

A: This is normal. Instead of letting apps freeze, iOS watches each app if they are taking a long time in the UI thread. Is there any reason you have to take the screenshots in a single run loop? Why not just setup a CADisplayLink callback and take just one screenshot every execution?


text:
Q: Task scheduler error:No such file or directory I had a python script which involves opening an absolute path and I used double backslash in the file name, and it works perfectly fine, and the batch file of it works too. But when i use windows tsak scheduler to run it, it shows
No such file or directory:H:\\gary\\file\\test.pdf
I tried to use forward slash to replace backward slash, this works perfectly fine in batch file too, but same error occurs when i run it in task scheduler:
No such file or directory: H:/gary/file/test.pdf
How can I solve this?


text:
Q: How can I limit the number of times a message is displayed while in a for loop in java?
The maximum number of rows that can be displayed for for loop statements is 11, regardless of reaching or exceeding the maximum value for the table.

for (double i = initialvalue; i <= finalvalue; i = i + increase) {
        System.out.println(tablevalue + "*" + i + "=" + tablevalue * i);

    }

I tried to limit it changing 'finalvalue' to 11 but that doesn't work and I get stuck, someone may can help me please?

A: Your loop looks fine. Please double check if i gets increased in each loop.
If you just want to reduce the number of outputs but still iterate the full length just use a variable to check for the number of outputs:
int maxOutputs = 11;
for (double i = initialvalue; i <= finalvalue; i = i + increase) {
        if(maxOutputs > 0){
           System.out.println(tablevalue + "*" + i + "=" + tablevalue * i);
           maxOutputs--;
        }
}


text:
Q: Mongoose does not post with express server I am experimenting with Mongoose and I have made this little project:
db.js
var db = mongoose.connect('mongodb://localhost/boeken', function(){
    console.log('mongoose connected');
});
module.exports = db;

Server.js
var express = require('express');
var bodyParser = require('body-parser');
var db = require('./db');
var Boek = require('./models/boeken');

var app = express();
app.use(bodyParser.json());

//1. Eenvoudige instructie
app.get('/api', function (req, res) {
    res.json({'Gebruik': 'voer een GET of POST-call uit naar /boeken'});
});

//2. POST-endpoint: nieuw boek in de database plaatsen
app.post('/api/boeken', function (req, res, next) {
    var boek = new Boek({
       titel: req.body.titel,
       auteur: req.body.auteur,
       ISBN: req.body.ISBN
    });
});

app.listen(3000, function () {
    console.log('server gestart op poort 3000');
});

models/boeken.js
var mongoose = require("mongoose");
var Boek = mongoose.model('Boek', {
   titel: {type: String, required: true},
   auteur: {type: String, required: true},
   ISBN: {type: String, required: true},
   date: {type: Date, required: true, default: Date.now()}
});
module.exports = Boek;

But when I post the following json with Postman it just says "Sending.." and in the browser it says Cannot POST /api/boeken and does not post the data:
{
"titel": "Hey",
"auteur": "You",
"ISBN": "1111"
}

What am I doing wrong? I am using mongod.exe Daemon in the background.
I am able to reach /api on the browser btw

A: You have to end the request for the post to work:
app.post('/api/boeken', function (req, res, next) {
    var boek = new Boek({
       titel: req.body.titel,
       auteur: req.body.auteur,
       ISBN: req.body.ISBN
    });
    boek.save((err, b) => {
      res.status(201).send(b); // end the request.
    });
});

Also, ensure your client is setting the Content-Type header to application/json.


text:
Q: Android Studio ActionBar width / icon locations I have a problem with my ActionBar that results in my menu icon being pressed up against the edge of the screen!

Below is a few code snippets of the styles I've tweaked and the declarations:
HomeActivity.xml
private TextView tvViewAll;
DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    //Nav Drawer
    mDrawerLayout = findViewById(R.id.drawer_layout);

    //custom shadow for menu drawer
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle (this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close);

    mDrawerLayout.addDrawerListener(mDrawerToggle);
    mDrawerToggle.syncState();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if(mDrawerToggle.onOptionsItemSelected(item)){
        return true;
    }

    return super.onOptionsItemSelected(item);
}

styles.xml
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:statusBarColor">@color/colorBackgroundBlack</item>
    <item name="android:navigationBarColor">@color/colorBackgroundBlack</item>
    <item name="actionMenuTextColor">@color/colorBackgroundBlackDark</item>
    <item name="colorPrimary">@color/colorBackgroundBlackDark</item>
    <item name="colorAccent">@color/colorPrimaryDark</item>
    <item name="colorButtonNormal">@color/ipBlue</item>
    <item name="toolbarNavigationButtonStyle">@color/ipGreen</item>
</style>

<style name="ActionBar.Solid.TMSA.NoTitle" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="displayOptions">useLogo|showHome</item>
    <item name="logo">@drawable/ic_ipaustralialogo</item>
    <item name="android:contentDescription">@string/ip_logo</item>
</style>

<style name="AppTheme.TMSA" parent="@style/AppTheme">
    <item name="actionBarStyle">@style/ActionBar.Solid.TMSA.NoTitle</item>
</style>

I don't remember touching the formatting layout for the ActionBar apart from the inclusion of the gov logo but I can't otherwise figure out why I'm getting this askew menu icon.
I have already considered doing a Toolbar approach but would prefer not to have to convert :P
Happy coding :)

A: ActionBarDrawerToggle sets its toggle icon on the ActionBar's navigation button. In an AppCompatActivity, the ActionBar is actually a Toolbar underneath, and that navigation button is styled with the style resource set on the theme's toolbarNavigationButtonStyle attribute.
In your theme, you've set a color resource on that attribute, rather than a style resource, and all of the values in the default style are lost, including the minWidth value, which is why your toggle is wrapped to the drawable's width.
If you want to modify some style values on the navigation button, you should create your own style resource, with the default style as its parent, set the desired attributes there, and specify that style as your theme's toolbarNavigationButtonStyle. For example:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
    <item name="toolbarNavigationButtonStyle">@style/Toolbar.Button.Navigation</item>
</style>

<style name="Toolbar.Button.Navigation" parent="Widget.AppCompat.Toolbar.Button.Navigation">
    <item name="android:background">@color/ipGreen</item>
</style>

If what you're actually trying to modify is the hamburger-arrow drawable, it has its own style that you can "sub-style", and change certain features in that. For example:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
    <item name="drawerArrowStyle">@style/DrawerArrowToggle</item>
</style>

<style name="DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@color/ipGreen</item>
</style>

Below is the full list of attributes available for modification in a drawerArrowStyle, should you want to customize any other of its properties.
<!-- The drawing color for the bars -->
<attr name="color" format="color"/>
<!-- Whether bars should rotate or not during transition -->
<attr name="spinBars" format="boolean"/>
<!-- The total size of the drawable -->
<attr name="drawableSize" format="dimension"/>
<!-- The max gap between the bars when they are parallel to each other -->
<attr name="gapBetweenBars" format="dimension"/>
<!-- The length of the arrow head when formed to make an arrow -->
<attr name="arrowHeadLength" format="dimension"/>
<!-- The length of the shaft when formed to make an arrow -->
<attr name="arrowShaftLength" format="dimension"/>
<!-- The length of the bars when they are parallel to each other -->
<attr name="barLength" format="dimension"/>
<!-- The thickness (stroke size) for the bar paint -->
<attr name="thickness" format="dimension"/>


text:
Q: Can't assign multiple values to 3 variables Request
curl -XGET http\://my_host\:9111/api/issues/search\?componentKeys\=my_poject\&facets\=severities\&p\=1\&ps\=1

Here response:
{
  "total": 10057,
  "p": 1,
  "ps": 1,
  "paging": {
    "pageIndex": 1,
    "pageSize": 1,
    "total": 10057
  },
  "effortTotal": 51031,
  "issues": [
    {
      "key": "AX0NVCNfENszTAxEgX5e",
      "rule": "java:S122",
      "severity": "MINOR",
      "component": "my_project:SomeFile.java",
      "project": "my_project",
      "line": 241,
      "hash": "1111111111",
      "textRange": {
        "startLine": 241,
        "endLine": 241,
        "startOffset": 0,
        "endOffset": 46
      },
      "flows": [],
      "status": "OPEN",
      "message": "At most one statement is allowed per line, but 2 statements were found on this line.",
      "effort": "1min",
      "debt": "1min",
      "author": "eugeniur",
      "tags": [
        "convention"
      ],
      "creationDate": "2021-11-11T06:40:05+0200",
      "updateDate": "2021-11-11T06:40:05+0200",
      "type": "CODE_SMELL",
      "scope": "MAIN"
    }
  ],
  "components": [
    {
      "key": "my_project",
      "enabled": true,
      "qualifier": "TRK",
      "name": "Parent",
      "longName": "Parent"
    },
    {
      "key": "my_project:MyFile.java",
      "enabled": true,
      "qualifier": "FIL",
      "name": "XStartDServerComponent.java",
      "longName": "MyFile.java",
      "path": "MyFile.java"
    }
  ],
  "facets": [
    {
      "property": "severities",
      "values": [
        {
          "val": "CRITICAL",
          "count": 5818
        },
        {
          "val": "MAJOR",
          "count": 1459
        },
        {
          "val": "BLOCKER",
          "count": 1286
        },
        {
          "val": "MINOR",
          "count": 1163
        },
        {
          "val": "INFO",
          "count": 331
        }
      ]
    }
  ]
}

Now I want to extract keys: "total", "issues", "facets.values".
So I try this in my bash script:
#!/bin/bash
readonly BASE_URL=http://my_host:9111/api
readonly PROJECT_KEY=my_project

read totalIssues facetsArr issuesArr < <(echo $(curl -XGET $BASE_URL/issues/search\?componentKeys\=$PROJECT_KEY\&facets\=severities\&p\=1\&ps\=1 |
                       jq -r '.total, .issues[], .facets[].values'))
echo "total      : $totalIssues"
echo "facetsArr     : $facetsArr"
echo "issuesArr  : $issuesArr"

But result is:
total      : 10057
facetsArr  : {
issuesArr  : "key": "AX0NVCNfENszTAxEgX5e", "rule": "java:S122", "severity": "MINOR", "component": "MyFile.java", "project": "myProject", "line": 241, "hash": "b68d3b4b390c81e2714d263b31acdd08", "textRange": { "startLine": 241, "endLine": 241, "startOffset": 0, "endOffset": 46 }, "flows": [], "status": "OPEN", "message": "At most one statement is allowed per line, but 2 statements were found on this line.", "effort": "1min", "debt": "1min", "author": "eugeniur", "tags": [ "convention" ], "creationDate": "2021-11-11T06:40:05+0200", "updateDate": "2021-11-11T06:40:05+0200", "type": "CODE_SMELL", "scope": "MAIN" } [ { "val": "CRITICAL", "count": 5818 }, { "val": "MAJOR", "count": 1459 }, { "val": "BLOCKER", "count": 1286 }, { "val": "MINOR", "count": 1163 }, { "val": "INFO", "count": 331 } ]

Why "facetsArr" get incorrect value?
The "facetsArr" must be:
facetsArr  : [ { "val": "CRITICAL", "count": 5818 }, { "val": "MAJOR", "count": 1459 }, { "val": "BLOCKER", "count": 1286 }, { "val": "MINOR", "count": 1163 }, { "val": "INFO", "count": 331 } ]

A: *

*Use string manipulation to insert a newline (\n) between each value, each line will now contain the value you're trying to catch

*Quote the jq command since it may contain spaces [info]

*Set IFS to a newline [info]

*Use read -d '' [docs]

-d delim
continue until the first character of DELIM is read, rather
than newline

Applying those fixes, the script will look like:
IFS=$'\n'
read -r -d '' totalIssues facetsArr issuesArr <<< "$( jq -r '"\(.total)\n\(.facets[].values)\n\(.issues[])"' input)"
echo "total      : $totalIssues"
echo "facetsArr  : $facetsArr"
echo "issuesArr  : $issuesArr"

Note: I've replaced the curl command with an actual file called input containing OP's JSON

The output will be:
total      : 10057
facetsArr  : [{"val":"CRITICAL","count":5818},{"val":"MAJOR","count":1459},{"val":"BLOCKER","count":1286},{"val":"MINOR","count":1163},{"val":"INFO","count":331}]
issuesArr  : {"key":"AX0NVCNfENszTAxEgX5e","rule":"java:S122","severity":"MINOR","component":"my_project:SomeFile.java","project":"my_project","line":241,"hash":"1111111111","textRange":{"startLine":241,"endLine":241,"startOffset":0,"endOffset":46},"flows":[],"status":"OPEN","message":"At most one statement is allowed per line, but 2 statements were found on this line.","effort":"1min","debt":"1min","author":"eugeniur","tags":["convention"],"creationDate":"2021-11-11T06:40:05+0200","updateDate":"2021-11-11T06:40:05+0200","type":"CODE_SMELL","scope":"MAIN"}

A: Slightly inefficient, but it would be much simpler to just parse the (small) response 3 times.
#!/bin/bash
readonly BASE_URL=http://my_host:9111/api
readonly PROJECT_KEY=my_project

response=$(curl -XGET "$BASE_URL/issues/search?componentKeys=$PROJECT_KEY&facets=severities&p=1&ps=1")

total=$(jq '.total' <<< "$response")
issues=$(jq '.issues' <<< "$response")
facets=$(jq '.facets[].values' <<< "$response")

# ...

Then you don't have to worry about constructing a single output with jq that bash must parse anyway.
(I've intentionally left the value of issues a JSON array, rather than a stream of issues, in the event that there is more than a single object in the array.)


text:
Q: Possible to see the query that gets executed on my database when using Parameterized Queries? Stemmed from this question:  How does SQLParameter prevent SQL Injection?
Is there any way that I can see what query is getting passed to my database and executed when I execute a parametrized query?
I don't have SQL Profiler available to me so that is not an option.  I was hoping there might be a way to do it from visual studio.  Possible?

A: Well, it's really no magic or no black art - a query like this in ADO.NET:
string sqlStmt = "SELECT * FROM dbo.Customers WHERE country = @country";

using(SqlConnection _conn = new SqlConnection("server=.;database=Northwind;integrated security=SSPI;"))
using(SqlCommand _cmd = new SqlCommand(sqlStmt, _conn))
{
    _cmd.Parameters.Add("@country", SqlDbType.VarChar, 100).Value = "Switzerland";

    DataTable results = new DataTable();

    using(SqlDataAdapter dap = new SqlDataAdapter(_cmd))
    {
        dap.Fill(results);
    }
}

will be translated into this on SQL Server:
exec sp_executesql N'SELECT * FROM dbo.Customers WHERE country = @country',N'@country varchar(100)',@country='Switzerland'

Basically, ADO.NET / SQL Server do not replace the parameters in the SQL statement string like many folks believe - it is actually passed to SQL Server as a parametrized query, along with a list of parameters and their values.
This SQL statement was taken from SQL Profiler - I don't know how else you could see that query...
Why can't you use SQL Profiler?? I mean - it's in every copy of SQL Server, there's even a free SQL Express Profiler for those using the free SQL Server Express editions.....

A: I don't believe you can access that sort of thing within Visual Studio since the translation would be happening internally inside ADO.NET libraries, but the answer marc_s posted above is correct.  You could verify this using SQL Server Management Studio by looking at the incoming transactions (if you had it available).


text:
Q: Object dot-notation is not working in React JSX Object dot-notation does not work here as value is undefined
<Input key={i} value={inputs.e} name={e} onNameChange={handleChange} />

this works
<Input key={i} value={inputs[e]} name={e} onNameChange={handleChange} />

this is signifying to me that initializing state like this may not be the best idea?
function _Login() {
  const inputNames = ["firstName", "lastName"];
  const [inputs, setInputs] = React.useState(
    inputNames
      .map((e) => ({ [e]: "" }))
      .reduce((accumulator, current) => ({ ...accumulator, ...current }), {})
  );
  const handleChange = (value: object) => setInputs({ ...inputs, ...value });

  return (
    <form>
      {inputNames.map((e, i) => (
        <Input key={i} value={inputs[e]} name={e} onNameChange={handleChange} />
      ))}
    </form>
  );
}

the reduce is just reducing an array of objects to one object
What is a good explanation for all of this?


text:
Q: How can I calculate the geometric center of a protein in Perl? I have a PDB file which contains information about a specific protein. One of the information it holds is the positions of the different atoms (xyz coordinates).
The file is the following https://files.rcsb.org/view/6U9D.pdb . With this file I want to calculate the geometric center of the atoms. In theory I know what I need to do, but the script I wrote does not seem to work.
The first part of the program, before the for loop, is another part of the assignment which requires me to read the sequence and convert it from the 3 letter nomenclature to the 1 letter one. The part that interests me is the for loop until the end. I tried to pattern match in order to isolate the XYZ coordinates. Then I used a counter that I had set up in the beginning which is the $k variable. When I check the output on cygwin the only output I get is the sequence 0 0 0 instead of the sum of each dimension divided by $k. Any clue what has gone wrong?
$k=0;
open (IN, '6U9D.pdb.txt');
%amino_acid_conversion = (
   ALA=>'A',TYR=>'Y',MET=>'M',LEU=>'L',CYS=>'C',
   GLY=>'G',ARG=>'R',ASN=>'N',ASP=>'D',GLN=>'Q',
   GLU=>'E',HIS=>'H',TRP=>'W',LYS=>'K',PHE=>'F',
   PRO=>'P',SER=>'S',THR=>'T',ILE=>'I',VAL=>'V'
);
while (<IN>) {
   if ($_=~m/HEADER\s+(.*)/){
   print ">$1\n"; }
   if ($_=~m/^SEQRES\s+\d+\s+\w+\s+\d+\s+(.*)/){
       $seq.=$1;
       $seq=~s/ //g;
   }
}

for ($i=0;$i<=length $seq; $i+=3) {
   print "$amino_acid_conversion{substr($seq,$i,3)}";
   if ($_=~m/^ATOM\s+\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+(\S+)\s+(\S+)\s+(\S+)/) {
       $x+=$1; $y+=$2; $z+=$3; $k++;
   }
}
print "\n";
#print $k;
$xgk=($x/$k); $ygk=($y/$k); $zgk=($z/$k);
print "$xgk $ygk $zgk \n";

A: I do not know bioinformatics but it seems like you should do something like this:
use feature qw(say);
use strict;
use warnings;

my $fn = '6U9D.pdb';
open ( my $IN, '<', $fn ) or die "Could not open file '$fn': $!";
my $seq = '';
my $x = 0;
my $y = 0;
my $z = 0;
my $k = 0;
while (<$IN>) {
   if ($_ =~ m/HEADER\s+(.*)/) {
       say ">$1";
   }
   if ($_=~m/^SEQRES\s+\d+\s+\w+\s+\d+\s+(.*)/){
       $seq .= $1;
   }
   if ($_ =~ m/^ATOM\s+\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+(\S+)\s+(\S+)\s+(\S+)/) {
       $x+=$1; $y+=$2; $z+=$3; $k++;
   }
}
close $IN;
$seq =~ s/ //g;
my %amino_acid_conversion = (
   ALA=>'A',TYR=>'Y',MET=>'M',LEU=>'L',CYS=>'C',
   GLY=>'G',ARG=>'R',ASN=>'N',ASP=>'D',GLN=>'Q',
   GLU=>'E',HIS=>'H',TRP=>'W',LYS=>'K',PHE=>'F',
   PRO=>'P',SER=>'S',THR=>'T',ILE=>'I',VAL=>'V'
);
my %unknown_keys;
my $conversion = '';
say "Sequence length: ", length $seq;
for (my $i=0; $i < length $seq; $i += 3) {
    my $key = substr $seq, $i, 3;
    if (exists $amino_acid_conversion{$key}) {
        $conversion.= $amino_acid_conversion{$key};
    }
    else {
        $unknown_keys{$key}++;
    }
}
say "Conversion: $conversion";
say "Unknown keys: ", join ",", keys %unknown_keys;
say "Number of atoms: ", $k;
my $xgk=($x/$k);
my $ygk=($y/$k);
my $zgk=($z/$k);
say "Geometric center: $xgk $ygk $zgk";

This gives me the following output:
[...]
Number of atoms: 76015
Geometric center: 290.744642162734 69.196842162731 136.395842938893


text:
Q: Why do coffeescript/jquery functions not trigger on DOM elements loaded via ajax, and how to fix? In a Rails 3.2 app I have a coffeescript function that toggles a css class when a link is clicked.
#coffeescript
jQuery ->
  $(".toggle-link").click ->
    $(this).toggleClass "selected"

#view
<%= link_to "toggle", my_path, class: "toggle-link" %>

This works fine.
But if I move the link into an ajaxified partial, e.g. for pagination, the jquery toggle stops working.
Why is this?
And how can it be fixed?

A: You need to use on for dynamic elements :
jQuery ->
  $(document).on 'click', ".toggle-link", ->
    $(this).toggleClass "selected"

(replace document with the container of your pages for better efficiency)

A: Use jQuery delegate function istead of click. http://api.jquery.com/delegate/
$('#paren-element-id').delegate('.toggle-link', click', function yourCallback(){});


text:
Q: FIRESTORE : Query Stream With Multiple where clause I hope you are well.
Here I have created a filter system in my application, I have a List filters on which I apply a forEach iteration and each String filter of this iteration is added in the Where clause which retrieve all the documents whose section field corresponds to one of the String filter of my Firestore query.
Here is what I tried to do:
Stream<List<Article>> filteredArticles() async* {
    List<String> filters = ['Sport', 'Santé'];
    final articlesCollection = FirebaseFirestore.instance.collection('REVIEWS');
    Stream<List<Article>> filteredArticles;
    Stream<QuerySnapshot> queryStream;

    await Future.forEach(filters, (filter) async {
      queryStream = articlesCollection
          .where('section', isEqualTo: filter)
          .orderBy('createdDate', descending: true)
          .snapshots();

      filteredArticles = queryStream.map(_convertToArticleList);
    });

    yield* filteredArticles;
  }

Method to map QuerySnapshot to List of article
List<Article> _convertToArticleList(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc) {
      return Article.fromMap(doc.data());
    }).toList();
  }

Method to convert firestore document data to a Article class
factory Article.fromMap(Map<String, dynamic> data) {
    final id = data[Fields.id];
    final imagesLinks = data[Fields.imagesLinks];
    final createdDate = data[Fields.createdDate];
    final date = data[Fields.date];
    final title = data[Fields.title];
    final details = data[Fields.details];
    final section = data[Fields.section];
    final link = data[Fields.link];
    final likes = data[Fields.likes];
    return Article(
      id: id,
      imagesLinks: imagesLinks,
      createdDate: createdDate,
      details: details,
      date: date,
      title: title,
      section: section,
      link: link,
      likes: likes,
    );
  }

Here is my database, it currently contains 3 documents of which 2 have the section field corresponding to one of the filters (Sport, Santé).

The problem is that I receive only one document instead of 2 and it depends on the position of the filter in the table, i.e. if I put Health in the first position of my table, I receive only the document with the section field corresponding to Health and the same if I put Sport in the first position of the table, I receive only the document with the section field corresponding to Sport instead of 2 at the same time.
My goal is to retrieve all the documents whose section field corresponds to one of the String filter in my List.

A: To check if a field's value is equal to any of the desired set of values, you can use Array-Membership based filtering: Source (Check the array queries section)
Use the filter list filters in your firestore query as follows:
queryStream = articlesCollection
          .where('section', arrayContainsAny: filters)
          .orderBy('createdDate', descending: true)
          .snapshots();

A: after a lot of research, I managed to find a solution by reading the FlutterFire documentation.
Here is what I did:
I changed the type of my field section from String to List<String> which contains just one element which is my keyword (my filter).
And then to filter my results, I use the parameter arrayContainsAny of the where method of Firestore on which I pass my List<String> filters
Stream<List<Article>> filteredArticles;
Stream<QuerySnapshot> queryStream;
List<String> filters = ['Sport', 'Health'];

  queryStream = articlesCollection
      .where(Fields.section, arrayContainsAny: filters)
      .orderBy(Fields.createdDate, descending: true)
      .snapshots();

  filteredArticles = queryStream.map(_convertToArticleList);

I hope this will help someone who will have the same problem as I have. Thanks


text:
Q: Which one? f string or using format in python3 Which one is better in python3?
They have same output but most of codes are using format instead F string.

a = "Test"
  print(f"this is for {a}")

or format?

print("This is for {}".format(a))

Some times when I used F string for Directory and file path I got some errors but there
were no problem with using format.

A: As pointed out in the comments, a good comparison of string formatting methods is provided on the Real Python website.
f-strings in many situations can be more readable and less human-error prone to code than other variants, but require Python >= 3.6, so may have to be avoided if backwards compatibility is required. In general they are a good choice though, up to a few gotchas that come up from time to time.
When nesting f-strings you have to be careful with quotation marks. This fails:
>>> f"Hello {"there"}"
  File "<stdin>", line 1
    f"Hello {"there"}"
                  ^
SyntaxError: invalid syntax

But using other quotation marks on the inside lets you get around this:
>>> f"Hello {'there'}"
'Hello there'

You cannot nest f-strings containing string literals deeper than that though, because you have no further different quotation marks to use.
Another gotcha I stumble across regularly is the restriction on not allowing backslashes in the f-string expression part, even if they are inside a string literal:
>>> f"Path: {'C:\Windows'}"
  File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash

You can get around that using an intermediate variable, or format():
>>> path = 'C:\Windows'
>>> f"Path: {path}"
'Path: C:\\Windows'

>>> "Path: {0}".format('C:\Windows')
'Path: C:\\Windows'

This is probably the issue you had with using f-strings to format paths. I personally tend to encounter this limitation when working with string literals that have newlines '\n' in them inside the f-string expression part.


text:
Q: Tier authors by getting the count of posts for each author I'm trying to make a tier for authors based on the total posts this author has posted in the past 30 days. I'm using Looker and Lookml for that, that what the company wants me to do, and when I saw the sql version of the lookml code I don't think that this is what I want.
SQL Code:
    (CASE
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      < 0 THEN '0'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      = 0 THEN '1'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      = 1 THEN '2'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      = 2 THEN '3'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      >= 3 AND (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      < 5 THEN '4'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      >= 5 THEN '5'
ELSE '6'
END) AS content2_authors_tiered__sort_,
    (CASE
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      < 0 THEN 'Below 0'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      = 0 THEN '0'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      = 1 THEN '1'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      = 2 THEN '2'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      >= 3 AND (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      < 5 THEN '3 to 4'
WHEN (SELECT
          (SELECT
          COUNT(content2.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          where content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID)
      >= 5 THEN '5 or Above'
ELSE 'Undefined'
END) AS content2_authors_tiered
FROM api-project-901373404215.DataMart.v_DataMart  AS datamart4
LEFT JOIN api-project-901373404215.Content.v_Content2  AS content2 ON lower(datamart4.GA_cmsNaturalId) = lower(content2.naturalid)
WHERE ((( content2.pub_date ) >= ((DATE_ADD(CURRENT_DATE('America/New_York'), INTERVAL -6 DAY))) AND ( content2.pub_date ) < ((DATE_ADD(DATE_ADD(CURRENT_DATE('America/New_York'), INTERVAL -6 DAY), INTERVAL 7 DAY))))) AND (content2.pub_date<=current_date() )
GROUP BY
    1,
    2
ORDER BY
    1
LIMIT 500

LookML Code:
    type: number
    hidden: yes
    sql: SELECT
          COUNT(${TABLE}.naturalid)
          FROM `api-project-901373404215.Content.v_Content2` AS content2
         ;;
  }

  dimension: total_posts_per_author {
    type: number
    hidden: yes
    sql: SELECT
           ${total_posts_dim}
          FROM `api-project-901373404215.Content.v_Content2` AS content2
          WHERE content2.author_naturalID = content2.author_naturalID
          GROUP BY content2.author_naturalID;;
  }

  dimension: authors_tiered {
    type: tier
    style: integer
    tiers: [0,1,2,3,5]
    sql: ${total_posts_per_author}
     ;;
  }

I have been trying a lot to get the code in the way I want without any luck


text:
Q: How do I solve the "FROM keyword not found where expected" error SELECT o.orderid,o.orderdate,
p.productid,o.orderid
o.productstandardprice,
o.productstandardprice*o.ordered_quantity as order_sales_price
FROM orders_t o and products_t p
WHERE p.productid = o.productid;

I have been getting the error  ORA-00923: FROM keyword not found where expected and I'm not sure what to do

A: Use JOIN properly. SELECT o.orderid, o.orderdate, p.productid, o.orderid, o.productstandardprice, o.productstandardprice*o.ordered_quantity as order_sales_price  FROM orders_t o join products_t p on p.productid = o.productid;

A: Your problem is the FROM clause where you should be using JOIN:
SELECT o.orderid, o.orderdate, p.productid, o.orderid,
       o.productstandardprice,
       (o.productstandardprice * o.ordered_quantity) as order_sales_price
FROM orders_t o JOIN
     products_t p
     ON p.productid = o.productid;

However, the only column coming from products_t is producctid -- and that is already in orders_t.  I doubt the JOIN is intended as a filter, so this should be equivalent:
SELECT o.orderid, o.orderdate, o.productid, o.orderid,
       o.productstandardprice,
       (o.productstandardprice * o.ordered_quantity) as order_sales_price
FROM orders_t o ;

That is, only orders_t seems necessary for this query.


text:
Q: Problem Confusion - Solution to SO DE I do not understand why my answer for
is wrong. Does anyone else get the same thing?

A: I get exactly the same result.
It is possible that the system is not grouping terms and leaving it as:
$$y(x) = e^{-x} + \dfrac{x e^x}{4} - \dfrac{e^x}{4} + e^{-x} x \ln(x)$$
It is even possible they have $\ln x$ as the more general $\log x$ with natural log understood.
At least you have the correct result and can share that with the instructor.


text:
Q: Is it possible to access static methods of a class by multiple object instances simultaneously? Example:
ThisClass.staticMethod(Object... parameters);

will be accessed by multiple instances of other objects and simultaneously.
Will there be any dependencies with this other objects when they are using the same static method at the same time?

A: Only if the method uses static Objects or the arguments are shared by the other instances.
Example: Math.max(int a, int b) is a static method but does not use any static objects, so there are no dependencies.
Example 2: Here all invocations share the same result variable, two parallel calls to staticMethod can cause wrong results.
private static int result = 0;
private static int staticMethod(Object... args)
{
      result = args.length;
      //Do Something
      return result;
}

Example 3: This one is Thread safe if none of the arguments are shared, each invocation has its own instance of result.
private static int staticMethod(Object... args)
{
    int result = 0;
    result = args.length;
    //Do something
    return result;
}

Example 4: This uses the class as a lock to prevent parallel access to the class functions. Only one call to staticMethod executes all others wait
private static int result = 0;
private static synchronized int staticMethod(Object... args)
{
      result = args.length;
      //Do Something
      return result;
}

A: Obviously, all users of the method depend on the class, if this is what you mean.
Moreover, if they are really calling the method simultaneously (i.e. from multiple threads), you may get concurrency problems, depending on what the method actually does. Show us the code, and we may be able to tell more.

A: A code fragment running concurrently by multiple threads has the potential of causing race conditions, regardless of where this code is placed (static/non-static method).
You must make sure that the data manipulated by the code tolerates concurrent accesses, and synchronize the code properly if needed.

A: All objects that call the static methods will be dependent on the class methods, but they won't have dependencies with each other.  If it's possible that your static method will be called by objects from different threads, you will need to make sure that your static method is thread-safe, i.e., you need to using locking to ensure that only one thread at a time accesses any non-stack memory.


text:
Q: Modifying y-axis label in pdf Diagram I have mislabelled the y-axis in my pdf graph that I generated from an Matlab file.
Unfortuantely, I cant find anymore the data that I used to generate the graph. So I am wondering if there is an free tool that allows me to rename the y-axis in my pdf diagram?
Are there any free tools available that could be helpful or is this something "impossible"
to do?
Many thanks for your help,
Andrea

A: Inkspace is good, for this purpose. It is a free tool for editing vector graphics files, similar to Illustrator or CorelDraw.

A: You can alternatively import the file into photoshop and edit it with the text tools (and eraser) and then print it back into a .pdf.


text:
Q: How many numbers are there between 100 and 1000 in which all the digits are distinct? How many numbers are there between 100 and 1000 in which all the digits are distinct?
My mathematics textbook says the answer is 648.
My analysis:-
The number at the hundred's place can be chosen in 9 ways(as zero is not possible)
The number at the ten's place can be chosen in 9 ways(the number at the hundred's place is no longer available but zero is now available).
The number at the one's place can be chosen in 8 ways(the number at the hundred's and ten's place is not available but zero is available).
So by the multiplication rule, the total number of ways would seem to be 9*9*8=648.
But the hundred's place can have 1 at its place, ten's can have 0 and ones can have 0. So 100 is a possibility but the question is asking for numbers between 100 and 1000.As a result of that, 100 has to be removed. Therefore, the correct answer is 648-1=647.
I have checked and rechecked my method and can't find anything wrong with it. Can someone please help verify my answer?

A: The answer $648$ is correct.
There are nine choices for the hundreds place. There are also nine choices for the tens place (it can be any digit except what you chose for the hundreds).
Finally, there are eight choices for the ones place, regardless of what the tens place is. If the tens place is a zero, then you can't choose either the hundreds place digit or zero for the ones place. If the tens digit is not zero, then you can pick zero for the ones place, just not the digits in the hundreds or tens place.

A: The digits in 100 are not distinct. So, 100 is sorted out by your algorithm.


text:
Q: Question on Mean value theorem involving ln Show that for all $x\in\mathbf{R}$, $|e^x-1-x|\le \frac{x^2}{2}e^{|x|}$
This can be written as
$-(\frac{x^2}{2}e^{|x|})\le e^x-1-x \le (\frac{x^2}{2}e^{|x|})$
I have started by taking $\ln$ on both sides.
$\ln \frac{2}{x^2 e^{|x|}} \le \ln(e^x-1-x) \le \ln \frac{x^2}{2}e^{|x|}$
$\ln 2-2\ln x-|x|  \le \ln(e^x-1-x) \le 2\ln x+|x|-\ln2$
We get 2 inequalities,
$\ln 2-2\ln x-|x|  \le \ln(e^x-1-x)$ and
  $\ln(e^x-1-x) \le 2\ln x+|x|-\ln2$
Afterwards, I am a bit lost.


text:
Q: Run Jmeter tests with direct call only I added the Jmeter plugin to my project and now its load tests are running together with the maven build.
  <!-- Jmeter  -->
            <plugin>
                <groupId>com.lazerycode.jmeter</groupId>
                <artifactId>jmeter-maven-plugin</artifactId>
                <version>2.9.0</version>
                <executions>
                    <execution>
                        <id>jmeter-tests</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>jmeter</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

I wanted Jmeter tests to run just by running the command:
mvn jmeter:jmeter -Pjmeter

I didn't want it to run when performing any maven lifecycle like for example:
mvn install

As the tests are performed in a Restful API the load test will be performing POST and creating data in the database every time a maven lifecycle is run.
Can someone help me?

A: Just put your JMeter Maven Plugin declaration under the jmeter profile like:
<profiles>
    <profile>
        <id>jmeter</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>com.lazerycode.jmeter</groupId>
                    <artifactId>jmeter-maven-plugin</artifactId>
                    <version>3.0.0</version>
                    <executions>
                        <!-- Generate JMeter configuration -->
                        <execution>
                            <id>configuration</id>
                            <goals>
                                <goal>configure</goal>
                            </goals>
                        </execution>
                        <!-- Run JMeter tests -->
                        <execution>
                            <id>jmeter-tests</id>
                            <goals>
                                <goal>jmeter</goal>
                            </goals>
                        </execution>
                        <!-- Fail build on errors in test -->
                        <execution>
                            <id>jmeter-check-results</id>
                            <goals>
                                <goal>results</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

this way JMeter maven plugin will be executed only if you explicitly specify the jmeter profile
Demo:

More information:

*

*Using maven profiles to control build execution

*How to Use the JMeter Maven Plugin


text:
Q: Stored Procedure to Insert the result of a parameterized OPENQEURY into a local table So this is "fun", and by "fun" I mean mindbending.  I have managed to:

*

*Feed parameters to OPENQUERY and get results like this:
Declare @MyString    varchar(max)
,       @TheDateAfter datetime

set     @TheDateAfter = DATEADD(d, 1, @TheDate)
set     @MyString =  'Select * from "ORACLEDB"."' + @TheTable + '"
                     WHERE "EDITTIME" > to_date(''' +         convert(varchar(30),@TheDate,120) + ''', ''YYYY-MM-DD HH24:MI:SS'')
                     AND "EDITTIME" < to_date(''' +         convert(varchar(30),@TheDateAfter,120) + ''', ''YYYY-MM-DD HH24:MI:SS'')'
set     @MyString =  N'select * from   openquery  (LINKEDSERVER
                                              ,    ''' + REPLACE(@MyString, '''',         '''''') + '''
                                              )'

Exec(@MyString)

*Return the results in a number of ways, including a stored procedure which takes my parameters:
sp_get_Deltas @TheDate = '1/2/03', @TheTable = 'Table'

But I have thus been unable to insert those results into a table.  I think that if I can have the sproc return as a table, but the solution I found turns the query into a string and putting those results into a table have only resulted in errors.
The other thing I tried was to put the "Insert Into" portion in with the string, but that throws errors about "labels already being used", or that the Oracle provider doesn't have access to write to my SQL tables.  Here was my attempt.
    Declare @MyString    varchar(max)
    ,       @TheDateAfter datetime

    set     @TheDateAfter = DATEADD(d, 1, @TheDate)
    set     @MyString =  'Insert Into [HO-RS1].[DELTAS].[dbo].[' + @TheTable +         ']
                         Select * from "ORACLEDB"."' + @TheTable + '"
                         WHERE "EDITTIME" > to_date(''' +         convert(varchar(30),@TheDate,120) + ''', ''YYYY-MM-DD HH24:MI:SS'')
                         AND "EDITTIME" < to_date(''' +         convert(varchar(30),@TheDateAfter,120) + ''', ''YYYY-MM-DD HH24:MI:SS'')'
    set     @MyString =  N'select * from   openquery  (LINKEDSERVER
                                                  ,    ''' + REPLACE(@MyString, '''',         '''''') + '''
                                                  )'

    Exec(@MyString)

I tried some other things that I didn't think would work, just to rule them out:
    Insert Into DELTAS.TABLE
    Select * From sp_get_Deltas @TheDate = '1/2/03', 'TheTable'

... and various ludicrous stuff such as that.
Can somebody show me how I can apply the results of the first query into an "Insert Into DELTAS.TABLE ....." statement?
I know I'm close, but I've been wandering in circles for a little while now and I feel like I'm stepping on my tail.
Thanks!

A: You're almost there. This works for normal stored procedures. Lets see if it works for SP's that use mindbending OPENQUERY
Insert Into DELTAS.TABLE
EXEC sp_get_Deltas @TheDate = '1/2/03', 'TheTable'

Of course the column list from the EXEC must match the target table.
If you get errors please post them.